Jean Paul's Blog

There are 2 types of People in the World, One who Likes SharePoint and..

  • Microsoft MVP

  • MindCracker MVP

  • CodeProject MVP

  • eBook on SharePoint 2010

  • eBook on Design Patterns

  • eBook on Windows Azure

  • NLayers Framework @ CodePlex

  • MSDN Forums

  • .Net vs. Java

    Due to Public Demand

Windows Azure – WCF in Worker Role

Posted by JP on November 29, 2011


In this article I am going to demonstrate the creation of WCF service in Worker Role and deployment to the cloud.

The attributes of WCF service on Worker role are:

  • Self Hosted
  • More Flexibility Attained
  • More Configurations Needed

Following are the steps involved.

Step 1: Create the WCF Service

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

clip_image002

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

clip_image004

Add reference to the System.ServiceModel assembly.

clip_image006

Add the following 2 files

  • Interface named IMessengerService
  • Class named MessengerService

Replace the contents of 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 WCF service. Now the solution explorer looks like below:

clip_image008

In the case of 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”&gt;

<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.

clip_image010

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.

clip_image012

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

clip_image014

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 Package menu item.

clip_image016

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

clip_image018

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

clip_image020

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

clip_image022

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.

clip_image024

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

clip_image026

Step 3: 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

clip_image028

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.

clip_image030

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.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s