Export (0) Print
Expand All

How to: Create a basic provider-hosted app for SharePoint

apps for SharePoint

Learn how to create a basic provider-hosted app for SharePoint with the Office Developer Tools for Visual Studio 2013, how to interact with SharePoint 2013 sites by using the SharePoint CSOM, and how to implement OAuth in an app for SharePoint.

Applies to:

A provider-hosted app for SharePoint consists of both an app for SharePoint that is deployed directly to a SharePoint 2013 site and a separately deployed web application. If the provider-hosted web application is an ASP.NET web application, you can use the Office Developer Tools for Visual Studio 2013 to create both components of a provider-hosted app for SharePoint.

Create an App for SharePoint 2013 project

  1. In Visual Studio 2013, choose File, New, Project.

  2. In the New Project wizard, expand the Visual C# node, and then expand the Office/SharePoint node.

  3. Choose Apps, and then choose to create an App for SharePoint project.

  4. Name the project SampleApp.

  5. Save the project in a location you choose, and then choose OK.

  6. Enter the URL for your Office 365 Developer Site. Select the Provider-hosted hosting option, and then choose the Next button.

  7. Under Which type of web application project do you want to create?, choose ASP.NET Web Forms Application. Choose the Next button.

  8. Under How do you want your app to authenticate?, choose Use Windows Azure Access Control Service (for SharePoint cloud apps).

  9. In the wizard, choose Finish. You may be prompted to sign in to your Office 365 Developer Site. Use the account (in the *.onmicrosoft.com domain) that you created when you signed up for your Developer Site. Much of the configuration is done when the solution opens. Two projects are created in the Visual Studio 2013 solution, one for the app for SharePoint and the other for the ASP.NET web application.

  1. Open the AppManifest.xml file. On the Permissions tab, specify the Site Collection scope and the Read permission level.

  2. Add the following HTML and ASP.NET controls inside the <body> tag of the Pages/Default.aspx file of your web application. This sample uses the UpdatePanel control to enable partial page rendering.

    <form id="form1" runat="server">
        <div>
            <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="true" />
          <asp:UpdatePanel ID="PopulateData" runat="server" UpdateMode="Conditional">
            <ContentTemplate>   
       
            <table border="1" cellpadding="10">
             <tr><th><asp:LinkButton ID="CSOM" runat="server" Text="Populate Data" OnClick="CSOM_Click" /></th>
                 </tr>
    
             <tr><td>
            <h2>SharePoint Site</h2>
            <asp:Label runat="server" ID="WebTitleLabel"/>
            <h2>Current User:</h2>
            <asp:Label runat="server" ID="CurrentUserLabel" />
            <h2>Site Users</h2>
            <asp:ListView ID="UserList" runat="server">     
                <ItemTemplate ><asp:Label ID="UserItem" runat="server" Text="<%# Container.DataItem.ToString()  %>"></asp:Label><br /></ItemTemplate>
            </asp:ListView>
            <h2>Site Lists</h2>
            <asp:ListView ID="ListList" runat="server">
                <ItemTemplate ><asp:Label ID="ListItem" runat="server" Text="<%# Container.DataItem.ToString()  %>"></asp:Label><br /></ItemTemplate>
            </asp:ListView>
            </td>
                  
            </tr>
            </table>
            </ContentTemplate>
          </asp:UpdatePanel>
        </div>
        </form>
    
  3. Add the following declarations to the Default.aspx.cs file of your web application.

    using Microsoft.SharePoint.Client;
    using Microsoft.IdentityModel.S2S.Tokens;
    using System.Net;
    using System.IO;
    using System.Xml;
    
  4. In the Default.aspx.cs file of your web application, add these variables inside the System.Web.UI.Page class.

    SharePointContextToken contextToken;
    string accessToken;
    Uri sharepointUrl;
    string siteName;
    string currentUser;
    List<string> listOfUsers = new List<string>();
    List<string> listOfLists = new List<string>();
    
    
  5. Add the RetrieveWithCSOM inside the SampleAppWeb namespace. This method uses the SharePoint CSOM to retrieve information about your site and display it on the page.

    // This method retrieves information about the host web by using the CSOM.
            private void RetrieveWithCSOM(string accessToken)
            {
    
                if (IsPostBack)
                {
                    sharepointUrl = new Uri(Request.QueryString["SPHostUrl"]);
                }
                
    
                ClientContext clientContext =
                        TokenHelper.GetClientContextWithAccessToken(
                            sharepointUrl.ToString(), accessToken);
    
    
                //Load the properties for the web object.
                Web web = clientContext.Web;
                clientContext.Load(web);
                clientContext.ExecuteQuery();
    
                //Get the site name.
                siteName = web.Title;
    
                //Get the current user.
                clientContext.Load(web.CurrentUser);
                clientContext.ExecuteQuery();
                currentUser = clientContext.Web.CurrentUser.LoginName;
    
                //Load the lists from the Web object.
                ListCollection lists = web.Lists;
                clientContext.Load<ListCollection>(lists);
                clientContext.ExecuteQuery();
    
                //Load the current users from the Web object.
                UserCollection users = web.SiteUsers;
                clientContext.Load<UserCollection>(users);
                clientContext.ExecuteQuery();
    
                foreach (User siteUser in users)
                {
                    listOfUsers.Add(siteUser.LoginName);
                }
    
    
                foreach (List list in lists)
                {
                    listOfLists.Add(list.Title);
                }
            }
    
    
  6. Add the CSOM_Click method inside the SampleAppWeb namespace. This method triggers the event that occurs when the user clicks on the Populate Data link.

    protected void CSOM_Click(object sender, EventArgs e)
            {
                string commandAccessToken = ((LinkButton)sender).CommandArgument;
                RetrieveWithCSOM(commandAccessToken);
                WebTitleLabel.Text = siteName;
                CurrentUserLabel.Text = currentUser;
                UserList.DataSource = listOfUsers;
                UserList.DataBind();
                ListList.DataSource = listOfLists;
                ListList.DataBind();
        
            }
    
    
  7. Replace the existing Page_Load method with this one. The Page_Load method uses methods in the TokenHelper.cs file to retrieve the context from the Request object and obtain an access token from ACS.

    // The Page_load method fetches the context token and the access token. 
    // The access token is used by all of the data retrieval methods.
            protected void Page_Load(object sender, EventArgs e)
            {
    
                string contextTokenString = TokenHelper.GetContextTokenFromRequest(Request);
    
                if (contextTokenString != null)
                {
                    contextToken =
                        TokenHelper.ReadAndValidateContextToken(contextTokenString, Request.Url.Authority);
    
                    sharepointUrl = new Uri(Request.QueryString["SPHostUrl"]);
                    accessToken =
                        TokenHelper.GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken;
                    CSOM.CommandArgument = accessToken;
    
                }
                else if (!IsPostBack)
                {
                    Response.Write("Could not find a context token.");
                    return;
                }
            }
    
    
  8. The Default.aspx.cs file should look like this when you’re done.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    
    using Microsoft.SharePoint.Client;
    using Microsoft.IdentityModel.S2S.Tokens;
    using System.Net;
    using System.IO;
    using System.Xml;
    
    namespace SampleAppWeb
    {
        public partial class Default : System.Web.UI.Page
        {
            SharePointContextToken contextToken;
            string accessToken;
            Uri sharepointUrl;
            string siteName;
            string currentUser;
            List<string> listOfUsers = new List<string>();
            List<string> listOfLists = new List<string>();
            protected void Page_PreInit(object sender, EventArgs e)
            {
                Uri redirectUrl;
                switch (SharePointContextProvider.CheckRedirectionStatus(Context, out redirectUrl))
                {
                    case RedirectionStatus.Ok:
                        return;
                    case RedirectionStatus.ShouldRedirect:
                        Response.Redirect(redirectUrl.AbsoluteUri, endResponse: true);
                        break;
                    case RedirectionStatus.CanNotRedirect:
                        Response.Write("An error occurred while processing your request.");
                        Response.End();
                        break;
                }
            }
    
            protected void CSOM_Click(object sender, EventArgs e)
            {
                string commandAccessToken = ((LinkButton)sender).CommandArgument;
                RetrieveWithCSOM(commandAccessToken);
                WebTitleLabel.Text = siteName;
                CurrentUserLabel.Text = currentUser;
                UserList.DataSource = listOfUsers;
                UserList.DataBind();
                ListList.DataSource = listOfLists;
                ListList.DataBind();
    
            }
    
            // This method retrieves information about the host web by using the CSOM.
            private void RetrieveWithCSOM(string accessToken)
            {
    
                if (IsPostBack)
                {
                    sharepointUrl = new Uri(Request.QueryString["SPHostUrl"]);
                }
    
    
                ClientContext clientContext =
                        TokenHelper.GetClientContextWithAccessToken(
                            sharepointUrl.ToString(), accessToken);
    
    
                //Load the properties for the web object.
                Web web = clientContext.Web;
                clientContext.Load(web);
                clientContext.ExecuteQuery();
    
                //Get the site name.
                siteName = web.Title;
    
                //Get the current user.
                clientContext.Load(web.CurrentUser);
                clientContext.ExecuteQuery();
                currentUser = clientContext.Web.CurrentUser.LoginName;
    
                //Load the lists from the Web object.
                ListCollection lists = web.Lists;
                clientContext.Load<ListCollection>(lists);
                clientContext.ExecuteQuery();
    
                //Load the current users from the Web object.
                UserCollection users = web.SiteUsers;
                clientContext.Load<UserCollection>(users);
                clientContext.ExecuteQuery();
    
                foreach (User siteUser in users)
                {
                    listOfUsers.Add(siteUser.LoginName);
                }
    
    
                foreach (List list in lists)
                {
                    listOfLists.Add(list.Title);
                }
            }
    
            protected void Page_Load(object sender, EventArgs e)
            {
    
                string contextTokenString = TokenHelper.GetContextTokenFromRequest(Request);
    
                if (contextTokenString != null)
                {
                    contextToken =
                        TokenHelper.ReadAndValidateContextToken(contextTokenString, Request.Url.Authority);
    
                    sharepointUrl = new Uri(Request.QueryString["SPHostUrl"]);
                    accessToken =
                        TokenHelper.GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken;
                    CSOM.CommandArgument = accessToken;
    
                }
                else if (!IsPostBack)
                {
                    Response.Write("Could not find a context token.");
                    return;
                }
            }
        }
    }
    
    
  9. Use the F5 key to deploy and run your app. If you see a Security Alert window that asks you to trust the self-signed Localhost certificate, choose Yes.

    Choose Trust It on the consent page to grant permissions to the app and then click on the name of your app in the Apps list that will appear on the Site Contents page. When you launch the app, you'll see a page containing the table shown in Figure 1. Choose Populate Data to see summary information about your SharePoint 2013 site.

    Figure 1. Launch page of the basic provider-hosted app sample

    Basic self-hosted app launch page

See Deploying and installing apps for SharePoint: methods and options for instructions on how to publish your app to a SharePoint 2013 site.

Was this page helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft