2012

Volume 27

Azure Insider - Windows 8 and Microsoft Azure: Convergence in the Cloud

By Bruno Terkaly, Ricardo Villalobos | 2012

Bruno Terkaly, Ricardo VillalobosThere’s little question that today’s software developer must embrace cloud technologies to create compelling Windows Store applications—the sheer number of users and devices make that a no-brainer. More than one-third of the Earth’s population is connected to the Internet, and there are now more devices accessing online resources than there are people. Moreover, mobile data traffic grew 2.3-fold in 2011, more than doubling for the fourth year in a row. No matter how you look at it, you end up with a very simple conclusion: Modern applications require connectivity to the cloud.

The value proposition of cloud computing is compelling. Most observers point to the scalability on demand and to the fact that you pay only for what you use as driving forces to cloud adoption. However, the cloud actually provides some essential technology in the world of multiple connected devices. Windows Store application users, likely to be using many applications and multiple devices, expect their data to be centrally located. If they save data on a Windows Phone device, it should also be immediately available on their tablets or any of their other devices, including iOS and Android devices.

Azure is the Microsoft public cloud platform, offering the biggest global reach and the most comprehensive service back end. It supports the use of multiple OS, language, database and tool options, providing automatic OS and service patching. The underlying network infrastructure offers automatic load balancing and resiliency to hardware failure. Last, but not least, Azure supports a deployment model that enables developers to upgrade applications without downtime.

The Web service application presented in this article can be hosted in one or more of Microsoft’s global cloud datacenters in a matter of minutes. Whether you’re building a to-do list application, a game or even a line-of-business accounting application, it’s possible to leverage the techniques in this article to support scenarios that rely on either permanently or occasionally connected clients.

What You’ll Learn

First, we’ll describe how to build a simple cloud-hosted service on Azure to support asynchronous clients, regardless of the type of device it’s running on—phone, slate, tablet, laptop or desktop. Then we’ll show you how easy it is to call into a Web service from a Windows Store application to retrieve data.

Generally speaking, there are two ways data can make its way into a Windows Store application. This article will focus on the “pull approach” for retrieving data, where the application needs to be running and data requests are issued via HTTP Web calls. The pull approach typically leverages open standards (HTTP, JSON, Representational State Transfer [REST]), and most—if not all—­device types from different vendors can take advantage of it.

We won’t be covering the “push approach” in this article. This approach relies on Windows Push Notification Services (WNS), which allows cloud-hosted services to send unsolicited data to a Windows Store application. Such applications don’t need to be running in the foreground and there’s no guarantee of message delivery. For information about using WNS, see bit.ly/RSXomc.

Two Projects

The full solution requires two main components: a server-side or Web services project (which can be deployed on-premises or in Azure), and a client-side project, which consists of a Windows Store application based on the new Windows UI. Both projects can be created with Visual Studio 2012.

Basically, there are two options for building the Web services project: Windows Communication Foundation (WCF) or the ASP.NET Web API, which is included with ASP.NET MVC 4. Because exposing services via WCF is widely documented, for our scenario we’ll use the more modern approach that the ASP.NET Web API brings to the table, truly embracing HTTP concepts (URIs and verbs). Also, this framework lets you create services that use more advanced HTTP features, such as request/response headers and hypermedia constructs.

Both projects can be tested on a single machine during development. You can download the entire solution at archive.msdn.microsoft.com/mag201210AzureInsider.

What You Need

The most obvious starting point is that Windows 8 is required, and it should come as no surprise that the projects should be created using the latest release of Visual Studio, which can be downloaded at bit.ly/win8devtools.

For the server-side project, you’ll need the latest Azure SDK, which includes the necessary assemblies and tooling for creating cloud projects from within Visual Studio. You can download this SDK and related tooling at bit.ly/NlB5OB. You’ll also need an Azure account. A free trial can be downloaded at bit.ly/azuretestdrive.

Historically, SOAP has been used to architect Web services, but this article will focus on REST-style architectures. In short, REST is easier to use, carries a smaller payload and requires no special tooling.

Developers must also choose a data-exchange format when building Web services. That choice is generally between JSON and XML. JSON uses a compact data format based on the JavaScript language. It’s often referred to as the “fat-free alternative” to XML because it has a much smaller grammar and maps directly to data structures used in client applications. We’ll use JSON data in our samples.

With these decisions made, we’re ready to create our Web service. Our goal is to build an HTTP-based service that reaches the broadest possible range of clients, including browsers and mobile devices.

Building the Web Service

Let’s begin by starting Visual Studio 2012 as Administrator. Here are the steps to create the server-side Web service, using the ASP.NET MVC 4 Web API:

  1. Click on the File menu and choose New | Project (see Figure 1).
  2. Select Visual C# | Web for the template type.
  3. Select .NET Framework 4 in the dropdown at the top.
  4. Select ASP.NET MVC 4 Web Application.
  5. Enter the Name WebService and a Location of your choice.
  6. Click OK.
  7. The wizard will ask you to select the Project Template. Choose Web API and be sure the View engine is Razor (the default), as shown in Figure 2.
  8. A variety of files will be generated by Visual Studio. This can be overwhelming, but we only need to worry about a couple of files, as shown in Figure 3.

New Project Dialog Box
Figure 1 New Project Dialog Box

Project Template Dialog Box
Figure 2 Project Template Dialog Box

Solution Explorer for WebService
Figure 3 Solution Explorer for WebService

ValuesController.cs is important because it contains the code that will execute when the Windows 8 client submits an HTTP request against the Web service. This is where we’ll add code to return the JSON data required by the Windows Store application. The ValuesController class, shown in Figure 4, is generated by Visual Studio and it inherits from ApiController, which returns data that’s serialized and sent to the client, automatically in JSON format.

Figure 4 ValuesController Class

public class ValuesController : ApiController
{
  // GET api/values
  public IEnumerable<string> Get()
  {
    return new string[] { "value1", "value2" };
  }
  // GET api/values/5
  public string Get(int id)
  {
    return "value";
  }
  // POST api/values
  public void Post([FromBody]string value)
  {
  }
  // PUT api/values/5
  public void Put(int id, [FromBody]string value)
  {
  }
  // DELETE api/values/5
  public void Delete(int id)
  {
  }
}

Note that the methods in Figure 4—Get, Post, Put and Delete—map to specific create, read, update and delete (CRUD) operations and HTTP verbs executed by the Windows Store application. This is the beauty of the ASP.NET Web API framework: It automatically routes the HTTP verbs used by the client directly to the methods defined in the ValuesController class, minimizing potential programming mistakes.

Out of the box, the WebService project is ready to run. The methods in the ValuesController class are self-documenting:

// GET api/values
public IEnumerable<string> Get()
{
  return new string[] { "value1", "value2" };
}

Note that the Get method is called when the client issues the HTTP verb Get using the URL http://localhost:[port]/api/values. For the purpose of this demo, the code draws concentric circles based on colors returned from the Web service. Modify the preceding code to look like this:

// GET api/values
public IEnumerable<string> Get()
{
  return new string[] { "#0000FF", "#000000", "#FF0000",
    "#FFFF00", "#00FF00" };
}

As you can see, we now return an array of strings of various colors. The Windows Store application we create will render these strings as actual colors, specifically as colored concentric circles.

Testing with a Browser

It’s always a good idea to test the Web service before creating the Windows Store application. Use any browser you like.

To test the Web service from a browser, perform the following steps:

  1. In Visual Studio, click on the Debug menu and choose Start Debugging.
  2. You should see the default start page, as shown in Figure 5.
  3. Notice that Visual Studio chooses an arbitrary port, in this case 58428. The port your instance of Visual Studio uses will likely differ.
  4. As you’ll recall, we need to add “api/values” to the URL so the Get method gets called, which means the final URL (in our case) should be http://localhost:58428/api/values. This is a built-in feature when Visual Studio creates your project. You can change this mapping to suit your needs.
  5. Go to the address bar of Visual Studio and type in http://localhost:58428/api/values. Remember to replace the port number with your own value.
  6. A dialog box will appear like the one in Figure 6.
  7. Click on the Save button, then open values.json in Notepad.
  8. Notepad will display the values returned. Notice in Figure 7 that the data returned is automatically in JSON format, courtesy of the ASP.NET Web API framework.

Using Internet Explorer to Test the Web Service
Figure 5 Using Internet Explorer to Test the Web Service

Internet Explorer Dialog Box
Figure 6 Internet Explorer Dialog Box

The JSON Data Returned by the Web Service
Figure 7 The JSON Data Returned by the Web Service

Enter Windows 8

Now that we’ve succeeded in returning JSON data from our Web service, let’s see how to consume this data from a Windows Store application. The goal is to read the colors from the Web service and to draw the concentric circles based on the values returned by the Web service. Our final Windows Store application should produce an image that looks like Figure 8. The colors you see were defined by the Web service. If the Web service changes the colors returned, the Windows Store application would reflect those colors as the concentric circles you see in Figure 8.

The Running Windows Store Application
Figure 8 The Running Windows Store Application

You can either create the Windows Store application in the same solution as the Web service project, or you can start a new instance of Visual Studio specifically for the Windows 8 client. We’ll start a new instance of Visual Studio as Administrator for the Windows Store app. To do this, follow these steps (see Figure 9):

New Project Dialog Box
Figure 9 New Project Dialog Box

  1. Start a second instance of Visual Studio as Administrator.
  2. Click on the File menu and choose New | Project.
  3. Select Visual C# | Windows Store for the template type.
  4. Select .NET Framework 4.5 in the dropdown at the top.
  5. Select Blank App (XAML).
  6. Enter the Name Windows8Client and a Location of your choice.
  7. Click OK.

When you’re finished with these steps, navigate to the View menu and choose Solution Explorer (see Figure 10), and open the file MainPage.xaml.cs.

Solution Explorer for Windows8Client
Figure 10 Solution Explorer for Windows8Client

Calling into the Web Service

We’re ready to add the code that will call into the Web service from the Windows Store application. The Windows Store application will issue a Web request against the Web service.

To support a Web request, MainPage.xaml.cs will be modified as follows:

  • A Loaded event will be added for the built-in Grid control.
  • The Loaded event will submit an asynchronous Web request to call into the Web service. The HttpClient class will be used for this purpose.
  • To convert the color string from the Web service into a real color, a method called CircleColorFromString will be added.
  • To draw the concentric circles, we’ll add a method called AddCircle.

Perform the following steps to issue a Web request against the Web service:

  1. Right-click MainPage.xaml and choose View Designer.
  2. Add the GridLoadedEvent and the Canvas control as follows (the canvas is where we’ll draw the circles):
<Grid Name="maingrid"
      Background="{StaticResource
                   ApplicationPageBackgroundThemeBrush}"
      Loaded="GridLoadedEvent">
  <Canvas Name="myCanvas" Background="White"/>
</Grid>
  1.  3.   Double-click MainPage.xaml.cs. The codebehind for MainPage.xaml.cs appears.
  2.  4.   To support the different namespaces required by the code to be added, include the following references at the top of MainPage.xaml.cs:
using System.Net.Http;          // for HttpClient()
using Windows.Data.Json;        // for parsing JSON Array data
using Windows.UI.Xaml.Shapes;   // for the Ellipse object
using Windows.UI                // for the Color class
  1.  5.   Add the supporting routines to draw the circles and parse the JSON string data sent by the Web service. Edit the code in MainPage.xaml.cs as shown in Figure 11.

Figure 11 MainPage.xaml.cs

public sealed partial class MainPage : Page
  {
    // [ Generated code omitted for brevity ]
    private void AddCircle(Color color, int diameter, int t, int l)
    {
      //
      // Build a circle using the attributes provided as parameters.
      //
      Ellipse newColoredCircle = new Ellipse();
      newColoredCircle.Fill = new SolidColorBrush(color);
      newColoredCircle.StrokeThickness = 1;
      newColoredCircle.Stroke = new SolidColorBrush(color);
      newColoredCircle.Width = diameter;
      newColoredCircle.Height = diameter;
      //
      // Add the circle to the Canvas control.
      //
      myCanvas.Children.Add(newColoredCircle);
      Canvas.SetTop(newColoredCircle, t);
      Canvas.SetLeft(newColoredCircle, l);
    }
    Color CircleColorFromString(string rgb)
    {
      //
      // Convert the string-based hex values
      // into a Color object and return to caller.
      //
      Color ringColor = new Color();
      byte a = 255;
      byte r = (byte)(Convert.ToUInt32(rgb.Substring(1, 2), 16));
      byte g = (byte)(Convert.ToUInt32(rgb.Substring(3, 2), 16));
      byte b = (byte)(Convert.ToUInt32(rgb.Substring(5, 2), 16));
      ringColor = Color.FromArgb(a, r, g, b);
      return ringColor;
    }
    private async void GridLoadedEvent(object sender, 
      RoutedEventArgs e)
    {
      //
      // Retrieve colors from Web service.
      //
      var client = new HttpClient();
      client.MaxResponseContentBufferSize = 1024 * 1024;
      //
      // Asynchronously call into the Web service.
      //
      var response = await client.GetAsync(
        new Uri("http://localhost:58428/api/values"));
      var result = await response.Content.ReadAsStringAsync();
      //
      // Parse the JSON data
      //
      var parsedResults = JsonArray.Parse(result);
      //
      // Build concentric circles, repeating colors as needed
      //
      const double startingPercentage = 1.0;
      const double desiredCircleCount = 50.0;
      for (int i = 0; i < desiredCircleCount; i++)
      {
        Color circleColor = CircleColorFromString(
          parsedResults[i % parsedResults.Count].GetString());
        int circleDiameter = Convert.ToInt32((startingPercentage –
          (i / desiredCircleCount)) * this.RenderSize.Width / 2.0);
        int top = Convert.ToInt32((this.RenderSize.Height -
          circleDiameter)/2.0);
        int left = Convert.ToInt32((this.RenderSize.Width -
          circleDiameter)/2.0);
        AddCircle(circleColor, circleDiameter, top, left);
      }
    }
}

Now test the application, which is quite simple:

  1. Return to the WebService project in Visual Studio and select Start Debugging from the Debug menu.
  2. Verify that the browser starts. You’re now ready to start the Windows8Client application.
  3. Return to the Windows8Client project in Visual Studio and select Start Debugging from the Debug menu.
  4. Verify the Windows Store application appears, as shown in Figure 8.

Deploying the Web Service to Azure

Once the Web service has been created and tested locally, the next logical step is to deploy it to the cloud for scalability purposes. This lets you vary the compute capacity assigned to the Web service—and its cost—as the number of requests from Windows 8 devices increases or decreases. Visual Studio offers different ways to deploy ASP.NET Web API projects to Azure, and the only prerequisite is to add a cloud service project to the Web service solution. Follow these steps:

  1. Right-click on the Solution name, and select Add | New project.
  2. Select Visual C# | Cloud as the project template (Figure 12).
  3. Select .NET Framework 4 in the dropdown at the top.
  4. Select Azure Cloud Service Visual C#.
  5. Enter the Name WindowsAzureCloudService and a Location of your choice.
  6. Click OK.
  7. Now go back to the Solution Explorer. Find the new project in the solution and right-click on the Roles node. Select Add | Web Role Project.
  8. Find the previously created WebService project. Select it and click OK.
  9. You should now see the WebService project listed under the Roles node as shown in Figure 13.
  10. You can change various deployment parameters for the WebService role before deploying it to Azure, such as the size of the virtual machine (VM) where it’s going to be hosted and the number of instances supporting it. To review these parameters, right-click on the WebService Roles node and select Properties. A dialog like the one in Figure 14 is displayed. Pay special attention to the Instance count and the VM size parameters, which will determine the consumption rate once the role has been deployed. For more information about Azure pricing for compute instances, visit bit.ly/SnLj68.
  11. Right-click on the Windows­AzureCloudService project, and select Package. Keep the default selections for the Service and Build configuration parameters, and click on the Package button. This action will generate two files: Windows­AzureCloudService.cspkg and ServiceConfiguration.Cloud.cscfg, which are required to create a cloud service on Azure via the portal. Note that projects can be directly deployed from Visual Studio, but we won’t cover this approach here.
  12. Log in to your Azure account by opening the URL manage.windowsazure.com, then follow the instructions at bit.ly/R15VNj for creating a new cloud service and uploading the two generated files.
  13. Depending on the name you use for the cloud service, your new ASP.NET Web API will be available at http://{cloudservicename}.cloudapp.net/api/values.
  14. Point the Windows Store application to this URL, and you’re done.

Adding a Cloud Service Project to the Web Service Solution
Figure 12 Adding a Cloud Service Project to the Web Service Solution

Adding the WebService Project to a Cloud Service Role
Figure 13 Adding the WebService Project to a Cloud Service Role

Azure Deployment Properties for the WebService Role
Figure 14 Azure Deployment Properties for the WebService Role

In the Cloud

By using the ASP.NET Web API, it’s extremely simple to support applications that asynchronously use REST commands for consuming and ingesting data via Web services. Visual Studio 2012 and the libraries included with the .NET Framework 4.5 make it very simple to issue asynchronous Web requests against a Web service. Last, but not least, the integration of the development environment with Azure allows developers to rapidly deploy the services portion to the cloud, taking advantage of the scalability and worldwide infrastructure capabilities the cloud provides.


Bruno Terkaly is a developer evangelist for Microsoft. His depth of knowledge comes from years of experience in the field, writing code using a multitude of platforms, languages, frameworks, SDKs, libraries and APIs. He spends time writing code, blogging and giving live presentations on building cloud-based applications, specifically using the Azure platform.

Ricardo Villalobos is a seasoned software architect with more than 15 years of experience designing and creating applications for companies in the supply chain management industry. Holding several technical certifications as well as a master’s degree in business administration from the University of Dallas, he works as a cloud architect in the Azure CSV incubation group for Microsoft.

Thanks to the following technical expert for reviewing this article: Robert Green