11 out of 14 rated this helpful - Rate this topic

How to: Create a basic autohosted app for SharePoint

apps for Office

Published: July 16, 2012

Create a basic autohosted app for SharePoint with the Office Developer Tools for Visual Studio 2012, interact with SharePoint 2013 websites by using the REST/OData web service, and implement OAuth in an app for SharePoint.

Applies to:  apps for SharePoint | Office 365 | SharePoint Server 2013 

Watch the video: Windows Azure auto-provisioned apps for SharePoint 2013

Videos

An autohosted app for SharePoint contains at least one Windows Azure Web Site that can be launched from a SharePoint 2013 host web, and may also include SharePoint components on an app web and a SQL Server database. The simple example in this article contains a Windows Azure Web Site and no SharePoint or SQL Server components.

Note Note

The infrastructure for autohosted apps will remain in preview status for a period of time after SharePoint 2013 releases. Autohosted apps (which includes all apps that depend on Access) will not be accepted by the Office Store during this preview phase. We will update dev.office.com with information about autohosted apps as it becomes available.

Development of an autohosted app is essentially the same as development of a provider-hosted app that includes a remote ASP.NET web application or a remote SQL Server or Windows Azure SQL Database database. The differences between the two types are in how the remote components are deployed. With an autohosted app, developers do not have to deploy the remote components separately, and they do not have to design and maintain a system of tenant isolation. These tasks are done automatically by the SharePoint 2013 installation infrastructure. The differences in development are that some markup in the app manifest is different for autohosted apps and no custom installation logic is required.

  • Visual Studio 2012. Obtain from Microsoft Visual Studio Ultimate 2012 RC.

  • Office Developer Tools for Visual Studio 2012

  • A SharePoint 2013 installation for testing and debugging.

    • This can be on the same computer as your development computer, or you can develop with a remote SharePoint 2013 installation, and the remote installation can be on Microsoft SharePoint Online. If you work with a remote installation, you need to install the client object model redistributable from SharePoint Client Components on the target installation.

    • The test SharePoint website must be created from the Developer Site site definition (which you can create in Central Administration).

    • The SharePoint 2013 installation must be configured to use OAuth. (If your test website is a Developer Site provisioned on SharePoint Online, it is already configured to use OAuth.)

Note Note

For guidance on how to setup a development environment that fits your needs, see Start building apps for Office and SharePoint.

Core concepts to know for creating an autohosted app

Before you create your first autohosted app, you should have a basic understanding of apps for SharePoint and the differences among SharePoint-hosted, provider-hosted, and autohosted apps for SharePoint. The articles listed in Table 1 should give you that understanding.

Table 1. Core concepts for creating an autohosted app

Article title

Description

Apps for SharePoint overview

Learn about the new app model in SharePoint 2013 that enables you to create apps, which are small, easy-to-use solutions for end users.

Important aspects of the app for SharePoint architecture and development landscape

Learn about aspects of the architecture of apps for SharePoint and the model for apps for SharePoint, including the app hosting options, user interface (UI) options, deployment system, security system, and lifecycle.

Hosting options for apps for SharePoint

Learn about the various ways that you can host apps for SharePoint.

In the procedures of this section, you create an app for SharePoint that includes a remote ASP.NET web application on your development machine. (Except where noted, the steps are nearly identical to how you would develop the same app for SharePoint as a provider-hosted app.)

To set up the Visual Studio 2012 solution and its elements

  1. In Visual Studio 2012, create an App for SharePoint 2013 project from the Office SharePoint | Apps node (under either C# or Visual Basic) in the templates tree of the New Project wizard. Choose the Autohosted hosting option. In the continuing example of this article, C# is used as the language and ReadListFromHostWeb is the project name.

  2. Choose Finish in the wizard. A lot of configuration is done when the solution opens. The following are some of the most important.

    • Two projects are created in the Visual Studio 2012 solution, one for the app for SharePoint and the other for the ASP.NET web application.

    • The Web Project property of the app for SharePoint project is set to the name of the web application project.

    • The values in the AppManifest.xml file are set appropriately for an autohosted app. The Start Page URL is set by default to ~remoteAppUrl/Default.aspx. The string ~remoteAppUrl is a token that resolves to the URL of the Windows Azure Web Site when your app is installed. (The manifest designer in Visual Studio 2012 may partially resolve the token rather than show it. To see the actual value of the StartPage element, open the shortcut menu for the AppManifest.xml file and choose View Code.) The Query String value is set to {StandardTokens}. This is also a token that resolves to a longer query string that includes an identification of the URL of the SharePoint website to which the remote web application communicates. Because neither the host web nor the app web URL is known until the app is installed, you need to use a token as the value of the query string. For more information on tokens in the app manifest, see App for SharePoint manifest file and URL strings and tokens in apps for SharePoint.

    • The Target Framework of the web application is set to Microsoft ASP.NET 4.0 (not Microsoft ASP.NET 4.5).

    • The SSL Enabled property of the web application is set to True.

    • References are added to the web application project for the SharePoint client object model assemblies as well as assemblies for the Microsoft identity model infrastructure.

    • A source file named TokenHelper.cs or TokenHelper.vb is added to the web application project.

  3. Open the AppManifest.xml file in the manifest designer. The Title element has the project name as its default value. Replace it with something more friendly because this is the name of the app that users see in the UI.

  4. Specify a Name for the app. This is an internal name that must contain only ASCII characters and must contain no spaces; for example, SimpleAutohostedSPApp.

  5. If the value of Query String was not set to {StandardTokens} when the project was created, give it that value now.

  6. Open the Web.config file and add the element <customErrors mode="Off"/> to the system.web element.

To code, test, and debug the project

  1. Open the AppManifest.xml file in the manifest designer and add a Permission Request for each permission to SharePoint that the web application is going to need. In the continuing example, the app is given Read access to all the lists on the host website with these steps.

    1. In the Scope cell, choose Web from the drop down list.

    2. In the Permission cell, choose Read from the drop down list.

    3. Save the file. For more information on the possible values for the Scope and Permission values, see App permissions in SharePoint 2013

  2. Develop the web application as you would any other ASP.NET web application: Add markup to the Default.aspx page, add code-behind as needed, add JavaScript as needed, add other files as needed, and so on. For the continuing example in this article, take the following steps.

    1. Open the Default.aspx file and replace the contents of the body element with the following markup and save the file.

      Note Note

      Your version of Visual Studio 2012 may have named this file "Home.aspx." If so, either use the shortcut menu to rename it, or in the remainder of this article replace "Default" with "Home."

      <body bgcolor="#000000">
          <form id="form1" runat="server">
          <div>
          <h2 style="font-family: Segoe UI; font-size: xx-large; font-weight: 100; font-style:normal; 
              color: White">composed looks on the SharePoint host website</h2>
          </div>
          <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" 
              Text="GET THE COMPOSED LOOKS" BackColor="#00FFFF" ForeColor="Black" Font-Size="Large" 
              Style="font-family: 'Segoe UI'; border-style: none; text-wrap: normal; font-weight: normal" 
              Height="210px" Width="239px" />
          <asp:Literal ID="Literal1" runat="server"><br /><br /></asp:Literal>
          <asp:GridView ID="GridView1" runat="server" BackColor="#808080" ForeColor="White"
              BorderColor="#0033CC" BorderStyle="None" Caption="THE COMPOSED LOOKS" 
              CaptionAlign="Left" CellPadding="5" Style="font-family: 'Segoe UI'" GridLines="None" 
              HorizontalAlign="Left">
              <AlternatingRowStyle BackColor="White" ForeColor="Black" />
          </asp:GridView>
          </form>
      </body>
      
    2. Open the Default.aspx.cs file and add the following using statements to it.

      using Microsoft.SharePoint.Client;
      using Microsoft.IdentityModel.S2S.Tokens;
      using System.Net;
      using System.IO;
      using System.Xml;
      using System.Data;
      using System.Xml.Linq;
      using System.Xml.XPath;
      using Microsoft.SharePoint.Samples;
      
      Note Note

      You do not need the last of these if your edition of Visual Studio 2012 uses the same namespace in the TokenHelper.cs file that it creates as is used in Default.aspx.cs.

    3. Add the following fields to the Default class.

      SharePointContextToken contextToken;
      string accessToken;
      Uri sharepointUrl;
      
    4. Replace the Page_Load method with the following code that uses the TokenHelper class to obtain tokens from the OAuth-compliant secure token server. During development, this is the token server of your development environment. After your app is converted to an autohosted app and installed, the token server is supplied by the Windows Azure Web Site hosting environment. The access token is stored in the CommandArgument property of the button for later retrieval by the button's click event handler.

      protected void Page_Load(object sender, EventArgs e)
      {
          TokenHelper.TrustAllCertificates();
          string contextTokenString = TokenHelper.GetContextTokenFromRequest(Request);
      
          if (contextTokenString != null)
          {
              // Get context token
              contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, Request.Url.Authority);
      
              // Get access token
              sharepointUrl = new Uri(Request.QueryString["SPHostUrl"]);
              accessToken = TokenHelper.GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken;
              
              // Pass the access token to the button event handler.
              Button1.CommandArgument = accessToken;
          }
      }
      
    5. Add the following event handler to the Default class. Note the following about this code.

      • It uses the SharePoint 2013 REST/OData endpoints to obtain list data. In this example, the code reads the Composed Looks list that is on every SharePoint 2013 website and already has items in it. The APIs for this service make it easy, in a single line of code, to select a list and specify three fields from the list to return. For more information about the REST/OData endpoints, see Programming using the SharePoint 2013 Preview REST service.

      • It uses the classes of the System.Xml.Linq namespace to parse the data that is returned and construct a List<T> object that can be bound to the grid control on the page.

      protected void Button1_Click(object sender, EventArgs e)
      {
          string accessToken = ((Button)sender).CommandArgument;
                
          if (IsPostBack)
          {
              sharepointUrl = new Uri(Request.QueryString["SPHostUrl"]);
          }
      
          // REST/OData section.
          string oDataUrl = "/_api/Web/lists/getbytitle('Composed Looks')/items?$select=Title,AuthorId,Name";
      
          HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(sharepointUrl.ToString() + oDataUrl);
          request.Method = "GET";
          request.Accept = "application/atom+xml";
          request.ContentType = "application/atom+xml;type=entry";
          request.Headers.Add("Authorization", "Bearer " + accessToken);
          HttpWebResponse response = (HttpWebResponse)request.GetResponse();
      
          // Response markup parsing section.
          XDocument oDataXML = XDocument.Load(response.GetResponseStream(), LoadOptions.None);
          XNamespace atom = "http://www.w3.org/2005/Atom";
          XNamespace d = "http://schemas.microsoft.com/ado/2007/08/dataservices";
          XNamespace m = "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata"; 
      
          List<XElement> entries = oDataXML.Descendants(atom + "entry")
                                   .Elements(atom + "content")
                                   .Elements(m + "properties")
                                   .ToList();
      
          var entryFieldValues = from entry in entries
                                 select new { Title=entry.Element(d + "Title").Value, 
                                              AuthorId=entry.Element(d + "AuthorId").Value, 
                                              Name=entry.Element(d + "Name").Value };
      
          // Bind data to the grid on the page.
          GridView1.DataSource = entryFieldValues;
          GridView1.DataBind();
      }
      
  3. To test the app for SharePoint and its remote web application, choose the F5 key in Visual Studio 2012. The web application is deployed to IIS Express at localhost. The app for SharePoint is installed to the target SharePoint website. The first time that you use F5, you are prompted by SharePoint to grant the permissions that the app for SharePoint requests. The Site Contents page of your target SharePoint website opens, and you see the new app listed there.

  4. Choose the app for SharePoint, and the remote web application opens to the page you specified for the Start Page in the AppManifest.xml file. Use the web application as needed to verify that it is working. In the continuing example of this topic there is a single button to choose. Doing so creates a grid and populates it with the Composed Looks list of the host web. Only three fields from the list are used.

    When the components are working correctly, you need to make changes to the two projects to configure the app and its remote web application to be an autohosted app. See the next section.

Depending on your edition of Visual Studio 2012, some or all of the steps of this procedure may have already been done automatically.

To configure the app to be autohosted

  1. In Solution Explorer, open the References node of the web application. For each of the following assemblies, highlight the assembly and set the Copy Local property to True, if it was not already set to True by Microsoft Visual Studio 2012. This ensures that all five assemblies will be installed on the virtual machine that hosts the web application in a Windows Azure Web Site.

    • Microsoft.SharePoint.Client.dll

    • Microsoft.SharePoint.Client.Runtime.dll

    • Microsoft.IdentityModel.dll

    • System.IdentityModel.dll

    • Microsoft.IdentityModel.Extensions.dll

  2. In Solution Explorer open the shortcut menu of the app for SharePoint project and choose Publish.

  3. In the Publish dialog box, choose Publish. The resulting app package file (which has the Windows Azure Web Site package inside) has an .app extension and is saved in the app.publish subfolder of either the bin\Debug or bin\Release folder of your Microsoft Visual Studio 2012 project.

The app for SharePoint can now be uploaded to the app catalog of a SharePoint Online tenancy. For further debugging, you can deploy the app directly from Visual Studio 2012 to a SharePoint Online website, if it was created with the Developer Site site definition. To do this, open the shortcut menu of the app project in Solution Explorer and choose Deploy. Tenant administrators can install the app on their SharePoint Online tenancy by using the following procedure.

To install the autohosted app

  1. Log in to Microsoft SharePoint Online as a tenant administrator.

  2. On the Admin drop-down menu at the top of the page, choose SharePoint.

  3. On the SharePoint Administration Center page, choose apps, Corporate Catalog.

  4. On the App Catalog page, choose the upload link, browse to your app for SharePoint package on the Add a document form, and choose OK. An item property form opens.

  5. Fill out the form as needed and choose Save. The app for SharePoint is saved in the catalog.

  6. Navigate to any website in the tenancy and choose Site Contents to open the Site Contents page.

  7. Choose Add an App, and on the Add an App page, find the app. If there are too many to scroll through, you can enter any part of the app title (that you entered for Title in the AppManifest.xml file) into the search box.

  8. When you find the app, choose the Details link beneath it, and then on the app details page that opens, choose Add It.

  9. You are prompted grant it permissions. Choose Trust It in the dialog box.

  10. The Site Contents page opens, and the app is listed. For a short time a message below the title indicates that it is being added. When this message disappears, you can choose the app title to launch the app. (You may need to refresh the page before the message disappears.) In the continuing example of this article, because the Start Page was set to the URL of the remote web application's Default.aspx page, that page opens.

This article demonstrated how to create a simple autohosted app for SharePoint with a remote web application. As next steps, consider the following:

Did you find this helpful?
(1500 characters remaining)

Community Additions

ADD
© 2013 Microsoft. All rights reserved.