Welcome!

SOA & WOA Authors: Kevin Benedict, Carmen Gonzalez, Elizabeth White, Keith Cawley, Jason Bloomberg

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.

http://server/site/_api/web/list/getbytitle(‘tasks’)/items

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

RESTAPIListsBrowser

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.

http://server/site/_api/web/list/getbytitle(‘tasks’)/items?$select=Title,DueDate,Status,PercentComplete

RESTAPIListsWithSelectBrowser

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).

VS12NewWindowsStoreApp

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.

VS12NewItemsPage

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"]

    BindData();

}

 

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);

response.EnsureSuccessStatusCode();

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.

string

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:

this

.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.

Windows8ProjectCapabilities

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)

{

    Frame.Navigate(typeof(TasksItemsPage));

}

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.

Windows8TasksItemsPage

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.

<GridView

    x:Name="itemGridView"

    AutomationProperties.AutomationId="ItemsGridView"

    AutomationProperties.Name="Items"

    TabIndex="1"

    Grid.RowSpan="2"

    Padding="116,136,116,46"

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

    ItemTemplate="{StaticResource Standard250x250ItemTemplate}"

    SelectionMode="None"

    IsSwipeEnabled="false"/>

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}"/>

        </Border>

        <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"/>

        </StackPanel>

    </Grid>

</DataTemplate>

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"/>

        </StackPanel>

    </Grid>

</DataTemplate>

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

<GridView

    x:Name="itemGridView"

    AutomationProperties.AutomationId="ItemsGridView"

    AutomationProperties.Name="Items"

    TabIndex="1"

    Grid.RowSpan="2"

    Padding="116,136,116,46"

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

    ItemTemplate="{StaticResource TaskItemTemplate}"

    SelectionMode="None"

    IsSwipeEnabled="false"/>

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

Windows8TasksItemsPageCustomTemplate

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
Disruptive macro trends in technology are impacting and dramatically changing the "art of the possible" relative to supply chain management practices through the innovative use of IoT, cloud, machine learning and Big Data to enable connected ecosystems of engagement. Enterprise informatics can now move beyond point solutions that merely monitor the past and implement integrated enterprise fabrics that enable end-to-end supply chain visibility to improve customer service delivery and optimize supplier management. Learn about enterprise architecture strategies for designing connected systems tha...
The Internet of Things (IoT) is going to require a new way of thinking and of developing software for speed, security and innovation. This requires IT leaders to balance business as usual while anticipating for the next market and technology trends. Cloud provides the right IT asset portfolio to help today’s IT leaders manage the old and prepare for the new. Today the cloud conversation is evolving from private and public to hybrid. This session will provide use cases and insights to reinforce the value of the network in helping organizations to maximize their company’s cloud experience.
Cultural, regulatory, environmental, political and economic (CREPE) conditions over the past decade are creating cross-industry solution spaces that require processes and technologies from both the Internet of Things (IoT), and Data Management and Analytics (DMA). These solution spaces are evolving into Sensor Analytics Ecosystems (SAE) that represent significant new opportunities for organizations of all types. Public Utilities throughout the world, providing electricity, natural gas and water, are pursuing SmartGrid initiatives that represent one of the more mature examples of SAE. We have s...
IoT is still a vague buzzword for many people. In his session at Internet of @ThingsExpo, Mike Kavis, Vice President & Principal Cloud Architect at Cloud Technology Partners, will discuss the business value of IoT that goes far beyond the general public's perception that IoT is all about wearables and home consumer services. The presentation will also discuss how IoT is perceived by investors and how venture capitalist access this space. Other topics to discuss are barriers to success, what is new, what is old, and what the future may hold.
Whether you're a startup or a 100 year old enterprise, the Internet of Things offers a variety of new capabilities for your business. IoT style solutions can help you get closer your customers, launch new product lines and take over an industry. Some companies are dipping their toes in, but many have already taken the plunge, all while dramatic new capabilities continue to emerge. In his session at Internet of @ThingsExpo, Reid Carlberg, Senior Director, Developer Evangelism at salesforce.com, to discuss real-world use cases, patterns and opportunities you can harness today.
All major researchers estimate there will be tens of billions devices – computers, smartphones, tablets, and sensors – connected to the Internet by 2020. This number will continue to grow at a rapid pace for the next several decades. With major technology companies and startups seriously embracing IoT strategies, now is the perfect time to attend @ThingsExpo in Silicon Valley. Learn what is going on, contribute to the discussions, and ensure that your enterprise is as "IoT-Ready" as it can be!
Noted IoT expert and researcher Joseph di Paolantonio (pictured below) has joined the @ThingsExpo faculty. Joseph, who describes himself as an “Independent Thinker” from DataArchon, will speak on the topic of “Smart Grids & Managing Big Utilities.” Over his career, Joseph di Paolantonio has worked in the energy, renewables, aerospace, telecommunications, and information technology industries. His expertise is in data analysis, system engineering, Bayesian statistics, data warehouses, business intelligence, data mining, predictive methods, and very large databases (VLDB). Prior to DataArcho...
Software AG helps organizations transform into Digital Enterprises, so they can differentiate from competitors and better engage customers, partners and employees. Using the Software AG Suite, companies can close the gap between business and IT to create digital systems of differentiation that drive front-line agility. We offer four on-ramps to the Digital Enterprise: alignment through collaborative process analysis; transformation through portfolio management; agility through process automation and integration; and visibility through intelligent business operations and big data.
There will be 50 billion Internet connected devices by 2020. Today, every manufacturer has a propriety protocol and an app. How do we securely integrate these "things" into our lives and businesses in a way that we can easily control and manage? Even better, how do we integrate these "things" so that they control and manage each other so our lives become more convenient or our businesses become more profitable and/or safe? We have heard that the best interface is no interface. In his session at Internet of @ThingsExpo, Chris Matthieu, Co-Founder & CTO at Octoblu, Inc., will discuss how thes...
Last week, while in San Francisco, I used the Uber app and service four times. All four experiences were great, although one of the drivers stopped for 30 seconds and then left as I was walking up to the car. He must have realized I was a blogger. None the less, the next car was just a minute away and I suffered no pain. In this article, my colleague, Ved Sen, Global Head, Advisory Services Social, Mobile and Sensors at Cognizant shares his experiences and insights.
We are reaching the end of the beginning with WebRTC and real systems using this technology have begun to appear. One challenge that faces every WebRTC deployment (in some form or another) is identity management. For example, if you have an existing service – possibly built on a variety of different PaaS/SaaS offerings – and you want to add real-time communications you are faced with a challenge relating to user management, authentication, authorization, and validation. Service providers will want to use their existing identities, but these will have credentials already that are (hopefully) ir...
Can call centers hang up the phones for good? Intuitive Solutions did. WebRTC enabled this contact center provider to eliminate antiquated telephony and desktop phone infrastructure with a pure web-based solution, allowing them to expand beyond brick-and-mortar confines to a home-based agent model. It also ensured scalability and better service for customers, including MUY! Companies, one of the country's largest franchise restaurant companies with 232 Pizza Hut locations. This is one example of WebRTC adoption today, but the potential is limitless when powered by IoT. Attendees will learn rea...
From telemedicine to smart cars, digital homes and industrial monitoring, the explosive growth of IoT has created exciting new business opportunities for real time calls and messaging. In his session at Internet of @ThingsExpo, Ivelin Ivanov, CEO and Co-Founder of Telestax, will share some of the new revenue sources that IoT created for Restcomm – the open source telephony platform from Telestax. Ivelin Ivanov is a technology entrepreneur who founded Mobicents, an Open Source VoIP Platform, to help create, deploy, and manage applications integrating voice, video and data. He is the co-founder ...
The Internet of Things (IoT) promises to create new business models as significant as those that were inspired by the Internet and the smartphone 20 and 10 years ago. What business, social and practical implications will this phenomenon bring? That's the subject of "Monetizing the Internet of Things: Perspectives from the Front Lines," an e-book released today and available free of charge from Aria Systems, the leading innovator in recurring revenue management.
The Internet of Things will put IT to its ultimate test by creating infinite new opportunities to digitize products and services, generate and analyze new data to improve customer satisfaction, and discover new ways to gain a competitive advantage across nearly every industry. In order to help corporate business units to capitalize on the rapidly evolving IoT opportunities, IT must stand up to a new set of challenges.
There’s Big Data, then there’s really Big Data from the Internet of Things. IoT is evolving to include many data possibilities like new types of event, log and network data. The volumes are enormous, generating tens of billions of logs per day, which raise data challenges. Early IoT deployments are relying heavily on both the cloud and managed service providers to navigate these challenges. In her session at 6th Big Data Expo®, Hannah Smalltree, Director at Treasure Data, to discuss how IoT, Big Data and deployments are processing massive data volumes from wearables, utilities and other mach...
P2P RTC will impact the landscape of communications, shifting from traditional telephony style communications models to OTT (Over-The-Top) cloud assisted & PaaS (Platform as a Service) communication services. The P2P shift will impact many areas of our lives, from mobile communication, human interactive web services, RTC and telephony infrastructure, user federation, security and privacy implications, business costs, and scalability. In his session at Internet of @ThingsExpo, Erik Lagerway, Co-founder of Hookflash, will walk through the shifting landscape of traditional telephone and voice s...
While great strides have been made relative to the video aspects of remote collaboration, audio technology has basically stagnated. Typically all audio is mixed to a single monaural stream and emanates from a single point, such as a speakerphone or a speaker associated with a video monitor. This leads to confusion and lack of understanding among participants especially regarding who is actually speaking. Spatial teleconferencing introduces the concept of acoustic spatial separation between conference participants in three dimensional space. This has been shown to significantly improve comprehe...
The Internet of Things is tied together with a thin strand that is known as time. Coincidentally, at the core of nearly all data analytics is a timestamp. When working with time series data there are a few core principles that everyone should consider, especially across datasets where time is the common boundary. In his session at Internet of @ThingsExpo, Jim Scott, Director of Enterprise Strategy & Architecture at MapR Technologies, will discuss single-value, geo-spatial, and log time series data. By focusing on enterprise applications and the data center, he will use OpenTSDB as an example...
SYS-CON Events announced today that Gridstore™, the leader in software-defined storage (SDS) purpose-built for Windows Servers and Hyper-V, will exhibit at SYS-CON's 15th International Cloud Expo®, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Gridstore™ is the leader in software-defined storage purpose built for virtualization that is designed to accelerate applications in virtualized environments. Using its patented Server-Side Virtual Controller™ Technology (SVCT) to eliminate the I/O blender effect and accelerate applications Gridsto...