in SharePoint 2013

Autohosted SharePoint Apps Deep Dive – Part 2

Autohosted SharePoint Apps Deep Dive Part 1

Autohosted SharePoint Apps Deep Dive Part 2

Autohosted SharePoint Apps Deep Dive Part 3

Introduction

In my previous post we explored a simple ‘Hello World’ autohosted app.

Let us now build a real sample – Contacts List app

The app consists of a contacts list and it will allow users to add and read the contacts from the list.

Adding the Contacts List

Remember, since this is an autohosted app:

  • SharePoint items will reside in the app for SharePoint project
  • Non-SharePoint items & the app’s UI will reside in the ASP.NET web project

To add the contacts list, navigate to your app for SharePoint project solution:

  • Right click the solution and choose to Add | New Item
  • Select List item template and input the following name – MyContacts – and click Add
  • Choose to create a customizable list based on Contacts
  • Click Finish

Visual Studio will add your list to the project:

image

Testing MyContacts List

If you are thinking that you can just press F5 and browse to the contacts list as you would normally do with SharePoint solutions – You are wrong!

Unfortunately apps for SharePoint site template does not include the usual SharePoint site template with a quick launch and other menu items.

One possible way is to modify the app’s start page to load the MyContacts list page

In order to change the start page of the app:

  • Open the AppManifest.xml in the app for SharePoint project
  • Notice the Start page is currently set to Default.aspx (in the ASP.Net Web Project)

image

  • Change the Start page to the following:
    • ContactsListApp/Lists/MyContacts

image

  • Press F5 to debug – you will be taken to the contacts list page

image

Now that we have tested the existence of our contacts list, let us change the Start page back to its Default.aspx

App UI

As explained earlier, we will be updating the Default.aspx to include the app’s UI.

In our case it is going to be:

  • A grid view to display the contacts
  • An input form to add a contact

The UI could be as simple as above or as complex as you want. Its your choice and you are not bound by any SharePoint dependencies.

Open Default.aspx and replace the <body> with the following:

<body>
    <form id="form1" runat="server">
        <div>
            <h1><asp:Label ID="txtTitle" runat="server" /></h1>
        </div>
        <div>
            First Name
            <br />
            <asp:TextBox ID="txtFirstName" runat="server" /><br />
            <br />
            Last Name
            <br />
            <asp:TextBox ID="txtLastName" runat="server" /><br />
            <br />
            <asp:Button ID="btnAdd" 
                runat="server" OnClick="btnAdd_Click" 
                Width="120" Height="25" 
                Text="Add Contact" /><br />
            <br />
            <asp:Label ID="lblResults" runat="server" />
        </div>
        <div>
            <h2>Contacts</h2><pre><asp:Button ID
="btnGetContacts" 
                runat="server" Width="120" 
                Height="25" Text="Get Contacts" 
                OnClick="btnGetContacts_Click" /></pre>
            <asp:GridView ID="grdContacts" runat="server" AutoGenerateColumns="true" />
        </div>
    </form>
</body>

The Code

Now let us add some code to add and retrieve contacts

The first thing you will need in order to query and interact with SharePoint from the ASP.Net Web Project is a Context Token which will determine whether you have access to those specified resources (including SharePoint).

Open Default.aspx.cs:

Lets start with the namespaces:

using Microsoft.SharePoint.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI;

Add the following variable and the property to the Default class:

string appWebUrl;
 
public string ContextToken
{
    get
    {
        return ViewState["ctxToken"].ToString();
    }
    set
    {
        ViewState["ctxToken"] = value;
    }
}

Replace the Page Load method code with the following:

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        ContextToken = TokenHelper.GetContextTokenFromRequest(Page.Request);
 
        appWebUrl = Page.Request["SPAppWebUrl"].ToString();
 
        lblResults.Text = "Contact loaded, click "Add Contact" to add a contact to the SharePoint list";
    }
}

Using the TokenHelper helper class we are able to get the context token.

This context token is your key to SharePoint!

We need this context token in order to interact with SharePoint every time, so we store it in the view state. You can store it wherever you want – but make sure it is retrievable. For this blog post I am just saving it in the Page’s ViewState property bag.

As you can see we pass the page request object which will contain the required headers and query strings to the GetContextTokenFromRequest method. This information has everything TokenHelper needs in order to get the context token.

Query strings? To see the standard query strings included in your default page – Open the AppManifest.xml and you will see the Query string property as {StandardTokens}

image

This {StandardTokens} will insert the following query strings to your default page:

  • SPHostUrl={HostUrl}
    • Host web Url
  • SPAppWebUrl={AppWebUrl}
    • App Web Url
  • SPLanguage={Language}
    • Language

Read here for more info on Url string and Tokens

Let us add the method to add a contact:

protected void btnAdd_Click(object sender, EventArgs e)
{
    appWebUrl = Page.Request["SPAppWebUrl"].ToString();
 
    using (var clientContext = 
        TokenHelper.GetClientContextWithContextToken(appWebUrl, ContextToken, Request.Url.Authority))
    {
        List lstContacts = clientContext.Web.Lists.GetByTitle("MyContacts");
 
        ListItemCreationInformation itemCreationInfo = new ListItemCreationInformation();
        Microsoft.SharePoint.Client.ListItem newItem = lstContacts.AddItem(itemCreationInfo);
        newItem["FirstName"] = txtFirstName.Text;
        newItem["LastNamePhonetic"] = txtLastName.Text;
        newItem.Update();
 
        clientContext.ExecuteQuery();
 
        lblResults.Text = "Contact added, click "Get Contacts" to load contacts from the SharePoint list";
    }
}

The code is almost similar to how it is in SharePoint 2010. As you can see we reuse the context token in the TokenHelper method instead of creating one.

Let us now add the code to retrieve contacts:

protected void btnGetContacts_Click(object sender, EventArgs e)
{
    appWebUrl = Page.Request["SPAppWebUrl"].ToString();
 
    using (var clientContext =
        TokenHelper.GetClientContextWithContextToken(appWebUrl, ContextToken, Request.Url.Authority))
    {
        List lstContacts = clientContext.Web.Lists.GetByTitle("MyContacts");
 
        CamlQuery query = CamlQuery.CreateAllItemsQuery(100);
        query.ViewXml =
        @"<View>
            <ViewFields>
                <FieldRef Name='FirstName'/>
                <FieldRef Name='LastNamePhonetic'/>                       
            </ViewFields>
            <RowLimit>10</RowLimit>
            </View>";
 
        Microsoft.SharePoint.Client.ListItemCollection items = lstContacts.GetItems(query);
 
        clientContext.Load(items);
 
        clientContext.ExecuteQuery();
 
        if (items.Count() > 0)
        {
            List<ListItemContact> lstContactsColl = new List<ListItemContact>();
 
            foreach (Microsoft.SharePoint.Client.ListItem listItem in items)
            {
                ListItemContact itemContact = new ListItemContact()
                {
                    FirstName = listItem["FirstName"].ToString(),
                    LastName = listItem["LastNamePhonetic"].ToString()
                };
                      
                lstContactsColl.Add(itemContact);
            }
 
            grdContacts.DataSource = lstContactsColl;
 
            grdContacts.DataBind();
 
            lblResults.Text 
                = "Contact loaded, click "Add Contact" to add a contact to the SharePoint list";
        }
        else
        {
            lblResults.Text 
                = "No Contacts loaded, click "Add Contact" to add a contact to the SharePoint list";
        }
 
    }
}

And the contact data model:

public class ListItemContact
{
    public string FirstName { get; set; }
 
    public string LastName { get; set; }
}

Press F5 to debug and you can now add & retrieve items from the contacts list!

 image

You can download the sample below:

I would highly recommend taking this sample to the next level by adding Remote Event Receivers

Write a Comment

Comment

Time limit is exhausted. Please reload the CAPTCHA.

Webmentions

  • Autohosted SharePoint Apps Deep Dive – Part 1 ← Chaks' Corner November 18, 2013

    […] Debugging Remote Event Receivers in SharePoint 2013 Autohosted SharePoint Apps Deep Dive – Part 2 […]

  • Autohosted SharePoint Apps Deep Dive – Part 3 ← Chaks' Corner November 18, 2013

    […] « Autohosted SharePoint Apps Deep Dive – Part 2 […]