Azure Service Bus And Queue Implementation Using C#

The azure service bus is a fully managed message integration broker. If two applications want to communicate with each other with less dependency, then the 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 the two applications have less dependency on each other. Azure service message is reliable and durable as well. You can send a small text message or a complex message (object) to the message queue.

What we are going to cover.

  • How to create a 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 a service bus and queue in Azure (short intro as it can be viewed in Azure sites)

  • Log in to the Azure portal and navigate to the service bus.
  • Now click on the add button to create a namespace.

You can choose a resource group or create a new resource group. Add the namespace and the location at your 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 created 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 a shared access policy for the 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 deletion 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 the Azure service bus queue using the 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 to demonstrate 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 to the console application.

Entry point of the application (of course the main method in Program class).

Code for Program.cs

using System;
namespace AzureServiceBusApp
{
    class Program
    {
        static void Main(string[] args)
        {
            Program program = new Program();
            program.GetMessageFromQueue();
            program.PutMessageInQueue();
        }

        public void PutMessageInQueue()
        {
            ServiceBusSender sender = new ServiceBusSender();
            do
            {
                Console.WriteLine("Please type message to send in azure and press enter: ");
                var strMessage = Console.ReadLine();
                if (!string.IsNullOrWhiteSpace(strMessage))
                {
                    sender.SendMessage(strMessage);
                    Console.WriteLine("Message sent successfully");
                }
                else
                {
                    Console.WriteLine("Empty Message. Please enter some text");
                }
            }
            while (Console.ReadKey(true).Key != ConsoleKey.End);
        }
        public void GetMessageFromQueue()
        {
            ServiceBusReceiver receiver = new ServiceBusReceiver();
            receiver.Listener();
        }
    }
}

The main method (entry point) calls two methods; e.g. GetMessageFromQueue() and PutMessageInQueue().

GetMessageFromQueue() method creates the ServiceBusReceiver object and invokes the Listener method.

PutMessageInQueue() creates the ServiceBusSender object and invokes the SendMessage method.

Inside putMessageInQueue() there is do..while loop. It is needed to prompt the user to type the message that he wants to send to the Queue. After sending the message in the queue, the user can terminate the program by pressing the END key or send another message by pressing the ENTRY key.

ServiceBusSender class

It will take the text message prepare the payload and send it to the Queue. Note that, it will be having Azure shared access policy.

Code for ServiceBusSender.cs

using Microsoft.Azure.ServiceBus;
using System;
using System.Text;

namespace AzureServiceBusApp
{
    public class ServiceBusSender
    {
        string QueueAccessKey = "—- Get key from azure queue->Shared access key--";

        public void SendMessage(string message)
        {
            ServiceBusConnectionStringBuilder conStr;
            QueueClient client;
            try
            {
                conStr = new ServiceBusConnectionStringBuilder(QueueAccessKey);
                client = new QueueClient(conStr);
                Message msg = new Message();
                msg.Body = Encoding.UTF8.GetBytes(message);
                Console.WriteLine("Please wait....message sending operation in progress.");
                client.SendAsync(msg).Wait();
            }
            catch (Exception exe)
            {
                Console.WriteLine("{0}", exe.Message);
                Console.WriteLine("Please restart application");
            }
        }
    }
}

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

using Microsoft.Azure.ServiceBus;
using System;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace AzureServiceBusApp
{
    public class ServiceBusReceiver
    {
        string QueueAccessKey = "--- Get key from azure queue ->Shared access key--";
        
        public void Listener()
        {
            ServiceBusConnectionStringBuilder conStr;
            QueueClient client;
            
            try
            {
                conStr = new ServiceBusConnectionStringBuilder(QueueAccessKey);
                client = new QueueClient(conStr, ReceiveMode.ReceiveAndDelete, RetryPolicy.Default);
                
                var messageHandler = new MessageHandlerOptions(ListenerExceptionHandler)
                {
                    MaxConcurrentCalls = 1,
                    AutoComplete = false
                };
                
                client.RegisterMessageHandler(ReceiveMessageFromQ, messageHandler);
            }
            catch (Exception exe)
            {
                Console.WriteLine("{0}", exe.Message);
                Console.WriteLine("Please restart application");
            }
        }  
        public async Task ReceiveMessageFromQ(Message message, CancellationToken token)
        {
            string result = Encoding.UTF8.GetString(message.Body);
            Console.WriteLine("Message received from Queue = {0}", result);
            
            await Task.CompletedTask;
            
            Console.WriteLine("---- Task completed ----");
            Console.WriteLine();
            Console.WriteLine("Please press END key to terminate.");
            Console.WriteLine("Please press Entry key to type and send next message.");
        } 
        public Task ListenerExceptionHandler(ExceptionReceivedEventArgs exceptionReceivedEventArgs)
        {
            Console.WriteLine("{0}", exceptionReceivedEventArgs.Exception);
            return Task.CompletedTask;
        }
    }
}

How to run the application with this code?
 

Option 1

Prerequisite

Visual Studio 2017 and .net core 2.1(should have a higher version as well). Update your “Shared access key” in the sender and receiver class.

  • Open Visual Studio and click on new -> project.
  • Select .net core from the 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 the default Program.cs file. Now from Nuget package manager, search Microsoft.Azure.ServiceBus and install from the selected project.
  • Add a new .cs file to the project and name it ServiceBusSender.cs
  • Copy the content from the section “Code for ServiceBusSender.cs” and paste it as the ServiceBusSender.cs file
  • Add a new .cs file to the project and name it ServiceBusReceiver.cs
  • Copy the content from the section “Code for ServiceBusReceiver.cs” and paste it as the ServiceBusReceiver.cs file
  • Copy the content of the main entry point (only the c# code) and paste it into the Program.cs file.

Build the solution and run the application.

Option 2

Download the zip file from here and unzip it in your local system. Open the solution file, build the project, and run the application.

Thanks, and happy coding.


Similar Articles