Share via


Microsoft Azure Worker Roles

This article explains how you can create Microsoft Azure Worker Role using Visual C#, so let's start!

  1. Solution selection
  2. Configuration and external EndPoint
  3. Worker Role
  4. Create a Server
  5. Example Source Code

Solution Selection

Open your Visual Studio 2013 select Visual C# under Templates section and select Windows Azure Cloud Service and named as WindowsAzureWorkerRole, then click OK, as shown in the following figure. 

http://kamranshahidbutt.com/wp-content/uploads/2015/01/WindowsAzureWorkerRole1.png

When you click OK, it will show you the following dialog box you need to select Worker Role from role section and then click on > icon to move the role in solution and click OK, and just need to wait for few seconds.

 http://kamranshahidbutt.com/wp-content/uploads/2015/01/WindowsAzureWorkerRole2.png

Configuring an External endpoint

You will need to open WorkerRole1 configuration page, by double-clicking on it or either by right click and then go to Properties and then you need to browse the Endpoints section.

 http://kamranshahidbutt.com/wp-content/uploads/2015/01/WindowsAzureWorkerRole3.png

So now you need to click on "Add Endpoint" to enter the new Endpoint. Here we need to declare the Endpoint name say as "WorkerRoleEndPoint" which listens on an external TCP port with port number "11011", here I need to put some light on Internal endpoint which can only be reached from your solution, not from external PC, This can be useful if you want to host the custom application server inside your project and make it available for other Web/Worker Roles.

http://kamranshahidbutt.com/wp-content/uploads/2015/01/WindowsAzureWorkerRole4.png

Worker Role

Under WorkerRole1 Project you can find a "WorkerRole.cs" file which contains three important functions, OnStart, Run and OnStop along with these three functions you will find an event handler RoleEnvironmentChanging too.

  1. OnStart(): This function run when the Worker Role is starting, here you can initialize the variables/objects and you also can add check depends upon your conditions.
  2. Run(): As the function name is self-explained, in this function you define your all the logic and magic of your project.
  3. OnStop(): This function executes when the Worker Role is stopped.
  4. RoleEnviromentChanging(): This event handler is called when the environment changes like as configuration changed, extra instances fired and you can perform different triggers depends upon the condition.

Create a Server

The main logic will be written under Run() method, so now we'll be creating a new TCPListner which will accept connections from the client when a new client will connect it will dispatch a second thread that will be communicating with the client.

01.public override  void Run()
02.{
03.    TcpListener server = null;
04.    try
05.    {
06.        server = new  TcpListener(
07.            RoleEnvironment.CurrentRoleInstance.InstanceEndpoints["WorkerRoleEndPoint"].IPEndpoint);
08.        server.ExclusiveAddressUse = false;
09.        server.Start();
10.    }
11.    catch (System.Net.Sockets.SocketException ex)
12.    {
13.        Trace.Write("Worker role server could not start." + ex.ToString(), "Error");
14.        return;
15.    }
16. 
17.    while (true)
18.    {
19.        IAsyncResult result = server.BeginAcceptTcpClient(ExecuteClientConnection, server);
20.        WaitForClientHandler.WaitOne();
21.    }
22.}

So now let's discuss the above code.

1.server = new  TcpListener( RoleEnvironment.CurrentRoleInstance.InstanceEndpoints["WorkerRoleEndPoint"].IPEndpoint);

Here we are starting TCPListener which listen on TCP Port "11011", by using IPEndpoint configuration we enable the application to run under production environment along with development environment we don't need to make changes, let me explain you how it will work if we had multiple Worker Roles calling this Server application The client will connect with the TCP Port "11011" and then that port connects with Windows Azure Load Balancer, which decides the internal port and depending upon the load take decision itself either there is a need of new instance or this job can be done with the same instance, if there is a need of new instance it creates a new instance and perform that job on new instance and after performing the job it close the instance.

1.WaitForClientHandler.WaitOne();

This lines mean the server will not accept a new connection until the current one is up and running. So the next very important part of the code is starting an infinite loop which accepts connections and dispatches to the event handler, this event handler will initiate the other thread which enables Worker Role to handle multiple connections.

01.private void  ExecuteClientConnection(IAsyncResult result)
02.{
03.    // Accept connection
04.    TcpListener listener = (TcpListener)result.AsyncState;
05.    TcpClient client = listener.EndAcceptTcpClient(result);
06.    WaitForClientHandler.Set();
07. 
08.    // Accepted connection
09.    Guid clientId = Guid.NewGuid();
10.    Trace.WriteLine("Accepted connection with ID " + clientId.ToString(),  "Information");
11. 
12.    // Setup reader/writer
13.    NetworkStream netStream = client.GetStream();
14.    StreamReader reader = new  StreamReader(netStream);
15.    StreamWriter writer = new  StreamWriter(netStream);
16.    writer.AutoFlush = true;
17. 
18.    // Show application
19.    string input = string.Empty;
20.    while (input != "0")
21.    {
22.        // Show menu
23.        writer.WriteLine("…");
24. 
25.        input = reader.ReadLine();
26.        writer.WriteLine();
27. 
28.        // Do something
29.        if (input == "1")
30.        {
31.            writer.WriteLine("Current date: " + DateTime.Now.ToShortDateString());
32.        }
33.        else if  (input == "2")
34.        {
35.            writer.WriteLine("Current time: " + DateTime.Now.ToShortTimeString());
36.        }
37. 
38.        writer.WriteLine();
39.    }
40. 
41.    // Done!
42.    client.Close();
43.}

The above code creates a new TcpListner and TcpClient objects and create Stream objects to interact with streams, and then there is a small logic using while loop in which it checks if the user press 1 then it prints Date and if user press 2 then it prints time and while loop terminates if the user press 0.

1.WaitForClientHandler.Set();

As we already used WaitOne command so now by using the above command we allow the main thread to accept new connections so that a new client can connect to the server.

Example Source Code

You can download from here Windows Azure Worker Role