I’m currently working on an extended series for creating a small backend with database, backend modular architecture approach and REST services to serve the different front end applications that I have been putting together for the blog. The idea is to provide a common backend framework and services to feed the different samples I create and help you out there to have a more complete series of code samples to work with.
In the meanwhile, I’ll be posting small tips about how to do things on the Windows Ecosystem, which encompasses Windows 8 (Metro Style, .NET, C# and JS), Windows Phone, Silverlight, WPF, Surface 2.0 and Kinect.
For this post, I’ll share with you an approach to consume REST web services from a Metro Style Windows 8 application.
For this sample, you need to create a new Windows 8 Metro Style application. Once Visual Studio created the default project structure, go into your MainPage.xaml.cs file. Let’s assume you will be consuming a REST web service that will return an XML with a collection of items. You will want to display those items, but first you need to populate your data collection. Lets create the default collection field.
Note that we are creating a private ObservableCollection of type Customer. You will need to define your customer class, which can be as simple as the following:
Ok, so you have your collection field to load your Customer collection from the web service. Now we need to initialize the collection on the page’s constructor by calling the asynchronous method that will in turn call the web service and return the collection of customers:
Notice the reserved keyword “await”. This is one of the goodness of Windows 8, which allows you to program asynchronous code in a linear approach, which makes it a lot easier to read and digest. Here, we are telling the thread to await the call resolution in an asynchronous way. The method we call, will hit the web service and parse the XML response to return our Customer collection. Notice how you can use LinqToXml to easily parse the response (be aware that no failure catching has been implemented, you should always check for null values to avoid code exceptions when parsing the XML).The code to do so is the following:
And that’s basically it. You have been able to load a collection of customers asynchronously from a REST web service serving XML responses from your Windows 8 application. Once the collection is loaded you can bind your UI items control to it to populate and display the collection items.
Hope it can help you on your Windows 8 Metro training. Keep tuned for more updates !
Let me know if you have any troubles with it and I’ll be more than happy to try to help you out.