Chapter 8. SharePoint apps

Without doubt, the biggest news of Microsoft SharePoint 2013 is the new app model, with which you can create apps and publish them in a public marketplace or corporate app catalog. You can use the app model on Microsoft Office 365 and SharePoint Online or in on-premises solutions. For example, you can create a custom app that addresses a common need and sell it worldwide to millions of users through the Microsoft Office Store. The main goal of this new app model is to enable developers to customize and extend SharePoint sites without full-trust access to the target farm. This goal adheres perfectly to the cloud-computing offering model and philosophy. In this chapter, you will tour the app model architecture, as well as learn about app development and deployment.

Introducing apps

When developing a new SharePoint app, you can choose between three configurations:

  • Full-page. Based on one or more web pages, these apps include a dedicated UI. You should provide a back button for returning to the parent site, where the app is launched from—but your app will have a UI of its own.

  • App Parts. Also called Client Parts, these render some app content in an IFrame inside pages of the parent site. Usually, App Parts are used to provide users with a small piece of information or functions that can directly interact with the SharePoint user interface.

  • UI command extension. Used to extend the UI of the parent site, these apps may include a ribbon button or an ECB (Edit Control Block) command to lead the user to a page or function provided by an external app.

SharePoint apps can use three hosting models, as well:

  • SharePoint-hosted. This model relies on a subweb of the parent site (also called an app web) and enables you to use all the common SharePoint artifacts for implementing the UI and the behavior of the SharePoint app. You can take advantage of all the features of SharePoint, such as lists, Web Parts, pages, workflows, and so on.

  • Autohosted. Apps following this model are hosted on Microsoft Windows Azure, which can access a Microsoft SQL Azure database for managing data, too. The apps are automatically deployed on Windows Azure on your behalf and can communicate with SharePoint through events and the Client Object Model. Secure communication with SharePoint is enforced using OAuth.

  • Provider-hosted. From a functional perspective, apps that follow this model are almost the same as autohosted apps. The only difference is that a provider-hosted app has to be deployed on your own hosting environment and does not necessarily use the Windows Azure environment.

Regardless of the hosting model and configuration, every SharePoint app is mainly a web application that interacts with SharePoint using the Client Object Model and the new REST API introduced with SharePoint 2013 (which is covered in Chapter 9). One key feature of SharePoint apps is that they can be developed with any programming language or technology, as long as you host them outside SharePoint (that is, using an autohosted or provider-hosted model). In fact, you can create a SharePoint app using PHP, Java, or any other technology capable of communicating with SharePoint via the new REST API and the OAuth protocol.

Development environment

You have two choices for your environment to develop and test a custom SharePoint app. Your first option is a SharePoint 2013 site based on the Developer Site site template and hosted on a properly configured, on-premises SharePoint farm. (For more information about configuring an on-premises farm for deployment of apps, read the “App management configuration and deployment” section later in the chapter.) Otherwise, you can sign up for an Office 365 Developer Site subscription, which is freely available, as long as you have a valid license of Microsoft Visual Studio Premium or Ultimate with MSDN Subscription, and enables you to develop and test apps using SharePoint 2013 Online. (To create a subscription, go to http://msdn.microsoft.com/en-us/library/fp179924.aspx.)

Moreover, if you want to develop the app using Microsoft .NET and Microsoft Visual Studio 2012, you will need the Office Developer Tools for Visual Studio 2012, which can be downloaded and installed through the Web Platform Installer 4.0 tool. You also will need to install the following tools and libraries:

  • SharePoint client components

  • Windows Identity Foundation SDK

  • Workflow Tools SDK and Workflow Client SDK

  • Windows Identity Foundation SDK and Windows Identity Foundation extensions

If you are working on a server with SharePoint 2013 installed, you need to add only Visual Studio 2012 and the Office Developer Tools for Visual Studio 2012. All the other libraries and tools are already part of the installation set of any SharePoint 2013 environment.

Your first app

The best way to learn about SharePoint apps is to develop one. Throughout the chapter, you will complete a sample introductory app, evaluating possible scenarios along the way. Imagine that you want to create an app for managing contacts. In this section, you will start hosting the app on SharePoint. First, you’ll create a new project. To do so, start Visual Studio 2012 and open the New Project dialog box (File | New Project). Select the Office/SharePoint | Apps group of projects and choose App For SharePoint 2013. Figure 8-1 shows the project type highlighted in the New Project window of Visual Studio 2012.

A screen shot illustrating the New Project window of Visual Studio 2012, highlighting the App For SharePoint 2013 project type under the Office/SharePoint | Apps group of projects.

Figure 8-1. The New Project window of Visual Studio 2012 with the App for SharePoint 2013 project highlighted.

As soon as you choose to add a new SharePoint app, Visual Studio prompts you with a wizard for configuring the target developer site URL, as well as the hosting model you would like to use. Figure 8-2 shows the first step of the wizard. For this first exercise, you should choose a SharePoint-hosted app, in order to make it simpler to develop and host the app.

If you choose to host your SharePoint app on an Office 365 developer site, click the Validate button, which is located just beside the target site URL. Depending on your configuration, you may be prompted with an Office 365 logon screen.

A screen shot of the first step of the New App For SharePoint wizard. Fields are provided for specifying the name of the app, the target developer site URL that will be used, and the hosting model. The available values for the hosting models are Autohosted, Provider-hosted, and SharePoint-hosted. There is also a button to validate the target site URL.

Figure 8-2. The New App For SharePoint wizard.

Sample SharePoint-hosted app outline

After you create a project, Solution Explorer presents you with a set of folders and files, as shown in Figure 8-3. The following are the main sections of this project outline:

  • Features folder. Contains all the features for provisioning contents and capabilities to the target app website. Upon creation, this folder contains only one web-level feature. The goal of this feature is to provision all the other contents to the target app website.

  • Package folder. Contains the package for deploying the app on the target site.

  • Content folder. Deploys custom CSS styles related to the app and is a Module feature.

  • Images folder. Deploys all the images related to the app and is a Module feature. Upon creation, the folder contains only the AppIcon.png file, which represents the icon of your app. To customize the look of your app, replace the default AppIcon.png file with a customized 96×96-pixel PNG image.

  • Pages folder. Holds a Module feature for deploying all the pages of the target app website. By default, the project template creates a Default.aspx page, but you can create more pages by yourself.

  • Scripts folder. Represents a Module feature that is composed of JavaScript files for deploying jQuery scripts, some JavaScript references, and the App.js file, which is the JavaScript Client Object Model entry point of the app.

  • AppManifest.xml file. Contains all the configuration and deployment information related to the app. It’s the fundamental file of every app, and it will be discussed in detail in the “Inside AppManifest.xml” section later in the chapter.

  • packages.config file. Relates to the jQuery package automatically configured in the current project. In general, this file holds the information about the packages referenced by the Visual Studio project.

A screen shot showing the outline of an app for the newly created SharePoint 2013 project. On the right is a list of folders—named Features, Package, Content, Images, Pages, and Scripts—as well as the AppManifest.xml file and a packages.config file. On the left side of the screen, by default, the code editor shows the source code of the Default.aspx page of the host web.

Figure 8-3. The outline of an app for SharePoint 2013 project.

To begin playing with the current app project, just press F5 to start debugging it on the target site. First, you will notice that Visual Studio 2012 starts compiling, packaging, deploying, and installing the solution. Then your default web browser will start, showing the Default.aspx page of the current app. Figure 8-4 shows the output.

A screen shot of the default welcome page of a SharePoint-hosted app. The outline and the layout are almost the same as a classic SharePoint 2013 site. The page welcomes the current user by name, displaying “Hello administrator.”

Figure 8-4. The default welcome screen of a SharePoint-hosted app.

Notice that the Default.aspx page, after a quick initialization message (“initializing…”), welcomes the current user by name. The code for retrieving the user name uses the JavaScript Client-Side Object Model (JSOM). Moreover, the page looks like every other SharePoint 2013 page, and it has a link at the top-left corner of the page for coming back to the host site.

Before clicking the Back link, notice the URL of the current page in the browser’s address bar. In the current example, which runs on-premises, the address is similar to the following:

http://apps-{UniqueID}.sp2013apps.local/sites/{ParentSiteName}/{AppName}/

Later, in the section “App management configuration and deployment,” you will learn how to configure a SharePoint web application or tenant for hosting such a URL. If you are targeting an Office 365 developer site, the URL of the app will be something like this:

https://{TenancyName}-{UniqueID}.sharepoint.com/sites/{ParentSiteName}/{AppName}/

Eventually, you will be prompted with the Office 365 logon screen to access the target host site and the app. Lastly, whether you are on-premises or in the cloud, the app URL will be enriched with a long list of query string parameters. (You’ll learn more about these later in this chapter.)

The app website

When you install your app onto the target development site, the site lists it on the Site Contents page in the Lists, Libraries, and other Apps category. As shown in Figure 8-5, the example app’s listing has a custom AppIcon.png file with the company’s logo.

A screen shot of the Site Contents page showing the example app available in the Lists, Libraries, And Other Apps category. The example app displays a custom icon.

Figure 8-5. The Site Contents page of a developer site with a custom app installed.

Remember, the SharePoint-hosted app uses an app website, which is a subweb of the current site collection, dedicated for hosting the app. You cannot access the app website with SharePoint Designer 2013, because support for it is disabled for this kind of website. Nevertheless, you can access it through PowerShell; simply use the Client-Side Object Model (CSOM) or any third-party tool to browse the site structure. A sample PowerShell script to retrieve information about the current app website demonstrates how to access the app website through PowerShell, by iterating through the child websites of the current site collection.

When you execute a PowerShell script like the one in A sample PowerShell script to retrieve information about the current app website, the host console will display output similar to the following:

Here are the sub-webs of the current site collection root web
ID:  75f26332-940d-4f08-838d-cda4b6e11c62  - Title:  AppsDevelopmentSite
ID:  43d8c941-d442-490c-8ed5-4408a41d5516  - Title:  DevLeap.SP20130.ContactsApp 
App Web Site Author:  SHAREPOINTsystem
App Web Site Is App Web? True
App Web Site Is Root Web? False
App Web Site Is Provisioned? True
App Web Site URL? http://apps-3285d5aad768c4.sp2013apps.local/sites/AppsDevelopmentSite
App Web Site parent Web Application: SPWebApplication Name=DevLeap Book Portal

The most interesting information you can glean from the script output is

  • The app website is automatically provisioned by the Local System account.

  • The app website has an explicit flag stating that it is the site hosting an app.

  • The parent site collection and web application of the app website are the site collection and web application of the extended site.

  • The app website is a subweb of the current site collection.

Provisioning content

Now that you understand the basics of a SharePoint-hosted app, you’re ready to provision some content into the app web of your first sample app. Imagine that you want to add a list of contacts based on a custom content type. In Chapter 3 you already learned how to provision list definitions based on custom content types. Thus, this section will skip all the details, and the goal will be to create a list of contacts made of the following fields: Title, Description, Telephone, Email, and Photo.

To present the custom Contacts list to the end user, you could add a direct link to the default view of the list into the home page (Default.aspx file) of the app, but there’s an even better way. You can use the app’s Default.aspx page, which is a common SharePoint page. Open the Default.aspx file, and put some ASPX code inside the content region named PlaceHolderMain, as shown in The Default.aspx page source ASPX code changed to show the custom list of contacts. The list-relative URL used is Lists/AppContacts.

As you can see, the WebPartZone control (highlighted in bolded text) wraps a classic SharePoint XsltListViewWebPart control, which shows the items of the custom Contacts list. Figure 8-6 illustrates the resulting output in the browser after some sample contacts have been added. As you can see, the layout and the behavior of the page are the same of any other SharePoint page, because the app website is yet another SharePoint site.

Important

Remember that an app website is provisioned and unprovisioned together with its app. Thus, you create an app that stores content inside its app web. If your end users remove or uninstall the app, however, not only will the app web be decommissioned, but your data will be lost as well. In order to intercept such events, you can handle app-related events. For example, you can use the AppUninstalling event (discussed in Chapter 10) together with other remote events.

Moreover, the Default.aspx page, as well as any other custom page you add to the app, is based on server controls or client-side code only. For example, you cannot add an application page (see Chapter 12 for further details) based on server-side code, because this would require a full-trust deployment of your page, which is not allowed for SharePoint-hosted apps. In case you need to create an app that uses server-side code, you should create an autohosted or a provider-hosted app.

A screen shot of the home page of the custom app web. It shows the custom list of contacts provisioned with the app. The layout of the list view is the same as any other SharePoint list, because the app website is a SharePoint site.

Figure 8-6. The output of the Default.aspx page after adding an XsltListViewWebPart control for showing the custom Contacts list.

Using the Client-Side Object Model

For the sake of completeness, have a look at how the JSOM interacts with your app website. Open the App.js file provided in the Scripts folder of the project. In The JavaScript code provided by default within the App.js file inside the Scripts folder of a SharePoint-hosted app project, you can see the default content of that file.

As discussed in Chapter 7 you can use the JavaScript Client Object Model (JSOM) to interact with the current site or site collection, as well with remote sites (as long as you have a set of authorized credentials). The JavaScript code provided by default within the App.js file inside the Scripts folder of a SharePoint-hosted app project uses a jQuery directive to register for the DOM document ready event. There it retrieves a reference to the current website in order to get the current user name. Because the JSOM natively provides asynchronous behavior, the code queries for the current user by invoking the executeQueryAsync method of the current context and, when successful, shows the title property of the current user in the paragraph (that is, the HTML element <p>) with an ID value of message, which is defined in the Default.aspx page. You can see that paragraph element in The Default.aspx page source ASPX code changed to show the custom list of contacts, just before the code highlighted in bold.

If you want to enrich your custom app with client-side code and the JSOM, you can simply add your custom code to this App.js file. Then you should invoke your custom functions from within the Default.aspx page or from any other custom page you will provision together with your SharePoint app. Everything you have already learned about the JSOM is valid in this context, too.

Inside AppManifest.xml

The main content of every SharePoint app project, regardless of its hosting model, is in the AppManifest.xml file. This file contains information about the app in general, the permissions required by the app, the prerequisites for running the app, the supported languages/locales, and any remote endpoint. By double-clicking the AppManifest.xml file, you can open the specific designer provided by Visual Studio 2012 and edit all these configurations. For example, Figure 8-7 shows the AppManifest.xml designer, which is made of a set of tabs for managing the various configuration properties, grouped by category. In the next section, you will learn all the details about these properties.

A screen shot illustrating the designer for the AppManifest.xml file. It provides a set of five tabs for configuring parameters: General, Permissions, Prerequisites, Supported Locales, and Remote Endpoints.

Figure 8-7. The designer for AppManifest.xml provided by Visual Studio 2012.

More Info

Under the hood, the AppManifest.xml file is just an XML file based on the XML schema with a namespace URI value of http://schemas.microsoft.com/sharepoint/2012/app/manifest. You can find further details about the AppManifest.xml schema at http://msdn.microsoft.com/en-us/library/jj583347.aspx.

The General tab

The first and main configuration tab, General, holds general information about the app, such as the title, name, and version, as well as the icon to show in the SharePoint UI. You can also choose the start page of the app, which will become the default page of the app website provisioned while installing the app. Finally, yet importantly, you can configure the query string behavior of the app. As shown in the previous section, when your app is activated, it receives a rich and long set of query string arguments. If you configure the query string property of you app, you can determine the list of arguments that the app will receive. In this property, you can use the tokens illustrated in Table 8-1. All these tokens will be resolved and appended to the URL of the default page of your app during activation.

Table 8-1. Tokens for configuring the AppManifest.xml file’s query string property

Token name

Description

{AppWebUrl}

The URL of the app web in an app for SharePoint. This token should be used only outside an app web. Within the app web itself, use {Site} for the URL of the app web.

{HostLogoUrl}

The logo for the host web of an app for SharePoint.

{HostTitle}

The title of the host web of an app for SharePoint.

{HostUrl}

The URL of the host web of an app for SharePoint.

{Language}

The current language/culture of the host web of an app for SharePoint.

{StandardTokens}

Combines three other tokens. It initially resolves to SPHostUrl={HostUrl}&SPAppWebUrl= {AppWebUrl}&SPLanguage={Language}. Then each of these tokens resolves. If there is no app web, the &SPAppWebUrl={AppWebUrl} portion is not present.

By default, any SharePoint app uses the {StandardTokens} URL token, because it is the most complete. You can change it, however, or add your own tokens or arguments to the URL.

The Permissions tab

The Permissions section is probably the most important, and it enables you to define the permissions your app requires in order to install and execute. Whenever you install an app, the SharePoint environment will ask to the user installing it for those specific permissions. In fact, an app must be explicitly granted the required permissions in order to be installed. When installing an app, users can grant only permissions that they have, and they can grant or deny permissions with an all-or-nothing approach only. Users cannot grant a subset of the required permissions. If a user tries to install an app that requires permissions the user does not have, the SharePoint environment will raise an exception, showing a message that states the user does not have sufficient permissions to complete the action.

Every app has an identity of its own, which is associated with a security principal called the app principal. The app principal of an app has full control rights against the app web hosting the app itself. Thus, you do not need to request permissions for accessing the app web from your app. On the contrary, if your app needs to access the parent site or any external location outside the app web, you will need to request specific permissions for that.

The available permissions are defined by scope, and scopes are represented as URIs in the AppManifest.xml file. In the UI for configuring the permission, however, you see only literal names, for the sake of simplicity. Table 8-2 lists the available scopes.

Table 8-2. Available scopes and permissions for an app

Scope

Available permissions

Description

BCS

Read

Corresponds to the URI http://sharepoint/bcs/connection and allows defining the permission to access Business Connectivity Services (BCS) data.

Enterprise Resources

Read, Write

Allows accessing enterprise-level resources of Microsoft Project Server 2013. It is defined by the URI http://sharepoint/projectserver/enterpriseresources.

List

Read, Write, Manage, FullControl

Allows defining permissions for accessing lists. It corresponds to the URI http://sharepoint/content/sitecollection/web/list and supports extended properties for defining a specific target BaseTemplateId number, in case you would like to define permissions only for lists based on a particular BaseTemplateId.

Micro Feed

Read, Write, Manage, FullControl

Corresponds to the URI http://sharepoint/social/microfeed and relates to the Social Features group of scopes. It allows defining permissions for accessing the social microfeed.

Multiple Projects

Read, Write

Allows defining permissions for accessing multiple projects of Project Server 2013. It corresponds to the URI http://sharepoint/projectserver/projects.

Project Server

Manage

Corresponds to the URI http://sharepoint/projectserver and defines the permission to manage Project Server 2013.

Reporting

Read

Allows defining the permission to read reporting information from Project Server 2013 and corresponds to the URI http://sharepoint/projectserver/reporting.

Search

QueryAsUserIgnoreAppPrincipal

Defines permission to search contents via the app as the user principal, instead of using the app principal. It corresponds to the URI http://sharepoint/search.

Single Project

Read, Write

Allows defining permissions for accessing a single project of Project Server 2013. It corresponds to the URI http://sharepoint/projectserver/projects/project.

Site Collection

Read, Write, Manage, FullControl

Corresponds to the URI http://sharepoint/content/sitecollection and defines the permissions related to a site collection.

Social Core

Read, Write, Manage, FullControl

Provides permissions for accessing core information of the social features. It corresponds to the URI http://sharepoint/social/core.

Statusing

SubmitStatus

Allows defining the permission to submit status to Project Server 2013. It corresponds to the URI http://sharepoint/projectserver/statusing.

Taxonomy

Read, Write

Provides permission configuration for accessing the taxonomy engine and corresponds to the URI http://sharepoint/taxonomy.

Tenant

Read, Write, Manage, FullControl

Corresponds to the URI http://sharepoint/content/tenant and defines permissions for accessing the content at the tenant level.

User Profile

Read, Write, Manage, FullControl

Corresponds to the URI http://sharepoint/social/tenant and defines permissions for accessing the users’ social features at the tenant level.

Web

Read, Write, Manage, FullControl

Defines permissions for accessing a specific website within a site collection and corresponds to the URI http://sharepoint/content/sitecollection/web.

Workflow

Elevate

Allows defining the permission to elevate privileges in workflows of Project Server 2013. It corresponds to the URI http://sharepoint/projectserver/workflow.

Where available, the FullControl permission cannot be requested for apps that you want to publish to the Office Store. Moreover, the permission scopes related to Project Server 2013 are available only in environments where Project Server 2013 is installed.

App permissions are inherited hierarchically, and a permission applied to a parent object is implicitly applied to all of its children. For example, if you grant a Write permission at the Site Collection scope, the app will have that same permission for all of the sites within the target site collection.

Figure 8-8 shows how the Permissions tab behaves in the AppManifest.xml designer. For the sake of clarity, the AppManifest.xml file illustrated requires all the available permissions.

A screen shot of the Permissions tab of the AppManifest.xml designer. On the tab, you can set the permissions that your app will require for the end user during installation. Permissions are grouped by scope, are defined by permission type, and can have custom properties.

Figure 8-8. The Permissions tab in the designer for AppManifest.xml.

The XML source of an AppManifest.xml file with all the available permission scopes defined provides the XML source of an AppManifest.xml file configured as illustrated in Figure 8-8.

Notice the List permission, highlighted in bold, with the optional property BaseTemplateId configured to a value of 101 (for “document library”). When you install an app with some custom permissions requests, the SharePoint environment will ask you to trust it. Figure 8-9 illustrates how the request to trust the app is prompted to an end user. As you can see, the form asks the end user to choose the library to which you would like the app to have access. If you trust the app and give it the requested permissions, then you will be able to use it.

A screen shot of the page for trusting an app during installation. It includes a list of requested permissions and a button to trust the app. There is also a button to cancel the installation without trusting the app.

Figure 8-9. The page for trusting an app during installation.

In case you later decide to change or retract permissions from an app, you can remove the whole app, or you can go to the permissions-management page specific for that app. To view that page, go to the Site Contents page, click the ellipsis just behind the app icon, and select the Permissions link on the ECB menu. This link will lead you to the permissions-management page that is illustrated in Figure 8-10.

A screen shot showing the page for checking and managing permissions for an app. It includes a list of granted permissions and a button for trusting the app again.

Figure 8-10. The permissions-management page for an app.

The Prerequisites tab

The third configuration tab of the AppManifest.xml file, Prerequisites, provides a grid for configuring the list of the prerequisites that must be installed on the SharePoint site in order for the app to be installed. If necessary, you can configure the following prerequisites:

  • Access V14 (aka Access 2010)

  • Access V15

  • Duet Enterprise Services

  • Education Services

  • Managed Metadata Web Service

  • PowerPoint Services

  • Search Services

  • Secure Store Services

  • SharePoint Translation Services

  • SharePoint Workflow Services

  • User Profile Service

  • Visio Services

  • Work Management Service

Each prerequisite feature or service can also specify a minimum version requirement. Figure 8-11 shows the outline of this configuration tab, with all of the out-of-the-box prerequisites configured.

A screen shot of the outline of the tab for configuring the app prerequisites. It includes a grid with the list of all the available and configurable prerequisites.

Figure 8-11. The outline of the tab for configuring app prerequisites.

The resulting configuration defines an AppPrerequisites element in the AppManifest.xml file, filled with a set of elements with name AppPrerequisite. Each AppPrerequisite element is configured with a Type attribute, an ID attribute, and an optional MinimumVersion attribute. Here is the XML definition of the AppPrerequisite element for the Visio Services capability:

<AppPrerequisite Type="Capability" ID="778D6B91-D46F-40E6-B7A4-1C666B800D03" MinimumVersion="15.0.0.0" />

As you can see, the prerequisite is referenced by ID, which in general is a globally unique identifier (GUID). The Type attribute can assume values of Feature, Capability, or AutoProvisioning. The first two values are self-explanatory; the AutoProvisioning value is suitable only for autohosted apps. In fact, for autohosted apps, you can automatically provision components that the app needs while provisioning the app itself. In this case, the ID attribute can assume literal values (instead of GUIDs) corresponding to RemoteWebHost and Database, for provisioning a Windows Azure website and a SQL Azure database, respectively. The MinimumVersion attribute is in the form of a product version: {number} ({major version}.{minor version}.{build number}.{revision}).

For services such as Excel, Access, or Visio Services, the infrastructure will verify that the service is installed and licensed. For features at the Farm, WebApplication, or Site scope, the infrastructure will verify that they are deployed and activated. For features that can be activated at the Web scope on the target app web, the environment will automatically activate them during app installation.

The Supported Locales tab

Through the Supported Locales tab, you can configure the locales supported by your app, together with the resource files corresponding to each locale. Every SharePoint app can support one or more locales, providing dedicated resources and resource files. On this tab, you simply need to configure a locale ID (using the culture name) and the name and content of the corresponding resource file. Each time you configure a supported locale, Visual Studio 2012 creates the corresponding .resx file for you. Figure 8-12 shows the tab configured for supporting the Italian locale and the French locale. It also shows the SharePoint app project outline, with the .resx files corresponding to these supported locales.

Important

By default, apps have no locales configured. If you want to publish your app on the Office Store, however, you must declare at least one supported locale, and you should support the English locale (1033).

A screen shot depicting the tab for configuring the supported locales for a SharePoint app. It includes a grid for configuring the culture names and the corresponding RESX files. The SharePoint app project outline and the RESX files are also visible.

Figure 8-12. The tab for configuring the supported locales for an app.

The Remote Endpoints tab

The last tab of the AppManifest.xml configuration panel is Remote Endpoints. A remote endpoint is a URL that your app will use for accessing data or services from external domains. Nowadays, there are cross-site scripting (XSS) policies denying access to external domains via JavaScript code. When you are developing an HTML-and-JavaScript-based SharePoint app, use this tab to configure the list of allowed remote endpoints. SharePoint will then provide a JavaScript-based API (SP.RequestExecutor) that will call the configured remote endpoints for you, and pass back the data it receives. Figure 8-13 shows how the configuration for remote endpoints behaves in Visual Studio 2012.

A screen shot of the Remote Endpoints tab. It includes a text box where you can type a URL and an Add button to add that URL to a list. It also has a Remove button for removing an already added URL.

Figure 8-13. The tab for configuring the remote endpoints for an app.

Configuring the remote endpoints on this tab results in the creation of an XML section within the AppManifest.xml file, such as the following:

<RemoteEndpoints>
    <RemoteEndpoint Url="http://www.myremoteservice.com" />
</RemoteEndpoints>

In Chapter 9, you will learn how the SP.RequestExecutor API works and how to take advantage of it in your apps.

App Parts and custom UI extensions

So far, this chapter has discussed full-page apps. In this section, you will learn how to create App Parts and custom UI extensions, which are the two other configurations available for SharePoint apps.

Creating App Parts

To recap, an App Part (also known as a Client Part) renders some content of the app in an IFrame inside pages of the parent site. Now, imagine that you want to extend the functionalities of the SharePoint app you developed during the previous sections. For example, you could add an App Part for searching the contacts from within the parent SharePoint site. Figure 8-14 shows the intended output result.

A screen shot of the sample App Part in action. Along with a Search Contacts text box and Search button, it displays the pictures of contacts that match the searched term.

Figure 8-14. The sample App Part in action while searching app contacts.

To add a new App Part, simply right-click the app project while in Visual Studio and select Add | New Item | Client Web Part (Host Web) from the list of available item templates. Then provide a name for the target App Part. For this example, call it SearchContactsAppPart. When you add an App Part to a project, a wizard will prompt you to enter some information about the App Part, as shown in Figure 8-15. In this wizard, you can choose between creating a new App Part and using an already existing ASPX page, which will be loaded inside the IFrame that will host the App Part. Click the Finish button to create an ASPX page file and a new feature element for provisioning your App Part.

A screen shot of the wizard for adding an App Part. It includes options for creating a new page and reusing an already existing page.

Figure 8-15. The UI for adding an App Part to a target project.

The ASPX page file is just another web page that will be hosted in your app web, and that will have the same capabilities of the Default.aspx page or any other custom ASPX page. Here you can use the JSOM to interact with SharePoint and with your app web. The default content of the SearchContactsAppPart.aspx page behind the custom App Part shows the default content of the SearchContactsAppPart.aspx file created by Visual Studio 2012 upon creation of the App Part.

As you can see, the page references the classic SharePoint server-side libraries and controls, and inherits its behavior from the Microsoft.SharePoint.WebPartPages.WebPartPage base class, without defining any master page file. Moreover, the server-side control called AllowFraming enables your page to be rendered inside an IFrame.

Just after the server control for allowing the frame support is HTML and JavaScript code for rendering the basic elements of the page, together with default theming consistent with the host SharePoint website. By default, the page will try to locate the SPHostUrl parameter in the query string and will download the CSS style (if it exists) from the URL _layouts/15/defaultcss.ashx relative to the SPHostUrl. If the SPHostUrl argument is missing, the App Part will be rendered using the CoreV15.css style of the current app website.

To implement the App Part, you will have to add some HTML and JavaScript code to the page. For the current sample, you will reuse some ideas and code already shown in Chapter 7. For example, you’ll add a text box and a button for searching contacts. Inside the body element of the page, add the following markup:

Search Contacts: <input type="text" name="textToSearch" id="textToSearch" />
  <input type="button" value="Search" onclick="javascript:searchContacts();" />
  <br /> <br />
  <div id="searchOutput" style="overflow:auto; height: 130px;"></div>

Then, just before the closing tag of the head element of the page, add the following references to scripts:

<script type="text/javascript"
  src="http://ajax.aspnetcdn.com/ajax/4.0/1/MicrosoftAjax.js"></script>
  <script type="text/javascript"
  src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.3.min.js"></script>
  <script type="text/javascript"
  src="http://code.jquery.com/ui/1.9.2/jquery-ui.min.js"></script>
  <script type="text/javascript"
  src="/_layouts/15/sp.runtime.debug.js"></script>
  <script type="text/javascript" src="/_layouts/15/sp.debug.js"></script>
  <script type="text/javascript"
  src="../Scripts/SearchContacts.js"></script>

Now you will need to add a new JavaScript file in the Scripts folder of the project. For example, give it a name of SearchContacts.js. The JavaScript code behind the App Part defined in the SearchContactsAppPart.aspx page shows how the code should look.

As you can see, the code is made of standard JSOM directives for searching the target list of contacts using Collaborative Application Markup Language (CAML).

The last piece of code to evaluate is the feature element for provisioning the App Part. In fact, when you add an App Part to a SharePoint app project, Visual Studio 2012 adds also a feature element to the project. In The feature element file for provisioning the sample SearchContactsAppPart shows the one related to the sample App Part illustrated in this section.

The ClientWebPart element provisions an App Part, providing descriptive information like Name, Title, Description, DefaultWidth, and DefaultHeight. If you are creating a multilingual app, you should at least provide a resource-based value for both the Title and Description attributes, using the classic $Resources:ResourceName; syntax and providing a value for the key ResourceName in every RESX file.

In addition, you can include a list of custom properties, defined through a set of Property elements (children of the Properties element). Every Property element can assume the structure illustrated in Property element structure and define a property that will be configurable through the SharePoint UI while managing the page hosting the App Part. You can also define properties that are not configurable by the end users, but that are still needed by the App Part internal logic.

The most interesting things to notice are the available data types, which are string, int, Boolean, and enum (shown in Figure 8-15). In case of the enum type, you will have to provide the admitted values using the EnumItems child element. Some other interesting attributes are PersonalizationScope, for defining whether the property can be personalized by each user or will assume a shared value; and RequiresDesignerPermission, for determining whether the user has to have designer permissions to edit the property value. Moreover, you can define attributes to configure the appearance of every single property in the UI, including WebBrowsable, WebCategory, WebDescription, and WebDisplayName. These last attributes have names and meanings that correspond to similar properties of SharePoint Web Parts, which will be discussed in Chapter 11 A sample Property element defining a property of type enum, defined for the sample App Part for searching contacts demonstrates how to define an enum property for defining the orientation (horizontal or vertical) of results for the sample App Part for searching contacts.

The selected values of configurable properties can be passed via query string to the ASPX page behind the App Part. The syntax for passing the properties is to append them to the Src attribute value at the end of the App Part page URL. The name for the query string arguments can be anything you like, while the value has to be represented as _{PropertyName}_. For example, to get the value of a property with the name FlowDirection into an argument with the name Direction, you should write the Src attribute value as follows:

Src="~appWebUrl/Pages/ClientWebPart1.aspx?Direction=_FlowDirection_"

Remember that the feature element is an XML file, so any special characters, such as & or %, should be represented in URL-encoded format. To access the provided values while executing the App Part, use jQuery extensions or custom JavaScript code, just as you would with any other HTML or JavaScript application.

Figure 8-16 shows how the various types of properties are rendered in the SharePoint UI. To display the tool pane, click the Edit Web Part menu, which is available while the page is in Edit mode, as it is for any other classic Web Part in SharePoint.

A screen shot of the Edit Tool pane for the sample App Part. A preview of the App Part is on the left, and the controls for configuring its appearance, layout, and behavior are on the right. The Custom Properties settings are open, displaying four configurable properties, corresponding to the four data types available: Boolean, enum, integer, and string.

Figure 8-16. The UI for configuring the properties of an App Part.

After you install your app, you can add the App Part to a target page. You simply need to edit the page, and on the ribbon’s Insert tab, click the App Part button. You will be prompted with the list of all the available App Parts, including SearchContactsAppPart. Figure 8-17 illustrates the UI for inserting the sample App Part in a target page.

A screen shot of the UI SharePoint provides for adding an App Part to a target page. It displays the list of all the available App Parts and a button to add a selected App Part to the current page.

Figure 8-17. The UI for adding an App Part to a target page.

Notice that, although you are still in edit mode, your App Part is fully functional already. In fact, the code behind the App Part is based on JavaScript and runs both in edit and design mode.

Creating custom UI extensions

Custom UI extensions allow your SharePoint apps to interact with the end user through the standard UI of SharePoint. You can add custom menu items in the ECB, and custom ribbon commands and tabs to the ribbons of standard SharePoint pages, while using exactly the same tools and techniques you would for any other UI customization (see Chapter 12). In addition, while working in SharePoint apps, you also have the support of a few dedicated tools and wizards.

To create a custom UI extension, you simply need to add a new item to an already existing SharePoint app project. To add a new menu item, right-click the project in Visual Studio 2012 Solution Explorer, select Add from the menu, and then choose New Item and finally Menu Item Custom Action. In the wizard that appears, provide the appropriate answers to create the new menu item. Figure 8-18 depicts the first step of this wizard.

A screen shot of the first step of the wizard for creating a new menu item extension. You can click to choose either Host Web or App Web as the target of the action. Then you specify the scope of the action and the particular item to scope the action through drop-down menus.

Figure 8-18. The first step of the wizard for creating a new menu item extension.

First, you can choose whether the menu item will be created within the app web or the host web. Then you can choose where the menu item will be scoped. The available options are

  • List Template. The new menu item will be scoped to every list based on a specified template.

  • List Instance. The new menu item will be scoped to a specific list instance.

  • Content Type. The new menu item will be scoped to a specific content type, regardless of the list template or list instance where it will be used.

  • File Extension. The new menu item will be scoped to a particular file extension of items in libraries.

The wizard will adapt to the selection you make. For example, if you choose List Instance, then you will have to choose the specific target instance; when choosing Content Type, you will have to select the target content type; and so on.

In the second step of the wizard (Figure 8-19), you define the caption of the menu item, as well as the target URL to drive the user to when the menu item is selected.

A screen shot of the second step of the wizard for creating a new menu item extension. You can specify the caption of the menu item in the provided text box and use the editable drop-down list to select or enter the relative URL of the page that will be invoked when the user selects the menu item.

Figure 8-19. The second step of the wizard for creating a new menu item extension.

After you complete the wizard, Visual Studio will prompt you with a new feature element that defines the custom action. A sample feature element for provisioning a menu item extension shows sample content for such a file.

The UrlAction element, within the CustomAction element, defines a new menu item that targets the ECB menu of any item within a document library, as declared by attributes RegistrationType = List and RegistrationId = 101. For further details about the various options for the attributes of CustomAction and UrlAction elements, please read Chapter 12. Notice also the Id attribute of the CustomAction element, which defines the unique ID of the menu item and should be a unique literal value. Moreover, the Url attribute defined in the UrlAction element can reference content under the app web, in case you start the URL with the ~appWebUrl token. Otherwise, if the target content is under the host web, you can start the URL with the ~remoteAppUrl token.

The next steps are to create a page with a name corresponding to the one you provided while defining the custom action, and to start debugging the app. To create a new page, right-click the Pages folder in the SharePoint app project and select Add | New Item | Page. Moving into a document library within the host web, you will notice that the ECB menu contains the new item Send Document To The Contacts App (see Figure 8-20). Click this menu item and you will be redirected to the custom page you just created.

A screen shot illustrating the behavior of the custom menu item. It displays the classic ECB menu for a document, enriched with a new menu item with a caption value of Send Document To The Contacts App.

Figure 8-20. The custom menu item extension in action.

Behind the scenes, the SharePoint environment invokes a GET method to redirect the browser to a URL such as the following:

_layouts/15/appredirect.aspx?client_id={clientId}&redirect_uri=%7EappWebUrl%2FPages%2FSendDocument%2Easpx

where the {clientId} argument is a token describing the current context. If you want to provide some arguments to the target URL—for example, the ID of the source document or the ListId of the source library—you can modify the Url attribute of the UrlAction element, including some predefined tokens. Here is a sample Url value for this purpose:

<UrlAction Url="~appWebUrl/Pages/SendDocument.aspx?ItemId={ItemId}&ListId={ListId}" />

All the available URL tokens will be discussed in the “Custom actions” section of Chapter 12.

Many menu item customizations apply to custom ribbons, as well. To add a custom ribbon, for example, right-click the SharePoint app project and select Add | New Item | Ribbon Custom Action. A wizard will ask you questions very similar to those for creating a new menu item. This time, however, you can choose from only three scope values: List Template, List Instance, and None. While the first two scopes are the same as before, while creating custom menu items, the None option creates a ribbon command independent from any target scope.

The second step of the wizard (Figure 8-21) is specific for ribbons and asks you to provide information about the location of the ribbon command, the caption, and the target URL. The location of the ribbon can be one of the predefined locations (see Chapter 12) or a custom location.

A screen shot depicting the second step of the wizard for creating a new ribbon command extension. It includes an editable drop-down list for selecting the target location, a text box to provide the caption for the ribbon command, and an editable drop-down list for selecting or writing the relative URL of the page that will be invoked when the user selects the menu item.

Figure 8-21. The second step of the wizard for creating a new ribbon command extension.

Once again, the result of the wizard will be an XML file defining a feature element of type CustomAction. This time, the CustomAction will use the syntax to define a ribbon command. (For more details about defining ribbon commands, ribbon tabs, and groups, read Chapter 12.) An interesting thing to notice is that with a ribbon command, you can either define a target URL to redirect the end user to, or you can provide a JavaScript set of instructions to execute directly in the context of the current page. A sample feature element for provisioning a menu item extension shows the resulting XML feature element, while Figure 8-22 illustrates the resulting ribbon command.

A screen shot of the new ribbon command extension, highlighted with a red square.

Figure 8-22. The custom ribbon command extension created in the sample.

Autohosted apps

This section will move on from the SharePoint-hosted scenario to discuss the autohosted hosting model. The autohosted model uses a site that is automatically provisioned for you on Windows Azure websites. Thus, you can take advantage of the out-of-the-box capabilities of Windows Azure websites, including multitenancy, load balancing, high availability, and support for the SQL Azure data repository.

Creating an autohosted app

From a practical viewpoint, an autohosted app can do almost everything a SharePoint-hosted app can do. However, by default, an autohosted app does not have an app web for storing data and information; instead, it uses a persistence infrastructure of its own, which can be based on SQL Azure. The autohosted model works only for SharePoint sites hosted on Office 365 or SharePoint Online. At the time of this writing, Microsoft has not yet announced the pricing model for hosting apps on Windows Azure websites. In fact, so far, apps hosted on Windows Azure cannot be published to the Office Store.

To create an autohosted app, you can start Visual Studio 2012 and create a new SharePoint app. In the first step of the resulting wizard, provide the URL of an Office 365–hosted site and choose the autohosted hosting model. The procedure may be similar, but the solution outline (see Figure 8-23) is slightly different compared to a SharePoint-hosted app.

A screen shot of the outline of an autohosted app for SharePoint. It displays a SharePoint app project at the top, including two files (AppIcon.png and AppManifest.xml). On the right, in the Solution Explorer pane, is a classic ASP.NET web project.

Figure 8-23. The solution outline for an autohosted app for SharePoint.

The outline includes a classic ASP.NET web application, which can be any kind of ASP.NET web application, as well as a SharePoint app project, which contains only the AppIcon.png and AppManifest.xml files. These two files are the same as those of a SharePoint-hosted app. You could add to the SharePoint app project feature elements for provisioning content types, pages, lists, and so on; however, these elements would require an app website. On the contrary, because you are developing an autohosted app, you will probably prefer to benefit from the Windows Azure environment instead of using SharePoint for storing data and content of your app.

The ASP.NET web application is made of a Pages folder with a Default.aspx page, a Scripts folder with some useful JavaScript files, the classic web.config file, and a TokenHelper.cs file, which supports the application in managing and handling the secure communication with SharePoint. The Default.aspx file, unlike the SharePoint-hosted app page, will have some .NET code behind it. If you open the Default.aspx.cs file, you will find code similar to The .NET code behind the Default.aspx page of an autohosted app.

The main part of the code is the Page_Load method, where the page retrieves the Title property of the host web and writes it back to the HTTP response. Because the autohosted app site is hosted outside SharePoint, the code needs to retrieve a security context token with proper authorizations to access the host web and its properties. The following line does the magic:

var contextToken = TokenHelper.GetContextTokenFromRequest(Page.Request);

It uses the TokenHelper class, which is automatically generated by the project template, and that class reads a few arguments from the query string to create a secured communication session against the host web. The code of the TokenHelper class is open, you can read it and eventually change it. Of course, just because you can it does not mean you should change it. Probably the best thing to do is to read through the TokenHelper class—without changing it—to better understand how it works with the CSOM. You can see that the page uses the CSOM to retrieve the Title of the host web and creates a ClientContext object instance based on the contextToken gained through the page request. You can replace this code with anything else, and if you like to interact with the host web, you can simply use the CSOM to provide an authenticated and authorized context token to the ClientContext. (For more thorough detail on the CSOM, see Chapter 7.)

If you start debugging the app, you will have to provide credentials to access the Office 365 environment before you are presented with the page for trusting the app. Because an autohosted app works outside the context of SharePoint, you will always have to trust it during installation. Next, you will be redirected to the site hosting the app. Notice that while debugging in your development environment, the autohosted app site will run locally on Internet Information Services (IIS) Express so that you can debug it on your local machine. In the next section, you will learn how to publish the app, once you have finished development and testing.

As you can see from the output of the app in the web browser, you can control all the UI and UX details for an autohosted app. Thus, the layout of the output is up to you and your code.

Converting a site to a SharePoint app

Starting from scratch is one way to create your SharePoint App, but luckily for ASP.NET developers, there is another way: you can convert a classic ASP.NET project into a SharePoint autohosted app, meaning you can take advantage of the new and more productive MVC4 (Model-View-Controller 4.0) pattern available in ASP.NET 4.x. To try this option, create a new solution made of an ASP.NET 4.0 site based on MVC4, or use an already existing site you want to convert to a SharePoint app. Right-click the web project node in Solution Explorer and select the Add App For SharePoint Project menu item (Figure 8-24). Of course, you can use this functionality against any kind of ASP.NET project, not only with MVC4 sites.

A screen shot illustrating the menu item for creating a new SharePoint app, starting from an existing ASP.NET website.

Figure 8-24. The menu item for creating a SharePoint app from an already existing ASP.NET website.

Important

Do not choose a .NET version greater than 4.0 because, at the time of this writing, ASP.NET 4.5 is not supported by the autohosted apps environment on Windows Azure. Of course, this might change in the future.

Next, provide the URL of the host web, on Office 365 or SharePoint Online, for publishing the already existing ASP.NET website. Once you do, a new SharePoint app project will be added to the solution and some new references will be added to the ASP.NET web project. The name of the SharePoint app project will be the same of the ASP.NET web project, ending with the .SharePoint suffix. Moreover, the action will add a TokenHelper class to the ASP.NET web project, in order to support the SharePoint 2013 authentication and authorization environment. Now, the ASP.NET web project is the UI for the SharePoint app project. In fact, if you open the property grid of the SharePoint app, you can see that the MVC4 project is configured in the Web Project property of the app. See Figure 8-25 for details.

A screen shot depicting the properties of the SharePoint autohosted app, including the Web Project property for wiring the SharePoint app with a specific website, which will be published on Windows Azure.

Figure 8-25. The property grid of the SharePoint autohosted app with the Web Project property in evidence.

Handling a SQL Azure database

As you can see from Figure 8-25, there are also properties for configuring a SQL Database project and a SQL Data script. Suppose the example autohosted app uses a custom SQL Azure database on the back end for storing contacts data. In this case, you can add a new SQL Server database to the current solution. To do so, right-click the solution and choose Add | New Project | SQL Server Database Project. Open the properties of the database project and configure its target platform to SQL Azure.

More Info

If you do not configure the target platform to SQL Azure, Visual Studio will advise you and change it for you, as soon as you wire the SQL Database project to the SharePoint app. In fact, the only database platform supported by autohosted apps is SQL Azure.

Now add a new table for holding contacts to the database project (Add | New Item | Table) and configure some fields. For the sake of simplicity, in addition to the Id primary key field, configure just the following text fields: ContactDescription, ContactPhone, and ContactEmail. The final layout of the table will be similar to Figure 8-26.

A screen shot of the design of the Contacts table, which includes Id, ContactDescription, ContactPhone, and ContactEmail fields. It also includes the T-SQL script for creating such a table.

Figure 8-26. The designer of the Contacts table defined in the SQL Azure database.

Now you can configure the SQL Database project as the target database for the SharePoint app simply by selecting the new database project in the SQL Database property of the SharePoint app project.

To autopopulate the database with sample data, you can add an SQL script to the project and configure it in the SQL Data Script property of the SharePoint app. In real scenarios, you will probably use this script to autopopulate lookup tables, as well as to execute any other SQL script that you will need to commit just after having created the SQL Azure database.

The .NET code to retrieve the SqlConnection object of a SQL Azure database for an autohosted app provides the code excerpt you can use to retrieve an instance of a SqlConnection object for accessing the SQL Azure database—for example, for using it with Entity Framework. In fact, you cannot configure the connection string directly in the web.config file of your autohosted app, because while writing your app you won’t know where the SQL Azure database will be deployed. To solve this issue, the SharePoint Client Object Model provides you with a class named AppInstance, which has a method called TryGetAppDatabaseConnectionDirect that accepts the current ClientContext instance and a couple of output arguments for trying to retrieve the current database connection.

While working locally, the SQL Azure database will be deployed on your local machine under a connection string like the following:

Data Source=(localdb)Projects;Initial Catalog=DevLeap.SP2013.ContactsAppAutoHosted.DB;Integrated Security=True;Pooling=False;Connect Timeout=30;ApplicationIntent=ReadWrite

While on Windows Azure, the connection string will map to a real SQL Azure environment. Now you are free to use the database from any kind of code for accessing the database, such as direct System.Data.SqlClient objects, Entity Framework, or whatever else you like. In the companion source code, you will find a complete code example of using Entity Framework for accessing the Contacts entities, rendering the output in a read-only grid. Take a look at the result in Figure 8-27.

A screen shot of the default page of the autohosted Contacts app, shown while reading the contacts from the SQL Azure database. A GridView control renders some contacts read from the database, but otherwise the page is poor from a UI or UX perspective.

Figure 8-27. The sample SharePoint app based on SQL Azure rendering the list of Contacts entities.

The SharePoint Chrome control

As shown in Figure 8-27, the output is extremely simple, leaving a great deal of room for improvement to the UI and UX. For example, the app is missing a command bar to interact with the SharePoint environment, as well as a Back button to return to the host web. Such UI components were provided by default for SharePoint-hosted apps. You could create chrome to mimic a SharePoint-hosted app, but you don’t have to: SharePoint provides a control called a Chrome control, which renders based on some HTML/JavaScript/CSS code and can be included in any SharePoint app page. The Default.aspx page of the autohosted app with the Chrome control in place provides the source code of the Default.aspx page of an autohosted app with the Chrome control in place.

The code contains a couple of JavaScript inclusions in the header of the page. Taken from the official Microsoft CDN, these JavaScript files support jQuery and AJAX. Next, an explicit script injects the JavaScript file SP.UI.Controls.js from the source host web URL. Moreover, the script prepares the Chrome control for rendering, providing the ID of a DIV control that will be the placeholder for the Chrome control, as well as a set of options. These options define the title, icon, help page URL, and additional Settings menu links for rendering in the Chrome control. Compare Figure 8-28 with Figure 8-27 to fully appreciate the results of this makeover. Notice the custom items in the Settings menu, as well as the Back button to return to the host site.

A screen shot of the Default.aspx page of the autohosted app after enrichment with a Chrome control. There is a top bar for rendering the chrome of the page as it would be in a classic SharePoint environment. There is also a Settings menu with custom settings items.

Figure 8-28. The Default.aspx page of the autohosted app, with the Chrome control in action.

One last thing to emphasize about the Chrome control is that when you change the design of the host site, the app site will reflect the same choices because the Chrome control loads its styles dynamically.

Provider-hosted apps

A provider-hosted app is almost like an autohosted app, except it uses a third-party provider for hosting the web application rather than Windows Azure websites. The third-party provider can manually provision Windows Azure or can be based on anything else, even an on-premises server farm of your own. On its second page, the Visual Studio wizard for creating a provider-hosted app asks you to choose between using Windows Azure Access Control Services (ACS) for authentication and authorization, rather than using a high-trust configuration based on a private certificate and asymmetric keys exchange (see Figure 8-29). The first choice is suitable when your app will be used on sites hosted on Office 365. The second choice, High Trust, is suitable for on-premises scenarios and will be discussed later, in the “Security infrastructure” section.

A screen shot illustrating the second step of the wizard for publishing a provider-hosted app. It includes a choice between using Windows Azure ACS or specifying a certificate for managing authentication and authorization of the app.

Figure 8-29. The second step of the wizard for creating a provider-hosted app.

Behind the scenes, the only difference between an autohosted app and a provider-hosted app is a line in the AppManifest.xml file. An autohosted app has the following piece of XML in the AppPrincipal element:

<AppPrincipal>
    <AutoDeployedWebApplication/>
  </AppPrincipal></programlisting>
<para>while a provider-hosted app contains this:</para>
<programlisting><AppPrincipal>
    <RemoteWebApplication ClientId="*" />
  </AppPrincipal>

As you can see, the ClientId attribute has a value of * (that is, any) because you will have to provide the real value for this data during the publishing phase only. While developing and debugging, you will not need it. Instead, you will use the localhost site hosted by IIS Express. (Again, the “Security infrastructure” section provides more detail.)

Publishing apps and the Office Store

Now you are ready to publish your app to your customers, using either a corporate app catalog or the Office Store. Regardless of which you choose, you need to prepare the proper output files first. In this section, you will learn how to achieve these results.

Deploying a SharePoint app

Invoking the Deploy command for a SharePoint-hosted app or an autohosted app is easy: simply right-click the app project in Visual Studio Solution Explorer and click the Deploy command on the menu. The result will be a complete deployment of your app on the target platform. For example, your autohosted app will be packaged and published for you on Office 365 and on Windows Azure. Now you can test this project while running completely in the cloud or while on the target platform. Suppose you deployed the autohosted Contacts app on your developer site in Office 365. After deployment, the autohosted app will be executed from a dedicated hosting infrastructure, using Windows Azure websites and SQL Azure on the back end, instead of being executed from your localhost using IIS Express and the local SQL Server Express. Of course, in this last scenario, you will not be able to debug the server code. The URL of your app will become something like the following:

https://52b8b0c7-78da-4a07-9d2b-3190e07625f5.o365apps.net/

As you can see, the URL references the Office 365 autohosted apps environment (o365apps.net), and every app installation receives a unique GUID-based host name. If you want to remove the app, you can invoke the Retract menu item, still available by right-clicking the app project in Solution Explorer, or you can explicitly remove it from the target host site.

Publishing a SharePoint app

When you’re ready to publish your app, right-click the SharePoint app project in Solution Explorer and choose Publish from the menu to open the publishing wizard. For SharePoint-hosted and autohosted apps, the wizard only allows you to click the Finish button to create the package for publishing. The result will be an APP file placed inside the app.publish subfolder of the Debug or Release folder of the project, depending the compilation type you are using.

Important

When publishing a final release of your app, compile it in release mode. Do not publish the APP file taken from the Debug folder; publishing software compiled in debug mode is a very bad practice for security and performances reasons. Because the publishing wizard opens the destination folder for you by default, as long as you publish the app while in release mode, you should be safe.

The APP file is an ordinary ZIP file, but with .app extension instead. In fact, if you change the file extension from .app to .zip and you explore the content, you will find files and folders describing the app for publishing. For an autohosted app, for instance, you’ll see the AppIcon.png file, the AppManifest.xml file, a DACPAC file for provisioning the database on SQL Azure, a ZIP file for provisioning the website onto Windows Azure websites (if necessary), resource files, and so on. For SharePoint-hosted apps, you will see the AppIcon.png file, the AppManifest.xml, and the resources files, as well as a WSP file, which will be used for provisioning all the SharePoint artifacts onto the app website. Figure 8-30 compares the outline of two APP files: one for a SharePoint-hosted app (on the left) and one for an autohosted app (on the right).

A screen shot comparing the contents of the APP file of a SharePoint-hosted app (left) and an autohosted app (right). The SharePoint-hosted APP file contains more files because it includes the provisioning of artifacts on the target SharePoint-hosted app web, while the autohosted APP file uses a smaller number of files, because it stores the content of the autohosted app in a dedicated ZIP file for publishing onto Windows Azure websites.

Figure 8-30. The contents of a SharePoint-hosted app’s APP file (left) and an autohosted app’s APP file (right), once renamed into ZIP.

In either case, you can manually upload the resulting APP file to a developer site for testing, publish it to a corporate app catalog, or submit it to the Office Store to make it publicly available.

While publishing a provider-hosted app, you are presented with a rich wizard. The first page asks you to select or create a new publishing profile (see Figure 8-31). It even offers you options for multiple profiles for testing, staging, production, and so on.

A screen shot of the first page of the wizard for publishing a provider-hosted app. From the single drop-down list, you can select or create a publishing profile.

Figure 8-31. The first step of the publishing wizard for publishing a provider-hosted app.

The second page (Figure 8-32) asks you to provide information about the hosting environment, including the URL of the target site, the client ID, and the client secret for secure communication between SharePoint and the provider-hosted app. You can retrieve the client ID and client secret values from the Seller Dashboard available on the Office Store, or you can generate them from the target host site. (For more information, see the “Security infrastructure” section later in the chapter.

A screen shot of the second step of the wizard for publishing a provider-hosted app. It contains a drop-down list for selecting or writing the URL of the target host site, as well as client ID and Client Secret text fields.

Figure 8-32. The second step of the publishing wizard for publishing a provider-hosted app.

The last page is just a recap of your settings. This time, the result of the publishing wizard will be a set of files: an APP file for publishing the app, a DEPLOY file (web deploy file) for the website deployment, and a ZIP file with the contents of the website.

The corporate app catalog

To publish an app to the corporate app catalog, you need to have the URL of the corporate app catalog site collection configured for your current web application or tenant, as well as a set of authorized credentials for publishing apps. Then you can simply upload the APP file to the catalog into the Apps For SharePoint library. The results will be similar to the corporate app catalog in Figure 8-33. In the section “App management configuration and deployment,” you will learn how to configure an app catalog on your farm.

A screen shot of the Apps For SharePoint library of a sample corporate app catalog. It displays a list of apps, each one identified by a unique product ID, which is a GUID.

Figure 8-33. The list of apps for SharePoint published in a corporate app catalog.

Once you have configured a corporate app catalog for a web application or tenant, and you have published some apps on it, you can add an app to a target site by clicking Site Contents, and then Add An App. You can then choose apps published through the corporate app catalog by browsing a specific category of apps called From Your Organization. Figure 8-34 shows how the apps are presented to the end user. Notice that, for the sake of completeness, the app catalog in the figure also contains an autohosted app, which is not available in an on-premises scenario. Thus, the app catalog highlights this issue and does not allow the user to install that app.

A screen shot illustrating the corporate app catalog for installing an app in an on-premises scenario. It includes a list of apps available for installation. One app is flagged as not suitable for the on-premises scenario, because it is an autohosted app, which cannot be installed on-premises.

Figure 8-34. The user’s view of the apps in a corporate app catalog.

If you are a farm administrator, you will be able to monitor app installation and usage from SharePoint Central Administration (SPCA).

The Office Store

What if you want to make your apps available for the entire world? In that case, you need to rely on the Office Store provided by Microsoft (http://www.office.com/store). To do so, you first need to create a seller account for publishing apps. With a valid and enabled account, you can access the Seller Dashboard at https://sellerdashboard.microsoft.com. There, after logging in with a valid Windows Live ID, you will be able to submit an app, manage your already submitted apps, register client IDs, and monitor metrics of selling and downloads of your apps. Figure 8-35 shows the first step for creating an app profile. You have to choose whether you are publishing an app for Office or SharePoint, or an app for Windows Azure. Note, however, that the Seller Dashboard is the same for both types of apps.

More Info

For further information about how to create a seller account, read the document “How to: Create or edit your seller account in the Microsoft Seller Dashboard,” available on MSDN online at http://msdn.microsoft.com/en-us/library/office/apps/jj220034.aspx.

A screen shot of the first page of the wizard for publishing a new app on the Office Store. The page provides options for specifying the app’s type: App For Office, App For Outlook, App For SharePoint, Active Directory App, and Catalog App.

Figure 8-35. The first page of the wizard for submitting an app to the Office Store through the Seller Dashboard.

Click Next to go to the page for providing information about the app (title, version number, logo, category, screen shots, target markets, trial periods, and so on). As shown in Figure 8-36, during this phase you also must provide the APP file package.

A screen shot illustrating the second page of the wizard for publishing an app. The page includes fields for configuring all the relevant details, including the app title, version, release date, category, logo, testing notes, APP package file, duration of trial, and number of users in trial.

Figure 8-36. The second page of the wizard for submitting an app to the Office Store through the Seller Dashboard.

On the third page (Figure 8-37), you can provide descriptive information, up to five screen shots with a fixed size of 512×384 pixels, license information, and so on.

A screen shot of the third page of the wizard for publishing an app to the Office Store. There are controls for configuring descriptive information, screen shots of the app, support links and documents, and an end-user license file.

Figure 8-37. The third page of the wizard for submitting an app to the Office Store through the Seller Dashboard.

On the wizard’s last page, shown in Figure 8-38, you can configure the price for your app or choose to make it freely available.

A screen shot of the final page of the wizard for publishing an app to the Office Store. You can specify whether your app is free or for purchase. The drop-down menus enable you to set a price per user, as well as a price threshold depending on the number of users.

Figure 8-38. The last step for submitting an app to the Office Store through the Seller Dashboard.

Note

You must provide your app’s price on a per-user bases, but you can also specify the maximum number of user licenses that a customer can buy. If a customer buys a number of user licenses higher than the price threshold you set, he or she will pay only for the number of licenses configured in the Price Threshold field. Imagine you configure a price of $9.99 with a price threshold of 10 (as in Figure 8-38). Then, if a customer buys 20 copies of your app, he or she will pay only $99.90 (the price of 10 licenses), but will have the right to use up to 20 licenses.

Your app will be verified and checked against an approval process based on the rules outlined at the following URL: http://msdn.microsoft.com/en-us/library/office/apps/jj220035. Upon approval completion, your app will be available worldwide either on Office 365 or on-premises (as long as the farm administrators of the on-premises farm have enabled the capability to freely install apps from the Office Store).

As a seller, you will be able to monitor how your app sells on the market, as well as your revenues in the case of for-purchase apps.

Upgrading apps

The app model of SharePoint also provides a standard path for upgrading your apps. Whether you need to upgrade your app to fix a bug or add new features, the process is the same:

  1. Create a new APP package with a new version number.

  2. Change that information in AppManifest.xml file.

  3. Upload the file again to the Office Store or app catalog.

Upon changing the version number and republishing the app, you will have a new subfolder in the app.publish folder. From there you will be able to get the new upgraded APP file.

For apps published through the Office Store, however, you will need to submit the new and updated version for approval before publishing to the end users. For apps published through a corporate app catalog, you simply update the APP file in the catalog’s target Apps For SharePoint library. Regardless of the publishing environment you are using, existing installations will not be upgraded automatically. Instead, end users who have installed the app will be informed by the environment that a newer version is available, as shown in Figure 8-39.

A screen shot of the details panel of an installed app. A message states that an updated version of the app is available on the catalog, providing the new version number and release date. Authorized users can click the Get It button to upgrade the current version of the app to the latest one.

Figure 8-39. The notification of an available upgrade for an installed app.

Authorized users can upgrade the app by clicking the Get It button. During the upgrade process, the user will have to trust the app again. In fact, the upgraded version could have changed the permissions requirements. During the upgrade process, the app will show an informational message while on the Site Contents page.

The upgrade process for SharePoint-hosted apps is simple and easy. For autohosted apps, the upgrade of the Windows Azure website is handled on the Azure platform. The upgrade process for provider-hosted apps also involves the external publishing infrastructure, so be careful while upgrading these apps. In fact, you should not upgrade a provider-hosted app site introducing breaking changes, unless you are absolutely sure that all of your existing customers and users have already upgraded the app on their SharePoint environments. Usually, in these cases it would be better to keep different versions of the app online, on the provider side, to support customers who are reluctant to upgrade to the new versions of your app.

App management configuration and deployment

While you work on Office 365, the entire environment and application software is provided as a service, ready to use, according to the Software as a Service (SaaS) offering model. However, also having an on-premises farm that’s fully functional and capable of supporting SharePoint apps can be very useful, especially while working in a development environment. In this section, you will learn how to configure a SharePoint 2013 on-premises farm to provide full support for the new app model. This section will assume that you already have a SharePoint 2013 farm ready for the app environment configuration.

First, you will need to configure the required service applications: the Subscription Settings service and the App Management service. To do so, you can use SPCA, or you can run a PowerShell script, as in A PowerShell script for configuring the services required for running the app model on-premises.

The very beginning of the script declares four literal variables that you can configure based on your naming conventions. The script simply creates the Subscription Settings service application, together with its proxy, and starts an instance of the service on the current server. The same happens for the App Management service application.

To configure the App Management service for supporting apps, first create a web application for hosting apps. To define such a web application, you need to determine the host name that will be used for that web application. For example, you could decide to install all the apps under a top-level domain dedicated to hosting apps (something like company-apps.com), or you could host apps in a subdomain of the main domain of your on-premises farm (something like apps.company.com). The former scenario is the one recommended by Microsoft in official product deployment guidelines. Configure your DNS accordingly by creating a catchall CNAME record in a new top-level domain or a subdomain in the already existing domain. The CNAME record should map to the host name where the apps will be installed. For example, in case your domain and host name is company.com, the CNAME will be for * or for *.apps, respectively, and should map to company.com.

Next, create a new web application for hosting the apps and the app websites. Once again, you can use SPCA or PowerShell. A PowerShell script for creating the web application for hosting apps demonstrates the PowerShell method.

The script creates a new web application on the default server host name using the default configuration for claims-based authentication, and creates a root site collection based on the Blank Site template (STS#1). Again, the variables defined at the beginning of the script should be configured according to your farm and naming conventions.

To finalize the configuration of the services, you should configure the app domain name and the app prefix, which will be the name of the domain used for the autogenerated host names for hosting apps, as well as the prefix used while generating the host names. You can do that from SPCA by choosing Apps and then Configure Apps URLs in the App Management section. You can also still use PowerShell, executing the following two lines of code:

Set-SPAppDomain company-apps.com
Set-SPAppSiteSubscriptionName -Name "apps" -Confirm:$false

In the first line, you configure the domain name, which in the example is a top-level domain with a value of company-apps.com. While in the second line, you configure the prefix, which is “apps”. Thus, the resulting apps URLs will be something like this:

Error! Hyperlink reference not valid.

Important

For security reasons, it is strongly suggested to host apps under a secured site, which provides its content via HTTPS. For testing and development purposes, however, you can host apps in your development environment in a site published over HTTP. Moreover, when registering autohosted apps or provider-hosted apps, either on-premises or on the Seller Dashboard of the Office Store, you are obliged to provide a URL over HTTPS.

To complete the installation of your environment, you should configure an app catalog for providing corporate apps to your users. To do that, you need to have a corporate catalog site collection available in your web application or tenant. The template to use is APPCATALOG#0, and you can create it using the New-SPSite cmdlet or SPCA. Still using PowerShell, you can configure a site for being the app catalog using the following syntax:

Update-SPAppCatalogConfiguration -Site "http://www.company.com/sites/AppCatalog" -Force:$true -SkipWebTemplateChecking:$true

The URL of the site collection passed to the cmdlet will determine the target web application or tenant for the command. Otherwise, you can use SPCA, navigate to the Apps page, and select the Manage App Catalog menu item in the App Management group. There you will be able to create a corporate app catalog site collection from scratch and associate it with the target web application or tenant.

Security infrastructure

The last topic to cover in this chapter is the security infrastructure behind the scenes of the SharePoint app model. As you know, every SharePoint app uses an app principal, which represents the identity of the app and determines the app’s authorizations for accessing resources. This security environment uses the Security Token Service (STS) available in SharePoint, SAML (Security Assertion Markup Language) tokens, and the OAuth access tokens. The whole environment is based on the claims-based authentication model, which is the default authentication model in SharePoint 2013.

Important

Apps are not supported in SharePoint web applications configured with classic mode authentication.

The hosting method you choose for your app determines how it handles authentication. For example, SharePoint-hosted apps run on an app web, which is a subsite of the host web. When working in app websites, you can take advantage of internal authentication, which allows your app code to use the CSOM and REST for accessing both the app web and the host web, without requiring explicit app authentication code. (Of course, you still will need explicit permissions.) On the contrary, autohosted and provider-hosted apps run on external, remote websites. In these cases, your code will need to use external authentication, which is explicit authentication based on Windows Azure ACS or a server-to-server (S2S) trust relationship. To be authenticated and authorized for accessing resources, autohosted and provider-hosted apps require OAuth access tokens. The access tokens can contain information about the app only, or can carry information about a user identity inside a context token.

In all hosting cases, you can use policies within your code to enforce authorizations for both the user and the app. When an app calls SharePoint using the CSOM or REST from client-side code, for example, both the user and the app need to adhere to the required permissions. If either of them misses the proper permissions, the app code will fail with an access-denied exception. When an autohosted or provider-hosted app executes server-side code, your policy needs to enforce authorization for the app only. You must explicitly enable this scenario in the app’s AppManifest.xml file by setting the AllowAppOnlyPolicy attribute to true in the AppPermissionsRequests element. Only site collection administrators can grant use of the app-only policy. If the app-only policy is granted and the app already has tenant-scoped permissions, then the user must be a tenant administrator to grant use of the app-only policy. Finally, to use this capability in server-side code, you will need to invoke the GetAppOnlyAccessToken method of the TokenHelper class for retrieving a special app-only access token. Behind the scenes, all app-only requests are made by SHAREPOINTAPP, which is a special user that cannot be used during explicit authentication, almost like SHAREPOINTSYSTEM.

All these scenarios are possible thanks to the OAuth protocol and Windows Azure ACS. In Chapter 20 you will learn more about OAuth, ACS, user and app authentication, and the internals of the security infrastructure of SharePoint 2013. For now, however, simply understand that every single time you register an autohosted or provider-hosted app in SharePoint, you will need to provide a client ID and client secret information for securing the authentication and providing a valid and secure access token. When working with autohosted apps, the Office 365 environment must create this information and configure the remote web application to use them. When you work with provider-hosted apps, it is your responsibility to configure the client ID and the client secret in the remote web application. In fact, you have explicit configuration settings to provide while publishing the app, as you have already seen in Figure 8-32. There are also some application pages for managing app principals:

  • /_layouts/15/AppRegNew.aspx. Allows manual registration of a new app, providing the client ID and client secret, as well as the remote domain and redirect URL for the target app

  • /_layouts/15/AppPrincipals.aspx. Enumerates all the registered apps, together with their unique client IDs

  • /_layouts/15/AppInv.aspx. Allows you to retrieve app registration information (title, domain, and redirect URL) based on a provided client ID

When publishing your apps through the Office Store, you must create a client ID and client secret through a wizard on the Seller Dashboard of the Office Store. As shown in Figure 8-40, the first page of the wizard asks you to specify the client ID and the client secret.

A screen shot of the first page of the wizard for creating a client ID and a client secret for an app in Office 365. There are fields to provide the friendly name of the app, the app domain, the URL for redirecting the browser to while starting the app, and the client secret lifetime duration.

Figure 8-40. The first page of the wizard for creating a client ID and a client secret.

After you click the Generate Client ID button, you can review and make note of your settings from the wizard’s recap page, as shown in Figure 8-41.

A screen shot of the recap page provided by the Seller Dashboard. In addition to providing the details of the new client ID and the client secret, the page prominently displays a warning that the information will not be shown again.

Figure 8-41. The recap page of the Seller Dashboard displays your newly created client ID and client secret.

As you can see, the screen provides all the security information (client ID and client secret) and urges you to copy the details to a safe place. For security reasons, you will never be able to come back to this screen after clicking the Done button. If you lose your client ID or client secret, you can’t retrieve them—you must recreate them from scratch.

More Info

For further details about configuring app principals and OAuth, read the document “Tips and FAQs: OAuth and remote apps for SharePoint 2013,” which is available on MSDN online at http://msdn.microsoft.com/en-us/library/fp179932.aspx.

If you cannot rely on OAuth and ACS for authenticating an app principal, you can use S2S authentication, which requires you to configure a trust relationship between SharePoint and your app. This rarely used scenario works only on-premises and uses a certificate, to whose private key the app code should have access. This is a high-trust scenario, because the app is trusted by SharePoint but still has a restricted set of permissions. It is not a full-trust solution, in which the code can do almost everything. Moreover, a high-trust app is responsible for authenticating the end users, because it cannot use the capability of OAuth 2.0 and ACS to transfer the user identity through the context token. To configure this scenario, you will need to provide the app with an X.509 certificate, as well as execute some PowerShell scripts to register the certificate and the trust on the SharePoint side.

More Info

For further details about configuring a high-trust scenario, read the document “How to: Create high-trust apps for SharePoint 2013 using the server-to-server protocol (advanced topic),” available at http://msdn.microsoft.com/en-us/library/fp179901.aspx.

Summary

In this chapter, you learned a great deal about the architecture of SharePoint apps. Specifically, you learned the differences between SharePoint-hosted, autohosted, and provider-hosted apps, as well as how to develop them. Then you explored the internals of the AppManifest.xml file of SharePoint apps. You discovered how to deploy and publish an app, either on a corporate app catalog or on the Office Store. Lastly, you examined the workings of the security infrastructure of the SharePoint app model. Now you are ready to create your own apps and publish them.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset