How to: Create app parts to install with your app for SharePoint

apps for SharePoint

Learn how to create an app part in SharePoint 2013 that is available in the Web Part gallery of the host web when you install your app for SharePoint.

Last modified: January 03, 2014

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

In this article
Prerequisites for using the example in this article
Create an app part to install on the host web
Next steps
Additional resources

With app parts, you can show your app user experience right in the SharePoint website pages. An app part displays the webpage you specify by using an IFrame (also referred to as a frame) in a page in the host web. Figure 1 shows how the app part content is displayed in a SharePoint page.

Figure 1. App part content displayed in a SharePoint page

App part content displayed in a SharePoint page

App parts are an app-specific implementation of client Web Parts that are available for users in the host web. The app part appears in the App Part gallery when a user installs the app for SharePoint that includes it. Your users can further customize the app part using the properties that you provide.

The example in this article uses a webpage that is hosted on a remote server, not on SharePoint, as the content page. Keep in mind that you can also use SharePoint pages to host the app part content, as described in the Next steps section later in this article.

To follow the steps in this example, you need the following:

  • Visual Studio 2012

  • Office Developer Tools for Visual Studio 2012

  • A SharePoint 2013 development environment (app isolation required for on-premises scenarios)

If you need help setting up a development environment, see Start building apps for Office and SharePoint.

There are several tasks required to create and install your app part to the host web:

  1. Create the app for SharePoint and remote web projects.

  2. Add an app webpage for the app part content.

  3. Add the app part feature to the app for SharePoint project.

After completing the tasks, your app part should look similar to Figure 2. Here we can see (1) the app content displayed in a SharePoint page, and (2) the app part custom properties.

Figure 2. SharePoint page hosting a basic app part

Web part page hosting a basic app part

Create the app for SharePoint and remote web projects

  1. Open Visual Studio 2012 as administrator. (To do this, right-click the Visual Studio 2012 icon on the Start menu, and choose Run as administrator.)

  2. Create a new project using the App for SharePoint 2013 template.

    The App for SharePoint 2013 template in Visual Studio 2012 is located under Templates, Visual C#, Office SharePoint, Apps.

  3. Provide the SharePoint website’s URL that you want to use for debugging.

  4. Select Autohosted or Provider-hosted as the hosting option for your app.

Add an app webpage for the app part content

  1. Right-click the web project and add a new Web Form. Rename the Web Form AppPartContent.

  2. Copy the following HTML code and paste it in the Web Form. The HTML code contains JavaScript that performs the following tasks:

    • Provides placeholders for the custom property values

    • Extracts the property values from the query string

    • Renders the property values in the placeholders

    <!DOCTYPE HTML>
    <html>
        <body>
            <div id="content">
                <!-- Placeholders for properties -->
                String property: <span id="strProp"></span><br />
                Integer property: <span id="intProp"></span><br />
                Boolean property: <span id="boolProp"></span><br />
                Enumeration property: <span id="enumProp"></span><br />
            </div>
    
        <!-- Main JavaScript function, controls the rendering
             logic based on the custom property values -->
        <script lang="javascript">
            "use strict";
    
            var params = document.URL.split("?")[1].split("&");
            var strProp;
            var intProp;
            var boolProp;
            var enumProp;
    
            // Extracts the property values from the query string.
            for (var i = 0; i < params.length; i = i + 1) {
                var param = params[i].split("=");
                if (param[0] == "strProp")
                    strProp = decodeURIComponent(param[1]);
                else if (param[0] == "intProp")
                    intProp = parseInt(param[1]);
                else if (param[0] == "boolProp")
                    boolProp = (param[1] == "true");
                else if (param[0] == "enumProp")
                    enumProp = decodeURIComponent(param[1]);
            }
    
            document.getElementById("strProp").innerText = strProp;
            document.getElementById("intProp").innerText = intProp;
            document.getElementById("boolProp").innerText = boolProp;
            document.getElementById("enumProp").innerText = enumProp;
        </script>
        </body>
    </html>
    

    Note that the code expects some parameters in the query string. The app part provides its custom properties through the query string so the webpage can use them. The next task explains how to declare custom properties and how to make them available to the app webpage.

Add the app part feature to the app for SharePoint project

  1. Right-click the app for SharePoint project and add a new Client Web Part item.

  2. In the Specify the client Web Part page dialog box, choose Select or enter a URL for an existing web page. Choose the AppPartContent page in the drop-down list.

  3. Set the following custom properties for the app part.

    Table 1. App part custom properties

    DefaultValue

    Name

    Type

    WebCategory

    WebDisplayName

    String default value

    strProp

    string

    Basic app part category

    A property of type string

    0

    intProp

    int

    Basic app part category

    A property of type integer

    false

    boolProp

    boolean

    Basic app part category

    A property of type boolean

    1st

    enumProp

    enum

    Basic app part category

    A property of type enumeration

  4. Add the following enum items to the enumProp property.

    Table 2. Enum items of the enumProp property

    Value

    WebDisplayName

    1st

    First option

    2nd

    Second option

    3rd

    Third option

  5. Visual Studio generates the following XML code in the elements.xml file of the app part feature.

    <?xml version="1.0" encoding="UTF-8"?>
    <Elements xmlns="http://schemas.microsoft.com/sharepoint/">
        <ClientWebPart
            Title="Basic app part"
            Name="Basic app part"
            Description="This is a basic app part with custom properties." >
            
            <!--  The properties are passed through the query string 
                    using the following notation: _propertyName_
                    in the Src property of the Content element.  
              -->
            <Content
                Src="~remoteAppUrl/AppPartContent.html?strProp=_strProp_&amp;intProp=_intProp_&amp;boolProp=_boolProp_&amp;enumProp=_enumProp_"
                Type="html"/>
            <Properties>
                <Property
                    Name="strProp"
                    Type="string"
                    RequiresDesignerPermission="true"
                    DefaultValue="String default value"
                    WebCategory="Basic app part category"
                    WebDisplayName="A property of type string.">
                </Property>
                <Property
                    Name="intProp"
                    Type="int"
                    RequiresDesignerPermission="true"
                    DefaultValue="0"
                    WebCategory="Basic app part category"
                    WebDisplayName="A property of type integer.">
                </Property>
                <Property
                    Name="boolProp"
                    Type="boolean"
                    RequiresDesignerPermission="true"
                    DefaultValue="false"
                    WebCategory="Basic app part category"
                    WebDisplayName="A property of type boolean.">
                </Property>
                <Property
                    Name="enumProp"
                    Type="enum"
                    RequiresDesignerPermission="true"
                    DefaultValue="1st"
                    WebCategory="Basic app part category"
                    WebDisplayName="A property of type enum.">
                    <EnumItems>
                        <EnumItem WebDisplayName="First option" Value="1st"/>
                        <EnumItem WebDisplayName="Second option" Value="2nd"/>
                        <EnumItem WebDisplayName="Third option" Value="3rd"/>
                    </EnumItems>
                </Property>
            </Properties>
        </ClientWebPart>
    </Elements>               
    
    

    The webpage in the previous task expects the custom properties in the query string. You can use tokens in the query string for every custom property that you define using the notation _propertyName_ (note the underscores before and after the property name). You can use the tokens in the Src attribute of the Content element. This makes the custom properties' values available to the app webpage when the app part is displayed in the SharePoint page.

Build and run the solution

  1. Press the F5 key.

    Note Note

    When you press F5, Visual Studio builds the solution, installs the app, and opens the permissions page for the app.

  2. Choose the Trust It button.

  3. Go to any page in the host web.

  4. Edit the page and add the Basic app part from the Web Part gallery.

    When the app is installed on the host web, the Basic app part is available in the App Part gallery, as shown in Figure 3.

    Figure 3. App part in the App Part gallery

    Basic app part in the web part gallery
Table 3. Troubleshooting the solution

Problem

Solution

The app part does not display any content. The app part displays the following error: Navigation to the webpage was canceled. This error occurs because the browser has blocked the content page.

Enable mixed content. The procedure might be different depending on the browser you are using:

  • Internet Explorer 9 and 10 display the following message at the bottom of the page: Only secure content is displayed. Choose Show all content to display the app part content.

  • Internet Explorer 8 shows a dialog box with the following message: Do you want to view only the webpage content that was delivered securely? Choose No to display the app part content.

Alternatively, you can enable mixed content in the Internet zone that you are working on. For most developers the Internet zone is Local intranet. If this is not the case for you, substitute Local intranet for the Internet zone you are working on.

  1. In Internet Explorer, choose Tools > Internet Options.

  2. In the Internet Options dialog box, on the Security tab, choose Local intranet, and then choose the Custom level button.

  3. In the Security Settings dialog box, enable Display mixed content in the Miscellaneous section.

This article shows how to create a basic app part with custom properties using a remote webpage as the content page. You can also explore the following scenarios and details about app parts.

Use a SharePoint page as the content page

In most cases, a webpage can’t be displayed in a frame if it sends an X-Frame-Options HTTP header in the response. By default, SharePoint pages include the X-Frame-Options header. If you are using a SharePoint webpage hosted on the app web, you might run into the following error (shown in Figure 4): This content cannot be displayed in a frame

Figure 4. App part that can't display its content in a frame

App part that can't display its content in a frame

Be aware that certain scenarios are susceptible to "ClickJacking" attacks when the webpages are displayed in a frame. Carefully evaluate your app part scenarios to make sure there is no risk of ClickJacking attacks.

If your page hosted on the app web is not susceptible to ClickJacking attacks, you can use the AllowFraming Web Part to suppress the X-Frame-Options header from your page’s response. The following code example shows how to use the AllowFraming Web Part on a SharePoint page.

<WebPartPages:AllowFraming ID="AllowFraming1" runat="server" />

You can download an app part code sample that shows how to use a SharePoint page as the content page.

Resize the app part

If you’re using dynamic content in your app part, the content might change its width and height. Due to the dynamic nature of the content, it may not fit in the frame. You may also be using too much space. With dynamic content, it could be difficult to specify a fixed size in your app part declaration. However, you can resize the frame to fit the content’s width and height.

You can use POST messages from your content webpage to specify the frame’s size. The following code example shows you how to send a POST message to resize the frame in which your app part is hosted.

window.parent.postMessage("<message senderId={SenderId}>resize(120, 300)</message>", {hostweburl});

In the example above, the senderId value will be set on the query string of the page automatically by the app part code when the page is rendered. Your page would just need to read the SenderId value off of the query string and use it when requesting a resize. You can retrieve the host web URL from the query string by appending the StandardTokens or HostUrl tokens to the Src attribute in your app part definition. You can download the Resize app parts code sample to see an app part that dynamically resizes.

Use the SharePoint style sheet in your app part content

Since your app part is hosted within a SharePoint page, you might want to make the app part content look like it is part of the page. One way to achieve a similar look and feel is to use the same style classes as the SharePoint page that is hosting the app part. You can make the SharePoint website’s style sheet available to the app part by adding a reference to the defaultcss.ashx file from the app web.

You can see How to: Use a SharePoint website's style sheet in apps for SharePoint for an explanation on how to reference the defaultcss.ashx file in your apps for SharePoint. You can also download the coffeemaker code sample to see an app part that references the style sheet.

Detect when the app part is in edit mode

Users can edit the app part to change its properties. If your app part is in edit mode, you might want to modify the rendering logic or prevent some unnecessary processing from happening. You can use the _editMode_ token to detect if users are editing your app part.

To use the _editMode_ token, add a query string parameter to the Src attribute of the Content element in the app part declaration.

<Content Src="content_page_url&amp;editmode=_editMode_">

The _editMode_ token lets your content page determine if the app part is in edit mode. If the app part is in edit mode, the _editMode_ token resolves to 1; otherwise, the token resolves to 0.

Community Additions

ADD
Show:
© 2014 Microsoft