.NET Authors: Jaynesh Shah, Liz McMillan, Carmen Gonzalez, Elizabeth White, Greg O'Connor

Blog Feed Post

How to: Use the SharePoint 2013 REST API from a Windows Store App (Windows 8 Metro)

I’ve recently taken an interest to building Windows Store Apps (aka Windows 8 Metro).  Not because I think I can get rich in the Windows Store but because I think it provides a unique way to present SharePoint data.  If you’re like me, you probably assumed Windows Store App development was just like .NET Framework 4.5 development.  You would be wrong.  The .NET Framework is provided by a single assembly reference called .NET for Windows Store Apps.  It has many of the familiar classes that you have come to expect.  My initial thinking was that I could use the SharePoint Client Object Model directly from my app.  That thinking was also wrong.  It turns out that the Client Object Model has a dependency on System.Web.Service.dll which does not exist in .NET for Windows Store Apps.  Simply put, Window Store Apps only support WCF references.  This means that the REST API is now our best choice.

When it comes to Windows Store Apps, you have a few choices on which programming language to use.  Modern JavaScript is not my strong point, so I am going to demonstrate using C#.  Before we dig into the C# code though, we’ll take a look at how to construct the REST URL.  This article on MSDN does a great job explaining the details of how the URL is built.  Essentially we start with the URL to our site (i.e.: http://server/site) and append /_api/web/lists to it along with a method to get a particular list by title, getbytitle.  To get the items of the list we append /items to it.   In my case, I want to pull the tasks list of a site so it would look something like this.


You can type this right into your browser and see the XML that the REST API returns.  Here’s an example.


There is a lot of XML to take in there.  We’re particularly interested in the content element contain in each entry element.  This has the data from our list items.  However, we can reduce the amount of XML returned significantly by using the $select parameter on the REST URL.  In my case I am going to select a few common fields such as Title, DueDate, and Status.  Here is what the URL looks like now.



You’ll notice that the results are much more manageable now.  We’ll talk about how we can use LINQ to XML here shortly to parse this data into something usable from our Windows Store app. 

Now let’s look at the code that is required to get the data in our app.  Start by creating a new Windows Store App in Visual Studio 2012.  You can do this by choosing your language (C#) and then Windows Store –> Blank App (XAML).


If this is the first Windows Store App you have started in Visual Studio, you will be prompted for your Windows Live credentials.  This allows you to get a certificate so that you can build apps locally.  In our app, we want to bind data, so I am going to create a new Items Page.  This template has many of the components you need to get started quickly with data binding.


When adding the page, you will be prompted to add some dependent files.  Click yes and then you should see your design surface.  Now, open the code-behind of your Items page.  In the LoadState method, we will start the process of retrieving our data and binding it.  We rely on some asynchronous calls to get data from REST, so we will need to put this data in another method and use the async keyword.

protected override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)


    // TODO: Assign a bindable collection of items to this.DefaultViewModel["Items"]




private async void BindData()




Before we start writing the method though, we need to include a few using statements.

using System.Net;

using System.Net.Http;

using System.Xml;

using System.Xml.Linq;

If you have looked at any of the other C# examples for working with the REST API, you will know they are heavily dependent on the HttpWebRequest object.  However, with Windows Store Apps, we have to use HttpClient instead. We’ll start by defining our REST URL from up above.

string restUrl = "http://server/_api/lists/getbytitle('tasks')/items?$select=Title,DueDate,Body,Status,PercentComplete";

To handle authentication we first need to create an HttpClientHandler object.  We want to automatically use the credentials of the currently logged in user so this is required.  To enable this, just set UseDefaultCredentials to true.  There are also other settings required which we’ll talk about below.

HttpClientHandler httpClientHandler = new HttpClientHandler();

httpClientHandler.UseDefaultCredentials = true;

We can now create the HttpClient object by passing the HttpClientHandler to the constructor.

HttpClient client = new HttpClient(httpClientHandler);

We then need to tell the REST API, that we want the result back as ATOM / XML as opposed to JSON.  We do this by setting a few headers.

client.DefaultRequestHeaders.Add("Accept", "application/atom+xml");

client.DefaultRequestHeaders.Add("ContentType", "application/atom+xml;type=entry");

Now, we can send the request to SharePoint and wait for a response.  We use the await keyword on the GetAsync() method which is why we needed the async keyword on the method signature.  The EnsureSuccessStatusCode() method simply throws an exception if a valid 200 HTTP response is not received.

var response = await client.GetAsync(restUrl);


At this point our data has been received back at the client from SharePoint.  Now we need to begin the fun process of parsing it and binding it.  We get the raw string XML data with the following method (also asynchronous).  You could run the app at this point (with a few tweaks) if you wanted to see it in the debugger but we haven’t done anything wit the data yet.


responseBody = await response.Content.ReadAsStringAsync();

Now we need to read the XML into an XDocument object so that we can use LINQ to XML to parse it.

StringReader reader = new StringReader(responseBody);

XDocument responseXml = XDocument.Load(reader, LoadOptions.None);

Now we have the data into something queryable.  However, what we really need is a custom object that we can bind to.  If you look back at the XML, you might have noticed a few namespaces in use in the XML document.  We need to define those or our queries will never work.

XNamespace atom = "http://www.w3.org/2005/Atom";

XNamespace d = "http://schemas.microsoft.com/ado/2007/08/dataservices";

XNamespace m = "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata";

Now, we can use LINQ to XML to select the data into a new anonymous type.  If you look at the XML again, we want to query entry elements using the Descendants() method and then the actual values we want are inside the nested Content and then Properties elements.  The data is heavily nested so it makes our LINQ to XML a little messy.  It’s not too bad though.  For the non-string values, I parse the data into the type that I want it (i.e.: DateTime).

var items = from item in responseXml.Descendants(atom + "entry")

            select new


                Title = item.Element(atom + "content").Element(m + "properties").Element(d + "Title").Value,

                DueDate = DateTime.Parse(item.Element(atom + "content").Element(m + "properties").Element(d + "DueDate").Value),

                Status = item.Element(atom + "content").Element(m + "properties").Element(d + "Status").Value,

                PercentComplete = decimal.Parse(item.Element(atom + "content").Element(m + "properties").Element(d + "PercentComplete").Value)


Now, we have data that can be bound to the GridView / ListView on the Items Page.  To bind we assign our data source as follows:


.DefaultViewModel["Items"] = items;

Just like Windows Phone and SharePoint apps need to declare the capabilities of the application, Windows Store Apps are no different.  To do this, open Package.appmanifest.  In our case, we need to declare that we intend to communicate over the internal network (Private Networks) and that we need Enterprise Authentication.  The latter allows the app to authenticate with the current user’s domain credentials automatically.  If you don’t have this capability set, you are guaranteed a 401 Access Denied or Unable to connect to remote server error.


We can now run the app.  However, there is one last thing we need to do.  We need a way to navigate to the TaskItemsPage that we created.  It loads MainPage by default.  Without getting to deep into how Windows Store app navigation works, we’ll just throw a button on the MainPage and then navigate to the TaskItemsPage when clicked.  You can drag and drop a button onto the MainPage using the designer.  Double click on it and it will create the event handling method.  Then we use Frame.Navigate() and pass it the type of page we want to go to, TaskItemsPage.  Here is the code.

private void Button_Click_1(object sender, RoutedEventArgs e)




Run your app, and click on the button to navigate to your TaskItemsPage.  If all goes well, you won’t receive any errors and you’ll see a page like the screen below.  Note, that your application doesn’t currently have any way to exit.  To get out you either need to Alt+Tab or move your mouse to the Top-Left corner of the screen to switch to the desktop.


This is great, but we’re not using all of our data yet.  By default, it will bind the Title for us.  However, we want to display some of our additional fields though.  To do this, we can create a DataTemplate.  We need to look into how it works first though.  Locate the GridView in your XAML file.  It should look something like this.








    ItemsSource="{Binding Source={StaticResource itemsViewSource}}"

    ItemTemplate="{StaticResource Standard250x250ItemTemplate}"



Notice the ItemTemplate and how it is bound to Standard250x250ItemTemplate.  This template can actually be found in StandardStyles.xaml

<DataTemplate x:Key="Standard250x250ItemTemplate">

    <Grid HorizontalAlignment="Left" Width="250" Height="250">

        <Border Background="{StaticResource ListViewItemPlaceholderBackgroundThemeBrush}">

            <Image Source="{Binding Image}" Stretch="UniformToFill" AutomationProperties.Name="{Binding Title}"/>


        <StackPanel VerticalAlignment="Bottom" Background="{StaticResource ListViewItemOverlayBackgroundThemeBrush}">

            <TextBlock Text="{Binding Title}" Foreground="{StaticResource ListViewItemOverlayForegroundThemeBrush}" Style="{StaticResource TitleTextStyle}" Height="60" Margin="15,0,15,0"/>

            <TextBlock Text="{Binding Subtitle}" Foreground="{StaticResource ListViewItemOverlaySecondaryForegroundThemeBrush}" Style="{StaticResource CaptionTextStyle}" TextWrapping="NoWrap" Margin="15,0,15,10"/>




If you look at what it is binding, it’s looking for fields Image, Title, and Subtitle.  We don’t have an image, so we can get rid of that.  In its place, we’ll add the other fields in our dataset.  We don’t want to edit the out-of-the-box template, so we can copy this snippet and add it to the Pages.Resources element in our TaskItemsPage.xaml.  I then changed its name to TaskItemTemplate and added the remaining fields.

<DataTemplate x:Key="TaskItemTemplate">

    <Grid HorizontalAlignment="Left" Width="250" Height="250">

        <StackPanel VerticalAlignment="Top" Background="{StaticResource ListViewItemOverlayBackgroundThemeBrush}">

            <TextBlock Text="{Binding Title}" Foreground="{StaticResource ListViewItemOverlayForegroundThemeBrush}" Style="{StaticResource TitleTextStyle}" Height="60" Margin="15,0,15,0"/>

            <TextBlock Text="{Binding DueDate}" Foreground="{StaticResource ListViewItemOverlaySecondaryForegroundThemeBrush}" Style="{StaticResource CaptionTextStyle}" TextWrapping="NoWrap" Margin="15,0,15,10"/>

            <TextBlock Text="{Binding PercentComplete}" Foreground="{StaticResource ListViewItemOverlaySecondaryForegroundThemeBrush}" Style="{StaticResource CaptionTextStyle}" TextWrapping="NoWrap" Margin="15,0,15,10"/>

            <TextBlock Text="{Binding Status}" Foreground="{StaticResource ListViewItemOverlaySecondaryForegroundThemeBrush}" Style="{StaticResource CaptionTextStyle}" TextWrapping="NoWrap" Margin="15,0,15,10"/>




Now we just need to change the template name in the GridView to use the TaskItemTemplate.








    ItemsSource="{Binding Source={StaticResource itemsViewSource}}"

    ItemTemplate="{StaticResource TaskItemTemplate}"



Run the app again and you’ll now have your custom fields bound.  It should look something like this.


The DueDate and PercentComplete are not formatted in this case.  I won’t cover that today, but if you look at the Blog Reader example, it explains the techniques you can use to do cool formatting.  The Data Binding article goes into a lot of detail if you want to learn all of the ways you can bind data too.  If you want a good tutorial to start from scratch on a Windows Store App, see the Hello, World example.

This turned out to be quite the long blog post.  I hope you find it useful.  If you find this interesting and you are going to be at SharePoint Conference 2012 in November (SPC12), you should be sure and attend my session Bringing SharePoint to the Desktop: Building Windows Store Apps with SharePoint 2013 (SPC025).

Follow me on twitter @coreyroth.

Read the original blog entry...

More Stories By Corey Roth

Corey Roth, a SharePoint Server MVP, is a consultant at Hitachi Consulting specializing in SharePoint and Office 365 for clients in the energy sector. He has more than ten years of experience delivering solutions in the energy, travel, advertising and consumer electronics verticals.

Corey specializes in delivering ECM and search solutions to clients using SharePoint. Corey has always focused on rapid adoption of new Microsoft technologies including Visual Studio 2013, Office 365, and SharePoint.

He is a member of the .NET Mafia (www.dotnetmafia.com) where he blogs about the latest technology and SharePoint. He is dedicated to the community and speaks regularly at user groups and SharePoint Saturdays.

@ThingsExpo Stories
We heard for many years how developing nations would be able to develop mobile-phone networks quickly, perhaps even leapfrog developed nations, because their lack of traditional, wired networks would not inhibit them from deploying the new technology. Now there is talk of history repeating itself with the Industrial Internet--a key aspect of the emerging Internet of Things. For example, Guo Ping, Deputy Chairman of the Board of Chinese electronics giant Huawei, said in a recent report from the World Economic Forum, "The Industrial Internet will afford emerging markets a unique opportunity ...
Avnet, Inc. has announced that it ranked No. 4 on the InformationWeek Elite 100 – a list of the top business technology innovators in the U.S. Avnet was recognized for the development of an innovative cloud-based training system that serves as the foundation for Avnet Academy – the company’s education and training organization focused on technical training around top IT vendor technologies. The development of this system allowed Avnet to quickly expand its IT-related training capabilities around the world, while creating a new service that Avnet and its IT solution providers can offer to their...
Ayla Networks, whose agile Internet of Things (IoT) platform makes it easy for manufacturers to deliver secure, connected products, today announced it has been included in the list of "Cool Vendors" in the Internet of Things report by Gartner, Inc. “Gartner knows how important it is that manufacturers of all kinds of products have the right IoT solution to help turn their products into connected ‘things,’” said David Friedman, CEO and co-founder of Ayla Networks. “The market for Ayla’s IoT platform has accelerated dramatically this year compared to last year. Today’s largest manufacturers ar...
SYS-CON Events announced today that B2Cloud, a provider of enterprise resource planning software, will exhibit at SYS-CON's 16th International Cloud Expo®, which will take place on June 9-11, 2015, at the Javits Center in New York City, NY. B2cloud develops the software you need. They have the ideal tools to help you work with your clients. B2Cloud’s main solutions include AGIS – ERP, CLOHC, AGIS – Invoice, and IZUM
The Internet of Things Maturity Model (IoTMM) is a qualitative method to gauge the growth and increasing impact of IoT capabilities in an IT environment from both a business and technology perspective. In his session at @ThingsExpo, Tony Shan will first scan the IoT landscape and investigate the major challenges and barriers. The key areas of consideration are identified to get started with IoT journey. He will then pinpoint the need of a tool for effective IoT adoption and implementation, which leads to IoTMM in which five maturity levels are defined: Advanced, Dynamic, Optimized, Primitive,...
SYS-CON Events announced today that MangoApps will exhibit at SYS-CON's 16th International Cloud Expo®, which will take place on June 9-11, 2015, at the Javits Center in New York City, NY., and the 17th International Cloud Expo®, which will take place on November 3–5, 2015, at the Santa Clara Convention Center in Santa Clara, CA. MangoApps provides private all-in-one social intranets allowing workers to securely collaborate from anywhere in the world and from any device. Social, mobile, and easy to use. MangoApps has been named a "Market Leader" by Ovum Research and a "Cool Vendor" by Gartner...
The world's leading Cloud event, Cloud Expo has launched Microservices Journal on the SYS-CON.com portal, featuring over 19,000 original articles, news stories, features, and blog entries. DevOps Journal is focused on this critical enterprise IT topic in the world of cloud computing. Microservices Journal offers top articles, news stories, and blog posts from the world's well-known experts and guarantees better exposure for its authors than any other publication. Follow new article posts on Twitter at @MicroservicesE
Containers and microservices have become topics of intense interest throughout the cloud developer and enterprise IT communities. Accordingly, attendees at the upcoming 16th Cloud Expo at the Javits Center in New York June 9-11 will find fresh new content in a new track called PaaS | Containers & Microservices Containers are not being considered for the first time by the cloud community, but a current era of re-consideration has pushed them to the top of the cloud agenda. With the launch of Docker's initial release in March of 2013, interest was revved up several notches. Then late last...
There is no doubt that Big Data is here and getting bigger every day. Building a Big Data infrastructure today is no easy task. There are an enormous number of choices for database engines and technologies. To make things even more challenging, requirements are getting more sophisticated, and the standard paradigm of supporting historical analytics queries is often just one facet of what is needed. As Big Data growth continues, organizations are demanding real-time access to data, allowing immediate and actionable interpretation of events as they happen. Another aspect concerns how to deliver ...
WebRTC defines no default signaling protocol, causing fragmentation between WebRTC silos. SIP and XMPP provide possibilities, but come with considerable complexity and are not designed for use in a web environment. In his session at @ThingsExpo, Matthew Hodgson, technical co-founder of the Matrix.org, discussed how Matrix is a new non-profit Open Source Project that defines both a new HTTP-based standard for VoIP & IM signaling and provides reference implementations.
So I guess we’ve officially entered a new era of lean and mean. I say this with the announcement of Ubuntu Snappy Core, “designed for lightweight cloud container hosts running Docker and for smart devices,” according to Canonical. “Snappy Ubuntu Core is the smallest Ubuntu available, designed for security and efficiency in devices or on the cloud.” This first version of Snappy Ubuntu Core features secure app containment and Docker 1.6 (1.5 in main release), is available on public clouds, and for ARM and x86 devices on several IoT boards. It’s a Trend! This announcement comes just as...
The security devil is always in the details of the attack: the ones you've endured, the ones you prepare yourself to fend off, and the ones that, you fear, will catch you completely unaware and defenseless. The Internet of Things (IoT) is nothing if not an endless proliferation of details. It's the vision of a world in which continuous Internet connectivity and addressability is embedded into a growing range of human artifacts, into the natural world, and even into our smartphones, appliances, and physical persons. In the IoT vision, every new "thing" - sensor, actuator, data source, data con...
The WebRTC Summit 2015 New York, to be held June 9-11, 2015, at the Javits Center in New York, NY, announces that its Call for Papers is open. Topics include all aspects of improving IT delivery by eliminating waste through automated business models leveraging cloud technologies. WebRTC Summit is co-located with 16th International Cloud Expo, @ThingsExpo, Big Data Expo, and DevOps Summit.
SYS-CON Events announced today the IoT Bootcamp – Jumpstart Your IoT Strategy, being held June 9–10, 2015, in conjunction with 16th Cloud Expo and Internet of @ThingsExpo at the Javits Center in New York City. This is your chance to jumpstart your IoT strategy. Combined with real-world scenarios and use cases, the IoT Bootcamp is not just based on presentations but includes hands-on demos and walkthroughs. We will introduce you to a variety of Do-It-Yourself IoT platforms including Arduino, Raspberry Pi, BeagleBone, Spark and Intel Edison. You will also get an overview of cloud technologies s...
The Internet of Things is not new. Historically, smart businesses have used its basic concept of leveraging data to drive better decision making and have capitalized on those insights to realize additional revenue opportunities. So, what has changed to make the Internet of Things one of the hottest topics in tech? In his session at @ThingsExpo, Chris Gray, Director, Embedded and Internet of Things, discussed the underlying factors that are driving the economics of intelligent systems. Discover how hardware commoditization, the ubiquitous nature of connectivity, and the emergence of Big Data a...
SYS-CON Media announced today that @WebRTCSummit Blog, the largest WebRTC resource in the world, has been launched. @WebRTCSummit Blog offers top articles, news stories, and blog posts from the world's well-known experts and guarantees better exposure for its authors than any other publication. @WebRTCSummit Blog can be bookmarked ▸ Here @WebRTCSummit conference site can be bookmarked ▸ Here
Scott Jenson leads a project called The Physical Web within the Chrome team at Google. Project members are working to take the scalability and openness of the web and use it to talk to the exponentially exploding range of smart devices. Nearly every company today working on the IoT comes up with the same basic solution: use my server and you'll be fine. But if we really believe there will be trillions of these devices, that just can't scale. We need a system that is open a scalable and by using the URL as a basic building block, we open this up and get the same resilience that the web enjoys.
In his session at WebRTC Summit, Peter Dunkley, Technical Director at Acision, will look at creating interactive communications via the web by adding messaging, file transfer, and group communication (group chat and audio/video conferencing) into the web experience. He will also discuss potential applications of this technology in areas including B2B, B2C, P2P, and gaming. Peter Dunkley is Technical Director at Acision. He graduated from The University of Edinburgh in 2000 with a BSc (Hons) in Computer Science. After graduation Peter worked on a PSTN switch developing signalling stacks for SS...
It's time to put the "Thing" back in IoT. Whether it’s drones, robots, self-driving cars, ... There are multiple incredible examples of the power of IoT nowadays that are shadowed by announcements of yet another twist on statistics, databases, .... Sorry, I meant, Big Data(TM), tiered storage(TM), complex systems(TM), smart nations(TM), .... In his session at WebRTC Summit, Dr Alex Gouaillard, CTO and Co-Founder of Temasys, will discuss the concrete, cool, examples of IoT already happening today, and how mixing all those different sources of visual and audio input can make your life happier ...
What exactly is a cognitive application? In her session at 16th Cloud Expo, Ashley Hathaway, Product Manager at IBM Watson, will look at the services being offered by the IBM Watson Developer Cloud and what that means for developers and Big Data. She'll explore how IBM Watson and its partnerships will continue to grow and help define what it means to be a cognitive service, as well as take a look at the offerings on Bluemix. She will also check out how Watson and the Alchemy API team up to offer disruptive APIs to developers.