Combining Silverlight and Windows Azure projects

A step-by-step guide to creating and running scalable Silverlight Enterprise Applications on the Windows Azure platform with this book and ebook

Combining Silverlight and Windows Azure projects

Standard Silverlight applications require that they be hosted on HTML pages, so that they can be loaded in a browser. Developers who work with the .Net framework will usually host this page within an ASP.Net website.

The easiest way to host a Silverlight application on Azure is to create a single web role that contains an ASP.Net application to host the Silverlight application. Hosting the Silverlight application in this way enables you, as a developer, to take advantage of the full .Net framework to support your Silverlight application. Supporting functionalities can be provided such as hosting WCF services, RIA services, Entity Framework, and so on.

In the upcoming chapters, we will explore ways by which RIA services, OData, Entity Framework, and a few other technologies can be used together. For the rest of this chapter, we will focus on the basics of hosting a Silverlight application within Azure and integrating a hosted WCF service.

Creating a Silverlight or Azure solution

Your system should already be fully configured with all Silverlight and Azure tools.

In this section, we are going to create a simple Silverlight application that is hosted inside an Azure web role. This will be the basic template that is used throughout the book as we explore different ways in which we can integrate the technologies together:

  1. Start Visual Studio as an administrator. You can do this by opening the Start Menu and finding Visual Studio, then right-clicking on it, and selecting Run as Administrator. This is required for the Azure compute emulator to run successfully.
  2. Create a new Windows Azure Cloud Service. The solution name used in the following example screenshot is Chapter3Exercise1:
  3. (Move the mouse over the image to enlarge.)

  4. Add a single ASP.Net Web Role as shown in the following screenshot. For this exercise, the default name of WebRole1 will be used. The name of the role can be changed by clicking on the pencil icon next to the WebRole1 name:
  5. Visual Studio should now be loaded with a single Azure project and an ASP. Net project. In the following screenshot, you can see that Visual Studio is opened with a solution named Chapter3Exercise1. The solution contains a Windows Azure Cloud project, also called Chapter3Exercise1. Finally, the ASP.Net project can be seen named as WebRole1:
  6. Right-click on the ASP.Net project named WebRole1 and select Properties.
  7. In the WebRole1 properties screen, click on the Silverlight Applications tab.
  8. Click on Add to add a new Silverlight project into the solution. The Add button has been highlighted in the following screenshot:
  9. For this exercise, rename the project to HelloWorldSilverlightProject. Click on Add to create the Silverlight project. The rest of the options can be left to their default settings, as shown in the following screenshot.
  10. Visual Studio will now create the Silverlight project and add it to the solution. The resulting solution should now have three projects as shown in the following screenshot. These include the original Azure project, Chapter3Exercise1; the ASP.Net web role, WebRole1; and the third new project HelloWorldSilverlightProject:
  11. Open MainPage.xaml in design view, if not already open.
  12. Change the grid to a StackPanel.
  13. Inside the StackPanel, add a button named button1 with a height of 40 and a content that displays Click me!.
  14. Inside the StackPanel, underneath button1, add a text block named textBlock1 with a height of 20
  15. The final XAML should look similar to this code snippet:
  16. <UserControl>
    <StackPanel x:Name="LayoutRoot" Background="White">
    <Button x:Name="button1" Height="40"
    Content="Click me!" />
    <TextBlock x:Name="textBlock1" Height="20" />

  17. Double-click on button1 in the designer to have Visual Studio automatically create a click event. The final XAML in the designer should look similar to the following screenshot:
  18. Open the MainPage.xaml.cs code behind the file and find the button1_Click method. Add a code that will update textBlock1 to display Hello World and the current time as follows:
  19. private void button1_Click(object sender, RoutedEventArgs e)
    textBlock1.Text = "Hello World at " +

  20. Build the project to ensure that everything compiles correctly.

    Now that the solution has been built, it is ready to be run and debugged within the Windows Azure compute emulator. The next section will explore what happens while running an Azure application on the compute emulator.

Running an Azure application on the Azure compute emulator

With the solution built, it is ready to run on the Azure simulation: the compute emulator. The compute emulator is the local simulation of the Windows Azure compute emulator which Microsoft runs on the Azure servers it hosts.

When you start debugging by pressing F5 (or by selecting Debug | Start Debugging from the menu), Visual Studio will automatically package the Azure project, then start the Azure compute emulator simulation. The package will be copied to a local folder used by the compute emulator. The compute emulator will then start a Windows process to host or execute the roles, one of which will be started as per the instance request for each role.

Once the compute emulator has been successfully initialized, Visual Studio will then launch the browser and attach the debugger to the correct places. This is similar to the way Visual Studio handles debugging of an ASP.Net application with the ASP. Net Development Server.

The following steps will take you through the process of running and debugging applications on top of the compute emulator:

  1. In Solution Explorer, inside the HelloWorldSilverlightProject, right-click on HelloWorldSilverlightProjectTestPage.aspx, and select Set as startup page.
  2. Ensure that the Azure project (Chapter3Exercise1) is still set as the start-up project.
  3. In Visual Studio, press F5 to start debugging (or from the menu select Debug | Start Debugging). Visual Studio will compile the project, and if successful, begins to launch the Azure compute emulator as shown in the following screenshot:
  4. Once the compute emulator has been started and the Azure package deployed to it, Visual Studio will launch Internet Explorer. Internet Explorer will display the page set as the start-up page (which was set to in an earlier step HelloWorldSilverlightProjectTestPage.aspx).
  5. Once the Silverlight application has been loaded, click on the Click me! button. The TextBlock should be updated with the current time, as shown in the following screenshot:
  6. Upon this completion, you should now have successfully deployed a Silverlight application on top of the Windows Azure compute emulator. You can now use this base project to build more advanced features and integration with other services.

Consuming an Azure-hosted WCF service within a Silverlight application

A standalone Silverlight application will not be able to do much by itself. Most applications will require that they consume data from a data source, such as to get a list of products or customer orders. A common way to send data between .Net applications is through WCF services.

The following steps will explore how to add a WCF service to your Azure web role, and then consume it from within the Silverlight application:

  1. In Visual Studio, right-click on the ASP.Net web role project (WebRole1) and click Add | New Item.
  2. Add a new WCF service named HelloWorldService.svc as shown in the following screenshot:
  3. Once the WCF service has been added into the project, three new files will be added to the project: IHelloWorldService.cs, HelloWorldService.svc, and HelloWorldService.svc.cs.
  4. Open IHelloWorldService.cs and change the interface, so that it defines a single method named GenerateHelloWorldGreeting that takes no parameters and returns a string. The entire file should look similar to the following code snippet:
  5. using System.ServiceModel;
    namespace WebRole1
    public interface IHelloWorldService
    string GenerateHelloWorldGreeting();

  6. Open HelloWorldService.svc.cs and modify the code, so that it implements the GenerateHelloWorldGreeting method as follows (the method in the code snippet returns Hello World, as well as the current server time):
  7. using System;
    namespace WebRole1
    public class HelloWorldService : IHelloWorldService
    public string GenerateHelloWorldGreeting()
    var currentTime = DateTime.Now.ToLongTimeString();
    return "Hello World! The server time is " + currentTime;

  8. Add a breakpoint on the line of code that returns the "Hello world" message. This breakpoint will be used in a later step.
  9. Build the solution to ensure there are no syntax errors. If the solution does not build, then runtime errors can occur when trying to add the service reference.
  10. Right-click on the Silverlight project HelloWorldSilverlightProject and select Add Service Reference. Click on Discover to allow Visual Studio to automatically detect the WCF service in the solution. Select the service and name the reference HelloWorldServiceReference, as shown in the screenshot, and click OK:
  11. With the WCF service reference added to the Silverlight application, we will change the functionality of the Click me! button. Currently when clicked, the event handler will update the TextBlock with a "Hello world" message and the current time on the client side. This will be changed, so that clicking on the button will cause the Silverlight application to call the WCF service and have the "Hello world" message generated on the server side. In Visual Studio, within the Silverlight project, open MainPage.xaml.cs.
  12. Modify the button1_Click method, so that it calls the WCF service and updates textBlock1 with the returned value. Due to the dynamic nature of developing with Azure, the address of the service endpoint can change many times through the development lifecycle. Each time Visual Studio deploys the project onto the compute emulator, a different port number can be assigned if the previous deployment has not been de-provisioned yet. Deploying to the Windows Azure staging environment will also give it a new address, while deploying to production will provide yet another endpoint address. The following code shows one technique to automatically handle the Silverlight application being hosted at different addresses. The Silverlight application invokes the WCF service by accessing it relative to where the Silverlight application is currently being hosted. This is in contrast to the usual behavior of calling WCF services which require an absolute address that would need to be updated with each deployment.
  13. using System;
    using System.ServiceModel;
    using System.Windows;
    using System.Windows.Controls;
    using HelloWorldSilverlightProject.HelloWorldServiceReference;
    namespace HelloWorldSilverlightProject
    public partial class MainPage : UserControl
    public MainPage()
    private void button1_Click(object sender, RoutedEventArgs e)
    //Find the URL for the current Silverlight .xap file. Go up
    one level to get to the root of the site.
    var url = Application.Current.Host.Source.OriginalString;
    var urlBase = url.Substring(0, url.IndexOf("/ClientBin",
    //Create a proxy object for the WCF service. Use the root
    path of the site and append the service name
    var proxy = new HelloWorldServiceClient();
    proxy.Endpoint.Address = new EndpointAddress(urlBase +
    proxy.GenerateHelloWorldGreetingCompleted +=
    void proxy_GenerateHelloWorldGreetingCompleted(object sender,
    GenerateHelloWorldGreetingCompletedEventArgs e)
    textBlock1.Text = e.Result;

    Relative WCF services

    The code in the code snippet shows a technique for calling WCF services relative to the currently executing Silverlight application. This technique means that the Silverlight application is not dependent on the service address being updated for each deployment. This allows the whole ASP.Net application to be hosted and deployed on a number of environments without configuration changes, such as the ASP.Net development server, Azure compute emulator, Azure staging or production environments, or on any other IIS host.

  14. Compile the application to check that there are no syntax errors.
  15. Press F5 to run the whole application in a debug mode. The Azure compute emulator should start up and Internet Explorer should be launched again with the Silverlight application.
  16. Click on the Click me! button. The Silverlight client will call the WCF service causing Visual Studio to hit the breakpoint that was set earlier inside the WCF service. This shows that even though we are running and debugging a Silverlight application, we are still able to debug WCF services that are being hosted inside the Azure compute emulator.
  17. Remove the breakpoint and continue the execution. Click on the button a few more times to watch the TextBlock update itself. The results should look similar to the following screenshot. Be sure to keep the browser open for the next steps:
  18. Open the Azure compute emulator. Do this by right-clicking on the Azure icon in the system tray, and then clicking on Show Compute Emulator UI.
  19. The compute emulator UI should now be open and look similar to the following screenshot. In the screenshot, you can see that there is a single deployment (the 29th one that has been deployed to the compute emulator). The deployment has one Azure project named Chapter3Exercise1. This Azure project has a single web role named WebRole1, which is currently executing a single instance. Clicking on the instance will show the output terminal of that instance. Here the trance information can be seen, being an output to the window:

Configuring the number of web roles

The power in Azure comes from running multiple instances of a single role and distributing the computational load. It is important to understand how to configure the size and number of instances of a role that should be initialized.

The following steps will explain how this can be done within the Visual Studio:

  1. Stop debugging the application and return to Visual Studio.
  2. Inside the Azure project Chapter3Exercise1, right-click on WebRole1, and select Properties.

The role properties window is used to specify both the size of the instances that should be used, as well as the number of instances that should be used.

The VM size has no effect on the compute emulator, as you are still constrained by the local development machine. The VM size setting is used when the package is deployed onto the Windows Azure servers. It defines the number of CPUs and amounts of RAM allocated to each instance. These settings determine the charges Microsoft will accrue to your account.

In the earlier stages of development, it can be useful to set the VM size to extra small to save consumption costs. This can be done in situations where performance is not a high requirement, such as when a few developers are testing their deployments.

Extra small instances

The extra small instances are great while developing as they are much cheaper instances to deploy. However, they are low-resourced and also have bandwidth restrictions enforced on them. They are not recommended for use in a high performance production environment.

The Instance count is used to specify the number of instances of the role that should be created. Creating multiple instances of a role can assist in testing concurrency while working with the compute emulator. Be aware that you are still constrained by the local development box, setting this to a very large number can lower the performance of your machine:

  1. Set the Instance count to 4 as shown in the following screenshot. If you are planning to deploy the application to the Windows Azure servers, it is a good idea to set the VM size to Extra Small while testing:
  2. Open HelloWorldService.svc.cs and modify the service implementation. The service will now use the Windows Azure SDK to retrieve instance ID that is currently handling the request:
  3. using System;
    using Microsoft.WindowsAzure.ServiceRuntime;
    namespace WebRole1
    public class HelloWorldService : IHelloWorldService
    public string GenerateHelloWorldGreeting()
    var currentTime = DateTime.Now.ToLongTimeString();
    var instanceId = RoleEnvironment.CurrentRoleInstance.Id;
    return string.Format("Hello World! The server time is {0}.
    Processed by {1}", currentTime, instanceId);

  4. Press F5 to debug the project again.
  5. Open the Azure compute emulator UI. There should now be four instances handling the request.
  6. In Internet Explorer, click on the Click me! button multiple times. The text will update with the server time and the instance that handled the request. The following screenshot shows that instance 1 was handling the request. If the instance ID does not change after multiple clicks, try to launch a second browser, and click again. Sometimes, affinity can cause a request to get sticky and stay with a single instance:

This exercise demonstrated requests for a WCF service being load balanced over a number of Azure instances. The following diagram shows that as requests from the Silverlight client come in, the load balancer will distribute the requests across the instances. It is important to keep this in mind while developing Azure services and develop each role to be stateless services when working with multiple instances. Each request may be handled by a different instance each time, requiring you to not keep any session state inside an instance:


In this article, we created a new Silverlight application that was hosted with an Azure project. We then created a WCF service that was also hosted within the Azure project, and consumed it from the Silverlight application. The WCF service was then scaled to 4 instances to demonstrate how WCF requests can be load balanced across multiple instances. A technique was also shown to allow a WCF service to be consumed through a relative path, allowing the website to be hosted anywhere without the service address needing to be changed for each deployment.

Books to Consider

comments powered by Disqus

An Introduction to 3D Printing

Explore the future of manufacturing and design  - read our guide to 3d printing for free