SharePoint app tools in Visual Studio 2013 preview, the new SharePointContext helper!

imageToday at the build conference  the new preview of Visual Studio 2013 was released.  Along with it there were some nice advances in the tools for building SharePoint and Office applications also.

You can read the full post about the tools here.

The most interesting of these is the new out of the box project template option for creating a ASP.Net MVC based application.  It asks you during the project creation wizard for provider hosted and autohosted apps.

image

When you create a totally out of the box app using the wizard and picking this setting you get a very familiar looking app if you have ever create an ASP.Net MVC app before.

image

Now that is pretty handy being able to create these via the wizard, but what is even cooler is a particular improvement to some of the additional helper classes you get in the new template.

Namely the SharePointContext class.

This is a new class that is added in the new out of the box template is helps you manage your SharePoint context across page requests.

image

When SharePoint “starts” an app i.e. when a user launches an app, SharePoint packs up some information about that user and passes it along to the app as a POST parameter. This is called the ContextToken and it contains OAuth tokens/information that you need in order to make calls back to SharePoint. Now the trick is that SharePoint passes it to your app when it launches and then it is up to you to do something like cache it so that in subsequent page requests your app has that context and can reuse it.  The basic auth token in it is good for 12 hours & it also contains a refresh token that can be used to get new auth tokens for up to 6 months.

The first question people that are new to SharePoint app development ask me is “my app breaks on the second page request, why?” … it is usually because they don’t realize its totally up to them to cache these very important tokens.

The new MVC template in the VS 2013 preview includes the SharePointContext class that helps with this whole process & gives you an out of the box experience that doesn’t totally suck.

In a new project you will see a line of code that looks like this:

var spContext = SharePointContextProvider.Current.GetSharePointContext(HttpContext);

This is creating a new context object & initializing it using all that good information passed as a POST parameter and some querystring parameters too.

Then you can use that context to get Client Side Object Model (CSOM) instances really easily like this:

using (var clientContext = spContext.CreateUserClientContextForSPHost())
{
    if (clientContext != null)
    {
        spUser = clientContext.Web.CurrentUser;

        clientContext.Load(spUser, user => user.Title);

        clientContext.ExecuteQuery();

        ViewBag.Message = spUser.Title;
    }
}

Now this is not all that different from what you used to do on the first request to your SharePoint app.  TokenHelper helped you create a CSOM instance from the request details. However the SharePointContext goes further.

When you make the GetSharePointContext(HttpContext) call the class checks the ASP.Net Session state for an existing context. If it doesn’t find one then it creates a new one based on the information passed and then stashes it in Session state for subsequent requests.

Then on subsequent requests, when SP hasn’t passed any new tokens, the GetSharePointContext(HttpContext) will return you back the context from Session state. It will also deal with when and if tokens expire.

(Update 6/28 – added this paragraph)
Additionally the provided [SharePointContextFilter] attribute on controller actions ensures a context is passed from SharePoint. If not it will redirect the user back to SharePoint to obtain one.  Why is this important?  Well, if someone bookmarks your app then when they use that bookmark the context wont be passed & in that case you need to bounce them via SharePoint to go and get one for the first request.  The [SharePointContextFilter] automates that for you.  This is only available in the MVC project however. Very handy indeed not having to wire up this flow yourself!

You don’t need to worry about writing any of this however, as it is all done for you in the helper class.  Go take a look in the GetSharePointContext(HttpContextBase httpContext) method if you are interested in seeing how it works & more importantly run your app and set through the code so you can see how it runs and works.

Once you have a SharePointContext object you can take a look in it and find the CacheKey (used for uniquely identifying this in the cache), ContextToken (for making calls back to SP), RefreshToken (for getting more access tokens when they expire) and other properties it stashes for you like the site language, SP product version etc…

image

The way in which it is structured is also very friendly for replacing if you want to roll a different caching technique.  You could replace the existing implementation or create your own SharePointContextProvider class that managed the caching.

The library comes with implementations for both on-prem and cloud scenarios:

  • SharePointAcsContextProvider – Office 365
  • SharePointHighTrustContextProvider – On-Prem apps using the high trust S2S auth model

Summary

This is simple but very timely additional to the out of the box templates in VS!

Just a few weeks ago at TechEd North America I did a tips and tricks session for app developers and Demo #2 was showing a simpler version of essentially the same thing.  The main difference in the helper class I showed in that demo was that it will work for ASP.Net forms apps as well as MVC (Update 6/27: The newly shipped helper does support ASP.Net Forms based apps too) … however it doesn’t deal with the high-trust S2S scenario for on-prem only apps.

Shout out to @chakkaradeep for the great work on the VS SharePoint tools (a topic near and dear) & for taking the time to watch my TechEd session and let me know they were releasing this helper today!

Update 6/27/2013: Mike Morton did a great session at build yesterday that walks through a whole lot of this. What it here: http://channel9.msdn.com/Events/Build/2013/3-319

To try this out for yourself you will need to get the VS 2013 preview bits: http://www.microsoft.com/visualstudio/eng/2013-downloads

You will also need a SharePoint site to try it out in and I recommend signing up for a trial Office 365 site here: http://msdn.microsoft.com/en-US/library/office/apps/fp179924

Thanks!

-CJ

3 thoughts on “SharePoint app tools in Visual Studio 2013 preview, the new SharePointContext helper!

  1. Chakkaradeep

    Thanks for the write-up (and mention) Chris 🙂

    The SharePointContext class is available for both Web Forms and MVC templates. The only difference is that SharePointContextFilterAttribute, an action filter attribute is available only in MVC applications. This filter attribute helps you to initialize the context and manage it across different views in a MVC app. This filter attribute can be applied to a specific view or to the controller itself.

    In Web Forms (for this preview) you will need to implement something similar in your Page_PreInit function.

    Reply
  2. Pingback: Introducing SharePointContext for Provider-Hosted SharePoint Apps! - Kirk Evans Blog - Site Home - MSDN Blogs

  3. Dan

    Hi.

    When I create a SharePoint app directly from the template, right out of the box, I can include my service bus string in the settings and I can hit my breakpoint on a remote event receiver. Awesome!

    Now, I am trying to call:

    SharePointContextProvider.Current.GetSharePointContet(System.Web.HttpContext.Current);

    But the problem is that in this default WCF service in my web application that it created, out of the box, HttpContext.Current is always null.

    I tried putting in my web.config and [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] on the service class but this doesn’t help.

    Any suggestions? Can I get a SharePointContextProvider somehow without an HttpContext??

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *