First step of the of the app development is to correctly get the access to SharePoint client context. I have struggling with develop a simple model to initialize the SharePoint Client context. Most of the App development include ASP Master pages. So I need to figure out a working model for app development.
First you need to know how SharePoint offer the contextString. contextString Offers when SharePoint is getting redirect from appredirect.aspx url.
that point we need to capture the contextString and generate either AccessToken or RefreshToken and save it for access the SharePoint Client Context in later time. other wise it will result in generating the error The parameter 'token' cannot be a null or empty string (This is nasty error which drove me crazy)
Normally AccessToken is valid for 12 hours and RefreshToken is valid for 6 months.
In my approach I used another key which is called as CacheKey to identify the user uniquely. Therefore I use this value to maintain a cookie based on user the user.
Following shows my approach to do this. If you have master page you need to put the code in the onInit() rather than page load.
this is code for button click
Note: In the middle of the app if the context broken due to expiation or some other case you need to initialize the app from the AppRedirect therefore you can
var hostWeb = Page.Request["SPHostUrl"];
var val = TokenHelper.GetAppContextTokenRequestUrl(hostWeb, Server.UrlEncode(Request.Url.ToString()));