Web Services
A web service is a method for communication between devices over the Internet. The most common protocol for communication is the Simple Object Access Protocol (SOAP) that was designed in 1998. If you’ve worked with SOAP, you know there is nothing simple about it, and a new protocol known as Representational State Transfer (REST) is quickly gaining popularity.
Web services are important for communications in applications. Many enterprise systems expose web services for consumption by client software like this Windows 8 application. One advantage of using SOAP is that it provides a discovery mechanism through the Web Services Description Language (WSDL) that allows the client application to determine the signature and structure of the API. You can learn more about the WSDL specification online at http://www.w3.org/TR/wsdl.
Open the WeatherService project to see an example of using web services. The example uses a free web service to obtain weather information. Connecting to the service was as simple as right-clicking the References node of the Solution Explorer, choosing Add Service Reference, and entering the URL for the service. The result is shown in Figure 6.4.
Figure 6.4. Adding a SOAP-based web service
When the service is added, a client proxy is generated automatically. The proxy handles all of the work necessary to make a request to the API and return the data and presents these as asynchronous implementations of the server interfaces. In the example application, the user is prompted to enter a zip code. When the button is clicked, the zip code is validated and, if there are no errors, passed to the web service. The following line of code is all that is needed to create a proxy for connecting to the web service and to call it with the zip code (note the convention of using Async at the end of the method name):
var client = new WeatherWebService.WeatherSoapClient(); var result = await client.GetCityForecastByZIPAsync( zip.ToString());
If the result does not indicate a successful call, a dialog is shown that indicates there was a problem. Otherwise, the results are bound to the grid and shown through data-binding. This is all it takes to data-bind the results from the web service call:
ResultsGrid.DataContext = result;
The XAML is set to show the city and state:
<StackPanel Orientation="Horizontal"> <TextBlock Text="{Binding City}"/> <TextBlock Text=","/> <TextBlock Text="{Binding State}"/> </StackPanel>
Listing 6.3 shows the full XAML for the individual forecast items. The “description” field is purposefully misspelled because this is how it came across in the web service as of the time of this writing.
Listing 6.3. Data-Binding the Results from a Weather Service
<ListView Grid.Row="1" ItemsSource="{Binding ForecastResult}"> <ListView.ItemTemplate> <DataTemplate> <StackPanel Orientation="Horizontal"> <TextBlock Text="{Binding Date, Converter={StaticResource ConvertDate}}" Width="200"/> <TextBlock Text="{Binding Description}" Width="150" Margin="5 0 0 0"/> <Image Source="{Binding Description, Converter={StaticResource ConvertImage}}"/> <TextBlock Text="{Binding Temperatures.MorningLow}" Margin="5 0 0 0" Width="50"/> <TextBlock Text="{Binding Temperatures.DaytimeHigh}" Margin="5 0 0 0" Width="50"/> </StackPanel> </DataTemplate> </ListView.ItemTemplate> </ListView>
The weather service documentation provided a set of icons that correspond to the description. The ImageConverter class takes the description and translates it to a file name so it can return the image:
var filename = string.Format("ms-appx:///Assets/{0}.gif", ((string) value).Replace(" ", string.Empty).ToLower()); return new BitmapImage(new Uri(filename, UriKind.Absolute));
Figure 6.5 displays the result of my request for the weather forecast of my hometown (Woodstock, Georgia) via its zip code.
Figure 6.5. The weather forecast for Woodstock, Georgia
OData Support
The Open Data Procotol (OData) is a web protocol used for querying and updating data. It is a REST-based API built on top of Atom that uses JSON or XML for transporting information. You can read more about OData online at http://www.odata.org/.
Windows 8 applications have native support for OData clients once you download and install the client from:
http://go.microsoft.com/fwlink/?LinkId=253653
To access OData services, you simply add a service reference the same way you would for a SOAP-based web service. A popular OData service to use for demonstrations is the Netflix movie catalog. You can browse the service directly by typing http://odata.netflix.com/catalog/ into your browser.
In most browsers, you should see an XML document that contains various tags for collections you may browse. For example, the collection referred to as Titles indicates you can browse all titles using the URL, http://odata.netflix.com/catalog/Titles.
The Netflix project shows a simple demonstration of using this OData feed. The main URL was added as a service reference the same way the weather service was added in the previous example. The first step in using the service is to create a proxy to access it. This is done by taking the generated class from adding the service and passing in the service URL:
var netflix = new NetflixCatalog( new Uri( "http://odata.netflix.com/Catalog/", UriKind.Absolute));
Next, set up a collection for holding the results of an OData query. This is done using the special DataServiceCollection class:
private DataServiceCollection<Title> _collection; ... _collection = new DataServiceCollection<Title>(netflix); TitleGrid.ItemsSource = _collection;
Finally, specify a query to filter the data. This query is passed to the proxy and will load the results into the collection. In this example, the query will grab the first 100 titles that start with the letter “Y” in order of highest rated first:
var query = (from t in netflix.Titles where t.Name.StartsWith("Y") orderby t.Rating descending select t).Take(100); _collection.LoadAsync(query);
Finally, as data comes in, you have the option to page in additional sets of data. This is done by checking the collection for a continuation. If one exists, you can request that the service load the next set. This allows you to page in data rather than pull down an extremely large set all at once:
if (_collection.Continuation != null) { _collection.LoadNextPartialSetAsync(); }
Run the included sample application. You should see the titles and images start to appear asynchronously in a grid that you can scroll through. As in the previous example, the results of the web service are bound directly to the grid:
<Image Stretch="Uniform" Width="150" Height="150"> <Image.Source> <BitmapImage UriSource="{Binding BoxArt.LargeUrl}"/> </Image.Source> </Image> <TextBlock Text="{Binding Name}" Grid.Row="1"/>
The Windows 8 development environment makes it easy and straightforward to connect to web services and pull data in from external sources. Many existing applications expose web services in the form of SOAP, REST, and OData feeds. The built-in support to access and process these feeds makes it possible to build Windows 8 applications that support your existing functionality when it is exposed via web services.