Worker Role In Azure Cloud Service

Introduction

In my previous article, we have seen the web role in Azure cloud service. In this article, I’m going to talk about Worker Role in Azure Cloud Service.

Content

  1. Difference between Web and worker role in Azure Cloud Service
  2. Creating a Worker Role
  3. Deploying the Worker Role

Difference between Web and Worker Role

The basic difference between the web and worker role is web role support and runs on IIS (Internet Information Service), where the worker role doesn’t support IIS.

The web role will accept the requests from the user and pass them to worker role instance for processing

Creating a worker role

In my previous article, I have explained about web role in cloud service. Now, I’m going to add the worker role project in the same existing web role project (AzureCloudServiceDemo). 

Right click on Roles ->Add ->New Worker Role Project - > Worker Role with the service bus queue.

 
                                             Figure 1  
 
Complete structure of my solution as shown below, 
 
 
                                           Figure 2  

Please, go through my previous article where I have explained about the Azure Service bus queue.

The worker role is a simple class library project, by default, it consists of the class file which inherits the RoleEntryPoint class

The file consists of three overridden methods

  1. OnStart()
    It is the first method will execute when the worker role starts, In this method I have written a code to create an Azure service bus queue if it's not available, then send a message to the queue.

  2. Run()
    This method will get fired once the Onstart is completed, I used this method to read the message from queue and send an email

  3. OnStop()
    Finally this method will get executed. In this method the service bus connection will be closed 
OnStart() in WorkerRole.cs 
  1. public override bool OnStart()  
  2.        {  
  3.            // Set the maximum number of concurrent connections   
  4.            ServicePointManager.DefaultConnectionLimit = 12;  
  5.   
  6.            // Create the queue if it does not exist already  
  7.              
  8.            string connectionString = CloudConfigurationManager.GetSetting("Microsoft.ServiceBus.ConnectionString");  
  9.            var namespaceManager = NamespaceManager.CreateFromConnectionString(connectionString);  
  10.            if (!namespaceManager.QueueExists(QueueName))  
  11.            {  
  12.                namespaceManager.CreateQueue(QueueName);  
  13.            }  
  14.   
  15.            // Initialize the connection to Service Bus Queue  
  16.            Client = QueueClient.CreateFromConnectionString(connectionString, QueueName);  
  17.            BrokeredMessage message = new BrokeredMessage("Am from Azure Service bus Queue as a worker roles");  
  18.            Client.SendAsync(message);  
  19.            return base.OnStart();  
  20.        }  
Run() in WorkerRole.cs 
  1. public override void Run()  
  2.        {  
  3.           
  4.            string connectionString = CloudConfigurationManager.GetSetting("Microsoft.ServiceBus.ConnectionString");  
  5.            var namespaceManager = NamespaceManager.CreateFromConnectionString(connectionString);  
  6.            Client = QueueClient.CreateFromConnectionString(connectionString, QueueName);  
  7.            BrokeredMessage message = Client.Receive();  
  8.            string body = message.GetBody<string>();  
  9.   
  10.            using (MailMessage mm = new MailMessage("from address""to address "))  
  11.            {  
  12.                mm.Subject = "Testing Worker Role";  
  13.                mm.Body = body;  
  14.                mm.IsBodyHtml = false;  
  15.                SmtpClient smtp = new SmtpClient();  
  16.                smtp.Host = "smtp.gmail.com";  
  17.                smtp.EnableSsl = true;  
  18.                NetworkCredential NetworkCred = new NetworkCredential("user name""password");  
  19.                smtp.UseDefaultCredentials = true;  
  20.                smtp.Credentials = NetworkCred;  
  21.                smtp.Port = 587;  
  22.                smtp.Send(mm);  
  23.            }  
  24.            message.Complete();  
  25.            message.Abandon();  
  26.   
  27.        }  
WorkerRole.cs
  1. public class WorkerRole : RoleEntryPoint  
  2.    {  
  3.        // The name of your queue  
  4.        const string QueueName = "ProcessingQueue";  
  5.   
  6.        // QueueClient is thread-safe. Recommended that you cache   
  7.        // rather than recreating it on every request  
  8.        QueueClient Client;  
  9.        ManualResetEvent CompletedEvent = new ManualResetEvent(false);  
  10.   
  11.        public override void Run()  
  12.        {  
  13.           
  14.            string connectionString = CloudConfigurationManager.GetSetting("Microsoft.ServiceBus.ConnectionString");  
  15.            var namespaceManager = NamespaceManager.CreateFromConnectionString(connectionString);  
  16.            Client = QueueClient.CreateFromConnectionString(connectionString, QueueName);  
  17.            BrokeredMessage message = Client.Receive();  
  18.            string body = message.GetBody<string>();  
  19.   
  20.            using (MailMessage mm = new MailMessage("from address""to address "))  
  21.            {  
  22.                mm.Subject = "Testing Worker Role";  
  23.                mm.Body = body;  
  24.                mm.IsBodyHtml = false;  
  25.                SmtpClient smtp = new SmtpClient();  
  26.                smtp.Host = "smtp.gmail.com";  
  27.                smtp.EnableSsl = true;  
  28.                NetworkCredential NetworkCred = new NetworkCredential("user name""password");  
  29.                smtp.UseDefaultCredentials = true;  
  30.                smtp.Credentials = NetworkCred;  
  31.                smtp.Port = 587;  
  32.                smtp.Send(mm);  
  33.            }  
  34.            message.Complete();  
  35.            message.Abandon();  
  36.   
  37.        }  
  38.   
  39.        public override bool OnStart()  
  40.        {  
  41.            // Set the maximum number of concurrent connections   
  42.            ServicePointManager.DefaultConnectionLimit = 12;  
  43.   
  44.            // Create the queue if it does not exist already  
  45.              
  46.            string connectionString = CloudConfigurationManager.GetSetting("Microsoft.ServiceBus.ConnectionString");  
  47.            var namespaceManager = NamespaceManager.CreateFromConnectionString(connectionString);  
  48.            if (!namespaceManager.QueueExists(QueueName))  
  49.            {  
  50.                namespaceManager.CreateQueue(QueueName);  
  51.            }  
  52.   
  53.            // Initialize the connection to Service Bus Queue  
  54.            Client = QueueClient.CreateFromConnectionString(connectionString, QueueName);  
  55.            BrokeredMessage message = new BrokeredMessage("Am from Azure Service bus Queue as a worker roles");  
  56.            Client.SendAsync(message);  
  57.            return base.OnStart();  
  58.        }  
  59.   
  60.        public override void OnStop()  
  61.        {  
  62.            // Close the connection to Service Bus Queue  
  63.            Client.Close();  
  64.            CompletedEvent.Set();  
  65.            base.OnStop();  
  66.        }  
  67.    }   
Let's run the application. You can see the Azure service bus queue is created for respective namespaces, and the message in the queue will be sent as an email through the run module in worker role. 
 
 
                   Figure 3: New queue(Processing queue) is created 
 
 
                Figure 4: Message send as an email  
 
Deploy Worker Role 
 
Right click on the Cloud service project -> publish, the Microsoft Azure publish setting window will be opened, configure it (which is already discussed in my previous article).

 
                                               Figure 5 
 
Once the publishing is done, you can check in the portal that the worker role will be deployed in the respective cloud service, as shown in the below figure. 
 
 
                                              Figure 6  
 
I hope you have enjoyed this article. Your valuable feedback, questions, or comments about this article are always welcome.