Windows Azure - WCF in the Worker Role

In this article I am going to demonstrate the following

  • Creation of a WCF service in Worker Role
  • Deployment to the cloud
  • Testing with a client

The attributes of a WCF service on a Worker role are:

  • Self Hosted
  • More Flexibility Attained
  • More Configuration Needed

The following are the steps involved.

Step 1: Create the WCF Service

Create a new Windows Azure project in Visual Studio 2010 and name it WCFInWorkerRole as shown below

WCFWinAzr1.gif

In the appearing dialog add one Worker Role project as shown below.

WCFWinAzr2.gif

Add a reference to the System.ServiceModel assembly.

WCFWinAzr3.gif

Add the following 2 files

  • Interface named IMessengerService
  • Class named MessengerService

Replace the contents of the above files with the following:

// IMessengerContract.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

namespace WorkerRole1
{
    [
ServiceContract]
   
public interface IMessengerService
    {
        [
OperationContract]
       
string SendMessage(string name);
    }
}

// MessengerService.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

namespace WorkerRole1
{
   
public class MessengerService : IMessengerService
    {
       
public string SendMessage(string name)
        {
           
return "Hello " + name + ". How do you do?";
        }
    }
}


Remove the app.config from the worker role project as we are going to do manual configuration of the WCF service. Now the solution explorer looks like below:

WCFWinAzr4.gif

In the case of a web role, the context and port was automatically identified. But in the worker role, we need to update the properties manually. The host name will be different in the development and deployment servers.

Modify the ServiceDefinition.csdef file as below.

<?xml version="1.0" encoding="utf-8"?>
<
ServiceDefinition name="WCFInWorkerRole" xmlns="http://schemas.microsoft.com/ServiceHosting/2008/10/ServiceDefinition">
  <
WorkerRole name="WorkerRole1" vmsize="Small">
       <
Imports>
         <
Import moduleName="Diagnostics" />
              </
Imports>
              <
Endpoints>
                <
InputEndpoint name="port" protocol="tcp" port="9001" />
                <
InputEndpoint name="mexport" protocol="tcp" port="8001" />
        </
Endpoints>
  </
WorkerRole>
</
ServiceDefinition>

The content defines the port and metadata port for our WCF service. Now we can modify the OnStart() method of the Worker role class as given below.

public override bool OnStart()
{
   
// Set the maximum number of concurrent connections
    ServicePointManager.DefaultConnectionLimit = 12;

    // Create the host
    ServiceHost host = new ServiceHost(typeof(MessengerService));

    // Read config parameters
    string hostName = RoleEnvironment.CurrentRoleInstance.InstanceEndpoints["port"].IPEndpoint.Address.ToString();
   
int port = RoleEnvironment.CurrentRoleInstance.InstanceEndpoints["port"].IPEndpoint.Port;
   
int mexport = RoleEnvironment.CurrentRoleInstance.InstanceEndpoints["mexport"].IPEndpoint.Port;

    // Create Metadata
    ServiceMetadataBehavior metadatabehavior = new ServiceMetadataBehavior();
    host.Description.Behaviors.Add(metadatabehavior);

    Binding mexBinding = MetadataExchangeBindings.CreateMexTcpBinding();
   
string mexendpointurl = string.Format("net.tcp://{0}:{1}/MessengerServiceMetadata", hostName, 8001);
    host.AddServiceEndpoint(
typeof(IMetadataExchange), mexBinding, mexendpointurl, new Uri(mexendpointurl));

    // Create end point
    string endpointurl = string.Format("net.tcp://{0}:{1}/MessengerService", hostName, 9001);
    host.AddServiceEndpoint(
typeof(IMessengerService), new NetTcpBinding(SecurityMode.None), endpointurl, new Uri(endpointurl));

    // Open the host
    host.Open();

    // Trace output
    Trace.WriteLine("WCF Listening At: " + endpointurl);
   
Trace.WriteLine("WCF MetaData Listening At: " + mexendpointurl);

    return base.OnStart();
}

The code performs the following:

  • Create Service Host

  • Read the Port number

  • Add the Metadata behaviour

  • Add the endpoints

  • Opens the Host

Note: The attached source code contains the working application.

Step 2: Test the application

Now we can test the application by executing it. If successfully executed we can see the trace from the Output window.

WCFWinAzr5.gif

You can see two addresses from the above screen:

  • The actual service end point

  • The metadata end point

We can also see the trace from the load development machine. The Windows Azure Compute Emulator can be used for this purpose.

WCFWinAzr6.gif

On invoking the Show Computer Emulator UI we can see the following window.

WCFWinAzr7.gif

The above window contains the same trace output with the end point urls. You may try adding reference to the metadata end point using the metadata url. We are going to deploy the service to cloud and test it.

Step 3: Deploy to the cloud

Now our application is working fine and we can deploy it to the online cloud. For this right click on the project and click the Package menu item.

WCFWinAzr8.gif

In the appearing dialog box, choose the default options and click the Package button.

WCFWinAzr9.gif

Now sign in to the Windows Azure portal and click on the New Hosted Service button from the top ribbon.

WCFWinAzr10.gif

In the appearing dialog box enter the details as shown below.

WCFWinAzr11.gif

Choose the option "Deploy to production environment"

Locate the package and configuration files from your application bin folder.
(Eg: ..\WCFInWorkerRole\bin\Debug\app.publish)

Please note that the URL prefix should be a unique name. If the URL prefix entered is already in use you need to change it.

After that click the Ok button of the dialog box. (You have to scroll down to see the button)

If any warning box appears, click Yes button to continue. Wait for a few minutes and your deployment will be ready in a few minutes as shown below.

WCFWinAzr12.gif

Select the Deployment 2 row and from the properties window you can get the url of the worker role. Now we just need the host name. In this case wcfinworkerrole.cloudap.net

WCFWinAzr13.gif

Step 4: Create the Client

Now we are ready to create the client application and test the deployed online cloud WCF service.

Create a new console application into the existing Azure project and name it as TestClient.

Use the add service reference option of the console application and in the appearing dialog enter the constructed service url as shown below.

Constructed Url: net.tcp://wcfinworkerrole.cloudapp.net:8001/MessengerServiceMetadata

Please note that we added the following:

  • Protocol as net.tcp

  • Host Name from previous step

  • Port number as 8001

  • Metadata Context Name

WCFWinAzr14.gif

Click the Go button and after seeing the MessengerService item populated, Click the Ok button to continue.

Modify the main method in the Program.cs as following:

static void Main(string[] args)
{
    ServiceReference1.
MessengerServiceClient client = new ServiceReference1.MessengerServiceClient();
   
string result = client.SendMessage("Kent");

    Console.WriteLine(string.Format("Invoking WCF Service Result: {0}", result));

    Console.ReadKey(false);
}



Modify the configuration file with the url of the Messenger Service. Please note that the messenger service url is having different port number and context.

<client>
  <
endpoint   
   
address="net.tcp://wcfinworkerrole.cloudapp.net:9001/MessengerService"
    binding="netTcpBinding"  
    bindingConfiguration="NetTcpBinding_IMessengerService"
    contract="ServiceReference1.IMessengerService" 
   
name="NetTcpBinding_IMessengerService" />
</
client>

Now set the console application as the start project and execute the application.

You can see the following results.

WCFWinAzr15.gif

You can see the result Hello Kent. How do you do? from the WCF service.

This concludes our article on WCF service deployment as worker role and the testing.

Multiple End Point

I would like to add a note on the 2 end points we created for the WCF service.

net.tcp://wcfinworkerrole.cloudapp.net:8001/MessengerServiceMetaData \
net.tcp://wcfinworkerrole.cloudapp.net:9001/MessengerService

You can see that there are 2 differences in the above urls:

  • Port

  • Context

Note: WCF with HTTP Port 80 endpoint configuration done as explained here.

Summary

In this article, we have seen how to host a WCF service using the Worker Role and deploy it to the cloud. This service is self hosted and experiments the service creation, hosting, metadata end point adding, deploying and testing with the client. The source code is attached and the application name in the url has to be changed according to your application name.

Up Next
    Ebook Download
    View all
    Learn
    View all