Azure Service Bus And Queue Implementation Using C#

Azure service bus is a fully managed message integration broker. If two applications want to communicate with each other with less dependency, then Azure service bus can used to send and receive the messages between them. It can provide your application decoupling and asynchronization with great flexibility as two applications have less dependency with each other. Azure service message is reliable and durable as well. You can send small text message or a complex message (object) to the message queue.
 
What we are going to cover,
  • How to create service bus and queue in Azure.
  • How to send/receive messages from Azure service bus queue using C# code.
  • How to run applications with this code.
How to create service bus and queue in Azure (short intro as it can be viewed in Azure sites)
  • Login to the azure portal and navigate to the service bus.
  • Now click on add button to create namespace.
You can choose resource group or create new resource group. Add the namespace and the location as per you convenience.
 
Now there is an option of Pricing Tier. For this application I have used Basic for learning purposes.
 
And fill in some other details in the tab and create the namespace. It will take some time and now we are ready to create a Queue.
 
Now open the newly create service bus namespace and create the queue.
 
After creating the namespace and the queue we need to create the claims and policies for the service bus namespace. Create shared access policy for service bus namespace.
 
There are 3 types of  claims in shared access policy and one can apply all three claims to one policy or combine any two. But as per the application needs, I suggest you create a policy based on the responsibilities.
 
Claims
  • Managed- Queue creation and delete can be done with this claim
  • Send – Only Message sending can be done with this claim
  • Listen – Only Message received can be done using this claim
How to send/receive messages from Azure service bus queue using C# code:
 
Generally, in ideal situations, one application (sender) is responsible for sending messages to the queue and another application (receiver) listens to the queue. If any message is available in the queue it reads the message from the queue and marks/removesit. Microservices applications are the best suitable solution for the service bus.
 
In the article, I have used .net core(2.1) and C# code for demonstrating the Azure service bus console application. I am using Visual Studio 2017. Only sending and receiving messages will be the part of this article, the creation of queue using C# code is not included.
 
There are 3 parts in the console application.
 
Entry point of the application (of-course the main method in Program class)
 
Code for Program.cs,
  1. using System;  
  2. namespace AzureServiceBusApp {  
  3.     class Program {  
  4.         static void Main(string[] args) {  
  5.             Program program = new Program();  
  6.             program.GetMessageFromQueue();  
  7.             program.PutMessageInQueue();  
  8.         }  
  9.         public void PutMessageInQueue() {  
  10.             ServiceBusSender sender = new ServiceBusSender();  
  11.             do {  
  12.                 Console.WriteLine("Please type message to send in azure and press enter: ");  
  13.                 var strMessage = Console.ReadLine();  
  14.                 if (!string.IsNullOrWhiteSpace(strMessage)) {  
  15.                     sender.SendMessage(strMessage);  
  16.                     Console.WriteLine("Message send successfully");  
  17.                 } else {  
  18.                     Console.WriteLine("Empty Message. Please enter some text");  
  19.                 }  
  20.             }  
  21.             while (Console.ReadKey(true).Key != ConsoleKey.End);  
  22.         }  
  23.         public void GetMessageFromQueue() {  
  24.             ServiceBusReceiver receiver = new ServiceBusReceiver();  
  25.             receiver.Listener();  
  26.         }  
  27.     }  
  28. }  
Main method (entry point) calls two methods; e.g GetMessageFromQueue() and PutMessageInQueue().
 
GetMessageFromQueue() method creates the ServiceBusReceiver object and invokes Listener method.
 
PutMessageInQueue() creates the ServiceBusSender object and invokes SendMessage method.
 
Inside putMessageInQueue() there is do..while loop. It is needed to prompt user to type the message which he wants to send to the Queue. After sending the message in the queue, user can terminate the program by pressing the END key or send another message by pressing ENTRY key.
 

ServiceBusSender class

 
It will take the text message and prepare the payload and send it to the Queue. Note that, it will be having Azure shared access policy.
 
Code for ServiceBusSender.cs,
  1. using Microsoft.Azure.ServiceBus;  
  2. using System;  
  3. using System.Text;  
  4. namespace AzureServiceBusApp {  
  5.     public class ServiceBusSender {  
  6.         string QueueAccessKey = "—- Get key from azure queue->Shared access key--";  
  7.         public void SendMessage(string messgae) {  
  8.             ServiceBusConnectionStringBuilder conStr;  
  9.             QueueClient client;  
  10.             try {  
  11.                 conStr = new ServiceBusConnectionStringBuilder(QueueAccessKey);  
  12.                 client = new QueueClient(conStr);  
  13.                 Message msg = new Message();  
  14.                 msg.Body = Encoding.UTF8.GetBytes(messgae);  
  15.                 Console.WriteLine("Please wait....message sending operation in progress.");  
  16.                 client.SendAsync(msg).Wait();  
  17.             } catch (Exception exe) {  
  18.                 Console.WriteLine("{0}", exe.Message);  
  19.                 Console.WriteLine("Please restart application ");  
  20.             }  
  21.         }  
  22.     }  
  23. }  

ServiceBusReceiver class

 
It will listen to the queue and trigger the message handler method if there is any message available in the Queue. It will have Azure shared access policy.
 
Code ServiceBusReceiver.cs,
  1. using Microsoft.Azure.ServiceBus;  
  2. using System;  
  3. using System.Text;  
  4. using System.Threading;  
  5. using System.Threading.Tasks;  
  6. namespace AzureServiceBusApp {  
  7.     public class ServiceBusReceiver {  
  8.         string QueueAccessKey = "—- Get key from azure queue ->Shared access key--";  
  9.         public void Listener() {  
  10.             ServiceBusConnectionStringBuilder conStr;  
  11.             QueueClient client;  
  12.             try {  
  13.                 conStr = new ServiceBusConnectionStringBuilder(QueueAccessKey);  
  14.                 client = new QueueClient(conStr, ReceiveMode.ReceiveAndDelete, RetryPolicy.Default);  
  15.                 var messageHandler = new MessageHandlerOptions(ListenerExceptionHandler) {  
  16.                     MaxConcurrentCalls = 1,  
  17.                         AutoComplete = false  
  18.                 };  
  19.                 client.RegisterMessageHandler(ReceiveMessageFromQ, messageHandler);  
  20.             } catch (Exception exe) {  
  21.                 Console.WriteLine("{0}", exe.Message);  
  22.                 Console.WriteLine("Please restart application ");  
  23.             }  
  24.         }  
  25.         public async Task ReceiveMessageFromQ(Message message, CancellationToken token) {  
  26.             string result = Encoding.UTF8.GetString(message.Body);  
  27.             Console.WriteLine("Message received from Queue = {0}", result);  
  28.             await Task.CompletedTask;  
  29.             Console.WriteLine("---- Task completed----");  
  30.             Console.WriteLine();  
  31.             Console.WriteLine("Please press END key to terminate.");  
  32.             Console.WriteLine("Please press Entry key to type and send next message.");  
  33.         }  
  34.         public Task ListenerExceptionHandler(ExceptionReceivedEventArgs exceptionReceivedEventArgs) {  
  35.             Console.WriteLine("{0}", exceptionReceivedEventArgs.Exception);  
  36.             return Task.CompletedTask;  
  37.         }  
  38.     }  
  39. }  

How to run application with this code

 
Option -1
 
Prerequisite- Visual Studio 2017 and .net core 2.1(should have higher version as well). Update your “Shared access key” in sender and receiver class.
  • Open visual studio and click on new -> project.
  • Select .net core from left end and select the Console App (.net core) template.
  • Mention the path where the solution will be created and click on the ok button.

    Now a new console app project will be created with default Program.cs file. Now from Nuget package manager, search Microsoft.Azure.ServiceBus and install from the selected project.

  • Add new .cs file to the project and name it as ServiceBusSender.cs
  • Copy the content from section “Code for ServiceBusSender.cs” and paste in as ServiceBusSender.cs file
  • Add new .cs file to the project and name it as ServiceBusReceiver.cs
  • Copy the content from section “Code for ServiceBusReceiver.cs” and paste in as ServiceBusReceiver.cs file
  • Copy the content of main entry point (only c# code) and paste it in the Program.cs file.
Build the solution and run the application.
 
Option -2
 
Download the zip file from here and unzip in your local system. Open the solution file, build the project, and run the application.
 
Thanks, and happy coding 😊😊😊😊