Share via


Pulling data from SharePoint 2013 in Windows Phone 8 and Windows 8 apps

In a recent project a Windows Phone 8 Line of Business (LOB) App was required to pull data from lists on a SharePoint 2013 site and present this data. After some investigation a solution was constructed to satisfy this requirement. This article demonstrates how to do so for Windows Phone 8 and Windows 8 apps.

Alternatives

When initially investigating this problem, I came across the SharePoint SDK for Windows Phone 8 [1]. A first attempt at a solution was using the process detailed on [2] under the section: Authenticating the user in the SharePoint client object model for Silverlight.

However during development this method of authenticating and communicating with SharePoint was limited in that it didn't provide Single Sign On across SharePoint sites. And also, I found the functionality to perform signing out and clearing of an authentication context wasn't working correctly.

This meant that it would limit the app in terms of the features as well as being necessary to include workarounds.

Proposed Solution

To overcome the limitations discussed previously, I decided to handle the authentication and requests manually. The following sections demonstrate this using the common scenario of getting List items from a SharePoint list.

Client Authentication

To communicate with SharePoint you need to have a valid cookie. For a Windows Phone 8 app, this can be done utilising the SharePoint SDK for Windows Phone 8 [1] and the process detailed on [2] under section: Authenticating the user in the SharePoint OData object model. A modified version of the code presented in this article (to use the async/await pattern) is presented below:

 

ODataAuthenticator oat = new ODataAuthenticator();

oat.AuthenticationMode = ClientAuthenticationMode.MicrosoftOnline;

TaskCompletionSource<string> tcs = new TaskCompletionSource<string>();

 

oat.AuthenticationCompleted += (sender, args) =>

{

if (args.Error != null)

{

throw args.Error;

}

else

{

string cookieString = string.Empty; 

foreach (Cookie cookie in oat.CookieContainer.GetCookies(new

Uri("<INSERT SHAREPOINT URL>", UriKind.Absolute)))

{

cookieString += string.Format("{0}={1}; ", cookie.Name,

cookie.Value);

tcs.SetResult(cookieString);

}

};

 

oat.Authenticate(new Uri(("<INSERT SHAREPOINT URL>", UriKind.Absolute));

string cookieValue = await tcs.Task;

 

Getting a SharePoint List

Now that we can get a cookie value, we can make a request to SharePoint. The method below demonstrates how to request the List Items from a SharePoint list and translate the response into objects we can use in the app.

 

public async Task<List<T>> GetListItems<T>(string cookie, string sharepointUri, string listTitle, string odataQueryString)

{

HttpResponseMessage response;

 

using (HttpClient client = new HttpClient())

{

MediaTypeWithQualityHeaderValue media = new

MediaTypeWithQualityHeaderValue("application/json");

media.Parameters.Add(new NameValueHeaderValue("odata", "verbose"));

client.DefaultRequestHeaders.Accept.Add(media);

client.DefaultRequestHeaders.Add("Cookie", cookie);

 

string completeUri = sharepointUri + "_api/web/lists/GetByTitle('" +

listTitle + "')/items";

 

if (!string.IsNullOrWhiteSpace(odataQueryString))

{

completeUri += odataQueryString;

}

 

response = await client.GetAsync(new Uri(completeUri));

}

 

if (response.IsSuccessStatusCode)

{

string json = await response.Content.ReadAsStringAsync();

 

ListContainer<T> container =

JsonConvert.DeserializeObject<ListContainer<T>>(json);

 

return container.Data.Items;

}

else

{

throw new WebException(response.StatusCode.ToString());

}

}

 

This snippet of code is from a Portable class library which uses the following Nuget Packages:

 

  • Json.NET
  • Microsoft HTTP Client Libraries
  • Microsoft BCL Portability Pack
  • Microsoft BCL Build Components

 

This utilises SharePoint's REST service [3]. Looking at the code you will notice a Generic (T) as well as the class ListContainer; these classes are used to map the JSON returned from SharePoint into objects that can be used in the app.

 

So let's work through an example of using this code, say we have a list called Sectors which looks as follows in SharePoint.

 

This list maps to the following JSON:

 

{

"d": {

"results": [

{

… Metadata

 

"FileSystemObjectType": 0,

"Id": 1,

"ContentTypeId": "0x01005DF7DDC996647342B43DEA29F7F6EDEA",

"Title": "Public",

"ID": 1,

"Modified": "2013-07-02T12:38:04Z",

"Created": "2013-07-02T12:38:04Z",

"AuthorId": 20,

"EditorId": 20,

"OData__UIVersionString": "1.0",

"Attachments": false,

"GUID": "0fdc2058-aff1-4ca1-ae7e-71bfd0bf8a04"

}

 

        … List items continued

]

}

}

 

To map this JSON into objects we can use in the app, we need to create some classes. First of all is the ListContainer class which uses a class called ListItems and are as follows:

 

using Newtonsoft.Json;

 

public class ListContainer<T>

{

[JsonProperty("d")]

public ListItems<T> Data

{

get;

set;

}

}

 

using System.Collections.Generic;

using Newtonsoft.Json;

 

public class ListItems<T>

{

[JsonProperty("results")]

public List<T> Items

{

get;

set;

}

}

 

This mapping is all down to the JsonProperty annotation which maps a Class property to the corresponding object in JSON. You can specify the name of the JSON property (as above) if you want to use a different Class property name.

 

The previous classes won't need modifying but the class to represent a SharePoint List item you will need to create. In this example, the Sector class to represent a Sector list item looks as follows:

 

using Newtonsoft.Json;

 

public class Sector

{

[JsonProperty("Title")]

public string SectorName

{

get;

set;

}

}

 

Putting it all together

Finally now we can authenticate with SharePoint and create a request, the last thing we need to do is call the method shown in the previous section. Putting everything together looks as follows:

 

List<Sector> sectorsList = await GetListItems<Sector>(

"<INSERT COOKIE VALUE>",

"<INSERT SHAREPOINT URL>",

"<INSERT LIST NAME>",

null);

 

Summary

This article has shown how to get list items from a SharePoint list and use them within a Windows Phone 8 app. Hopefully this has provided a starting point for authenticating with and manipulating data in SharePoint within a Windows Phone 8 and Windows 8 apps.

 

Resources

  1. SharePoint SDK for Windows Phone 8

    https://www.microsoft.com/en-us/download/details.aspx?id=36818

  2. Overview of the SharePoint 2013 mobile client authentication object model

    https://msdn.microsoft.com/en-us/library/jj163079.aspx

  3. SharePoint REST Service

    https://msdn.microsoft.com/en-us/library/jj164022.aspx

 

Written by Jonathan Harrison

Comments

  • Anonymous
    November 16, 2014
    What would be needed to perform in case I need to have client app that needs to connect to both SharePoint On-Prem (using Windows Auth) and SharePoint Online?