.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
 
Sign In
Register
 
Win Surprise Gifts!!!
Congratulations!!!


Top 5 Contributors of the Month
Lee Hnetinka
mithun

Home >> Articles >> Azure >> Post New Resource Bookmark and Share   

 Subscribe to Articles

Azure Part 37 - Windows Azure – WCF in Worker Role

Posted By:Jean Paul       Posted Date: April 25, 2012    Points: 200    Category: Azure    URL: http://www.dotnetspark.com  

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

Windows Azure – WCF in Worker Role

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




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



Add reference to the System.ServiceModel assembly.




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:



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.



  
	
	  
		
		
		  
		  
        
  

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.



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.



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



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.



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



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



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



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.



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




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



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.

  

Now set the console application as the start project and execute the application.
You can see the following results.



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.

 Subscribe to Articles

     

Further Readings:

Responses

No response found. Be the first to respond this post

Post Comment

You must Sign In To post reply
Find More Articles on C#, ASP.Net, Vb.Net, SQL Server and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend