(X) Hide this
    • Login
    • Join
      • Say No Bots Generate New Image
        By clicking 'Register' you accept the terms of use .

Connecting Windows 8 applications with services: Part 1: Using services to get data in our Windows 8 applications

(7 votes)
Gill Cleeren
Gill Cleeren
Joined Apr 02, 2010
Articles:   63
Comments:   6
More Articles
18 comments   /   posted on Aug 13, 2012
Tags:   windows-8 , gill-cleeren
Categories:   Data Access , Windows 8 , General

Windows 8’s biggest novelty is without a doubt “Apps”. Microsoft is entering the world of apps and is for the first time introducing a “real marketplace”, named the Windows 8 Store where developers can publish, market and sell their applications. This new (for Microsoft developers at least) way of working requires in many views a change of mindset. We as developers are facing many new things, including a new application lifetime management, a new API (WinRT), a different type of communication between apps (Contracts), a new Start experience (Tiles) and many more.

Since apps are going to be distributed through the means of a store, topics such as accessing data also requires some thought. In many views, accessing data through services is similar to accessing data in Silverlight applications. Although the principles are similar, the implementation tends to differ in many places.

The apps we build need to give the user the feeling of being connected. When we’re building a stock ticker application, the app needs access to up-to-date data. An RSS reader would be pretty useless without access to RSS feeds. A LOB app may need access to a CRM data. Without being connected to (up-to-date) data, many apps can’t even execute their normal routine.

In this new series of articles on SilverlightShow, we are going to explore how we can build connected Windows 8 applications. In other words, we are going to explore the options we have to connect our Windows 8 apps to services. The good news for us as developers is that Windows 8 apps can connect with many types of services.

In this first article, we are going to explore the principles of accessing data over services in Windows 8 apps. We are going to apply this knowledge by accessing ASMX and WCF Services from a Windows 8 application. The code for this article can be found here.

Accessing data over services in Windows 8

As outlined in the introduction, many scenarios for Windows 8 apps require access to services. Stock tickers, chat apps, LOB apps, RSS readers… all require access to data. In many scenarios, this data is required to be recent.

Most data resides in databases. In a Windows 8 app, we can specify for example a connection string to read out data stored in a server-side database. Not only would this be a huge security risk (imagine your connection string being on the thousands of devices where your app is downloaded!), it would also be pretty useless to have it there. WinRT has no knowledge of talking with a (remote) database. This means no ADO.NET or LINQ-To-SQL classes are in the API.

Moreover, there’s even no out-of-the-box database built into WinRT. Many Windows Phone developers will expect an implementation of SQL Server CE to be present (which was added in Windows Phone 7.5). Well, I have to disappoint you, since it’s not currently in WinRT. The only option we have is using sqlite for local database needs. Some information about this can be found here.

A local database would not be a solution to gaining access to data. It would mostly be useful for offline/occasionally connected systems. The requirements for these however can be satisfied using the Application Data API or using the above mentioned sqlite.

Where does that leave us? Well, the story is pretty much the same as we had in Silverlight. Relational data is to be stored server-side and should be behind a service layer. Luckily for us, many service types are available to be used from Windows 8 apps. The list below shows the services types we’ll be using throughout these articles:

  • ASMX services
  • WCF services
  • REST services
  • oData services (created using WCF Data Services)
  • Sockets

One that is notably missing from this list is indeed WCF RIA Services, a framework created for Silverlight LOB development. At the moment of writing, there’s no word on any integration between Windows 8 apps and WCF RIA Services.

In Windows 8, Microsoft heavily invested in speed and performance. The platform is very responsive and feels especially fluent using touch input. Apps should also be made as responsive as possible. Service access in Windows 8 apps therefore is all done asynchronously. This was also the case in Silverlight using callbacks. One thing that bothered me in this model is the fact that when we have a lot of sequential calls, the code tends to get messy. For example, we download orders; in the callback of this, we download order items for each order; in the callback of that... and so on.

The development languages teams have been focusing on making async development easier. In C# 5, the await/async pattern has been introduced. This allows writing asynchronous code in a more synchronous manner. Take a look at the code below. The code does an async operation, however, apart from the await keyword, it looks just like some plain sequential code!

    HttpResponseMessage response = await httpClient.GetAsync(String.Format(searchUrl, api_key, SearchTextBox.Text));
catch (HttpRequestException hre)
    ResultTextBlock.Text = hre.Message;

Internally, the compiler builds a state machine. A blog post on MSDN explains in-depth what is happening behind the scenes when you use async/await.

Once we got in the response, we get access to the data. Depending on the data source, we need to act differently on the result. If the result is XML, we can parse the data using perhaps LINQ-To-XML. With the objects materialized, we can use the data in our UI, probably in a data-binding scenario.

With the principles explained, let’s look at using an ASMX and a WCF service from Windows 8.

Accessing ASMX services from Windows 8 apps

The services many of us wrote as their very first services were web services (ASMX services). Plain web services are still being written today and many are still being used. How can we use them from Windows 8 apps?

The good news is that we can access these services without any change whatsoever. When connecting to an ASMX service from Windows 8, we perform the following steps, similar to what we did in Silverlight:

  • Create a service reference to the *.wsdl file exposed by the service
  • Based on this file, Visual Studio will generate a service reference (the proxy class). Although this is similar, the code generated in the proxy class is different. Take a look at the Reference.cs file (part of it is shown below). All the generated methods are now Task based. Task is the very base of the await/async pattern (only methods that return void or Task<T> can be awaited).
public System.Threading.Tasks.Task<ASMXServiceSample.WeatherService.GetWeatherInformationResponse> GetWeatherInformationAsync() {
    ASMXServiceSample.WeatherService.GetWeatherInformationRequest inValue = new ASMXServiceSample.WeatherService.GetWeatherInformationRequest();
    return ((ASMXServiceSample.WeatherService.WeatherSoap)(this)).GetWeatherInformationAsync(inValue);
public System.Threading.Tasks.Task<ASMXServiceSample.WeatherService.ForecastReturn> GetCityForecastByZIPAsync(string ZIP) {
    return base.Channel.GetCityForecastByZIPAsync(ZIP);
public System.Threading.Tasks.Task<ASMXServiceSample.WeatherService.WeatherReturn> GetCityWeatherByZIPAsync(string ZIP) {
    return base.Channel.GetCityWeatherByZIPAsync(ZIP);
  • Use the proxy methods in an asynchronous manner (based on the generated Task<T> methods in the proxy).

Let’s take a look at doing this in a sample. In Visual Studio 2012, create a new Windows 8 application named ASMXServiceSample.

For the service, we are going to use a public ASMX endpoint: http://wsf.cdyne.com/WeatherWS/Weather.asmx?wsdl. Copy this URL in the Add Service Reference dialog and click Go. Visual Studio will try reading out the WSDL file. Enter the name WeatherService for the namespace. If all goes well, the proxy will be generated for you. Open the Reference.cs file and notice the Task-based methods. This code can now be used in combination with the await/async pattern.

Notice that no configuration code is generated in the Windows 8 application. The idea here is that apps are going to be distributed from the store anyway, so the use of configuration, which is compiling and then changing settings, is not applicable with Windows 8 apps. Instead, a method is generated in the proxy class named ConfigureEndpoint:

static partial void ConfigureEndpoint(System.ServiceModel.Description.ServiceEndpoint serviceEndpoint, 
    System.ServiceModel.Description.ClientCredentials clientCredentials);

This method is partial, so we can use it from our own code to pass configuration code if needed. The configuration changes we would do normally (for example in a Silverlight application) will now be done in code using this method.

Let’s now take a look at using this service. In the MainPage.xaml of the application, add the following code:

<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
    <StackPanel Margin="30" Orientation="Vertical">
        <Button x:Name="backButton" Click="GoBack" Style="{StaticResource BackButtonStyle}"/>
        <TextBlock Text="Enter zip" FontSize="25"></TextBlock>
        <TextBox Name="ZipCodeTextBox" Width="300" ></TextBox>
        <Button Content="Load weather" Name="LoadWeatherButton" Click="LoadWeatherButton_Click_1"></Button>
        <TextBox IsEnabled="False" AcceptsReturn="True" TextWrapping="Wrap" Name="WeatherTextBox" 
            Width="300" Height="200" HorizontalAlignment="Left" Margin="20"></TextBox>

The UI is very simple and allows for entering a US ZIP code. The response will be shown in the WeatherTextBox. Some code needs to be added to the click event of the Button. Let’s take a look.

private async void LoadWeatherButton_Click_1(object sender, RoutedEventArgs e)
    StringBuilder builder = new StringBuilder();
    WeatherService.WeatherSoapClient client = new WeatherService.WeatherSoapClient();
    WeatherReturn result = await client.GetCityWeatherByZIPAsync(ZipCodeTextBox.Text);
    if (result.Success)
        builder.Append(String.Format("{0}, {1}\n", result.City, result.State));
            ("\n\nConditions - {0} \nTemperature - {1}F \nRelative Humidity - {2} \nWind - {3} \nPressure - {4}",
                result.Description, result.Temperature, result.RelativeHumidity, result.Wind, result.Pressure));
        WeatherTextBox.Text = builder.ToString();
        WeatherTextBox.Text = "City not found";

We start by instantiating the proxy class (new WeatherService.WeatherSoapClient()). Then we use the magic of await. In Silverlight, we would write the callback and then call the service using the *Async method. However here, we use the await keyword. This makes sure that all code that comes after it, isn’t executed until the call is returned. Notice that the method itself is marked with async since we are using await inside of it.

The result of the service call is an instance of type WeatherReturn, as defined by the service. We use this object to read out the weather and display it on the UI. If you run the sample now and enter a US ZIP code, you should get a response.


If you can’t access the service, take a look at the capabilities of the Windows 8 app by opening the Package.appxmanifest file. Under the capabilities tab, the Internet (Client) capability should be enabled.


There we go, we have our first service-enabled Windows 8 application running. Great! Let’s know look at what happens if we want to use WCF. In most cases, you’ll be using WCF instead of ASMX, that’s for sure!

Accessing WCF services from Windows 8 apps

Working with WCF in Windows 8 apps is pretty similar to working with ASMX. However, not every type of WCF service is supported: only the following bindings are supported from a Windows 8 application:

  • BasicHttpBinding
  • NetTcpBinding
  • NetHttpBinding
  • CustomBinding

This means indeed that we have pretty much the same options as we had in Silverlight. Services using the BasicHttpBinding are supported (which is basically what ASMX uses). The wsHttpBinding isn’t supported, so for security, we have to look at other solutions (we’ll look later in this article series at how we can secure communication between a Windows 8 app and a service). The CustomBinding can be used for example if you want to use BinaryEncoding. For a complete rundown on the specifics that are supported in Windows 8 apps, take a look at the following link.

Let’s look at a sample. Create a new Windows 8 app and name it WCFServiceSample. Add an empty ASP.NET web application to the solution (WeatherSite) and add a WCF Service to the project (WeatherService). In the service contract (IWeatherService), add the following code (which is some very basic WCF code using a ServiceContract and a DataContract):

public interface IWeatherService
    Weather GetCityWeatherByZip(string zipCode);
public class Weather
    public bool Success { get; set; }
    public int Temperature { get; set; }
    public string WeatherDescription { get; set; }

In the implementation of the contract, add the following code:

public Weather GetCityWeatherByZip(string zipCode)
    switch (zipCode)
        case "12345": return new Weather() { Success = true, Temperature = 15, 
            WeatherDescription = "Rainy, typical Belgian weather" };
        case "90210": return new Weather() { Success = true, Temperature = 25,     
            WeatherDescription = "Sunny all day long" };
        default: return new Weather() { Success = false, Temperature = 0, 
            WeatherDescription = "In your location, there's not weather... We don't know what happened" };

In the Windows 8 app, add a service reference in the same way as you did with the ASMX service. We can now use the proxy from code as follows:

StringBuilder builder = new StringBuilder();
WeatherService.WeatherServiceClient client = new WeatherService.WeatherServiceClient();
Weather result = await client.GetCityWeatherByZipAsync(ZipCodeTextBox.Text);
if (result.Success)
    builder.Append(String.Format("Temperature: {0} °C, \nWeather description: {1}\n", result.Temperature, result.WeatherDescription));
    WeatherTextBox.Text = builder.ToString();
    WeatherTextBox.Text = "City not found";

As you can see the code is very similar. Behind the scenes, this service uses the BasicHttpBinding (which is the default when adding a new service). That’s the reason why we can use it from Windows 8!


We have covered the basics of communicating with services in Windows 8 apps. In the next article, we’ll look at other types of services to communicate with, including REST services. Stay tuned!

About the author

Gill Cleeren is Microsoft Regional Director (www.theregion.com), Silverlight MVP (former ASP.NET MVP) and Telerik MVP. He lives in Belgium where he works as .NET architect at Ordina (http://www.ordina.be/). Passionate about .NET, he’s always playing with the newest bits. In his role as Regional Director, Gill has given many sessions, webcasts and trainings on new as well as existing technologies, such as Silverlight, ASP.NET and WPF at conferences including TechEd Berlin 2010, TechDays Belgium – Switzerland - Sweden, DevDays NL, NDC Oslo Norway, SQL Server Saturday Switzerland, Spring Conference UK, Silverlight Roadshow in Sweden, Telerik RoadShow UK… He’s also the author of many articles in various developer magazines and for SilverlightShow.net and he organizes the yearly Community Day event in Belgium. He also leads Visug (www.visug.be), the largest .NET user group in Belgium. Gill is the author of “Silverlight 4 Data and Services Cookbook”. In 2012, the second edition, “Silverlight 5 Data and Services Cookbook” was released.

You can find his blog at www.snowball.be.

Twitter: @gillcleeren



Add Comment

Login to comment:
  *      *       

From this series