Creating Azure Service Bus Queues And Sending Messages To Queues

Service Bus

The reason behind the use of service bus is to decouple applications and services. As we need to decouple applications and services, the data can be transferred between different applications and services using messages. The messages can be sent to the queue in the service bus.

Creating Service Bus Queue

Most of you might aware how to create a service bus queue in  Azure, but let me review.
Way 1
Login tothe Azure portal and create a service bus, namespace. Once that is done, you can see the queues and topics in the left hand side. Once we click on queue, we can click on Add and create a queue from Azure portal.
Creating Azure Service Bus Queues And Sending Messages To Queues
Way 2
If we have service Bus explorer, we can login into the service bus explorer with the connection string of service bus and right click on the queue and create the queue. We can have the settings enabled for the queue.
Creating Azure Service Bus Queues And Sending Messages To Queues
Some of the useful settings are:

Enable Sessions

This allows a guarantee of processing the messages in a sequential manner. This follows the pattern of FIFO.

Enabled Dead Lettering

This allows the messages to be in deadletter if the receiver fails to receive the messages in time. The message will not expire in deadletter until and unless it is viewed.
Configuring the Service Bus queue in the development environment.
Install the Microsoft.Azure.ServiceBus nuget package to the project where you are setting up the message queue.
First let's create a class for configuring the QueueClient and have a generic method for sending the message to the queue.
  1. using Azure.ServiceBus;  
  2. using Microsoft.Azure.ServiceBus;  
  3. using System;  
  4. using System.Collections.Generic;  
  5. using System.Text;  
  6. namespace AzureFunctionsUnitTesting.Service_Bus {  
  7.     public class QueueSender: IQueueSender {  
  8.         static Dictionary < string, IQueueClient > _queueClients;  
  9.         public QueueSender(string connectionString, List < Queue > queues) {  
  10.             _queueClients = new Dictionary < string, IQueueClient > ();  
  11.             if (!string.IsNullOrEmpty(connectionString)) {  
  12.                 foreach(Queue queue in queues) {  
  13.                     string queueId = queue.Id;  
  14.                     string queueName = queue.Name;  
  15.                     _queueClients.Add(queueId, new QueueClient(connectionString, queueName));  
  16.                 }  
  17.             };  
  18.         }  
  19.         public async void SendMessageAsync(string queueName, string messageItem, string messageLabel = null, Dictionary < stringobject > messageProperties = null) {  
  20.             try {  
  21.                 Message message = BuildMessage(messageItem, messageLabel, messageProperties);  
  22.                 await _queueClients[queueName].SendAsync(message);  
  23.             } catch (Exception ex) {  
  24.                 throw ex;  
  25.             }  
  26.         }  
  27.         private Message BuildMessage(string messageItem, string messageLabel, Dictionary < stringobject > messageProperties) {  
  28.             Message message = new Message(Encoding.UTF8.GetBytes(messageItem));  
  29.             message.UserProperties["TimeStampUTC"] = DateTime.UtcNow;  
  30.             message.Label = messageLabel;  
  31.             if (messageProperties != null) {  
  32.                 foreach(var messageProperty in messageProperties) {  
  33.                     message.UserProperties[messageProperty.Key] = messageProperty.Value;  
  34.                 }  
  35.             }  
  36.             return message;  
  37.         }  
  38.     }  
  39. }  
I have configured the QueueClient in the constructor so that it will be loaded when ever we inject the class through dependency injection.
I have created a method (BuildMessage) to build the message which will be sent to the queue. Message is a class of Azure service bus Nugets.
Once the message is built, we will send the message through the queue client we have injected by creating a Method(SendMessageAsync). The queue client will take care of sending the message to the service bus queue.

Calling the Configured Queue Sender for sending our custom Message

I have created a class and injected the Queue sender interface. I have created a method and will be calling the sendMessageAsync Method to send the message.
  1. using AzureFunctionsUnitTesting.Interfaces;  
  2. using AzureFunctionsUnitTesting.Service_Bus;  
  3. using Microsoft.Azure.ServiceBus;  
  4. namespace AzureFunctionsUnitTesting {  
  5.     public class MessageQueueSender: IMessageQueueSender {  
  6.         private readonly IQueueSender _queueSender;  
  7.         public MessageQueueSender(IQueueSender queueSender) {  
  8.             _queueSender = queueSender;  
  9.         }  
  10.         public void SendMessageToQueue() {  
  11.             Message message = new Message();  
  12.             message.SessionId = "session1";  
  13.             string queueName = "testqueue";  
  14.             string content = "Hello Service Bus Queue";  
  15.             _queueSender.SendMessageAsync(queueName, content);  
  16.         }  
  17.     }  
  18. }  

Unit Testing for Sending Message to Service Bus Queue

We can test if the configuration for setting up the service bus queue is correct or not by creating a unit test case.
I have created a unit test case where I will be mocking up all the required configuration and will be calling the SendMessageToQueue method and checking the count of messages in the queue as assertion.
  1. using AzureFunctionsUnitTesting.Service_Bus;  
  2. using Microsoft.VisualStudio.TestTools.UnitTesting;  
  3. using Moq;  
  4. using System.Collections.Generic;  
  5. namespace AzureFunctionsUnitTesting.Tests {  
  6.     [TestClass]  
  7.     public class MessageQueueSenderTests {  
  8.         public readonly Mock < IQueueSender > _queueSender;  
  9.         public List < string > _queueMessages;  
  10.         public MessageQueueSenderTests() {  
  11.                 _queueSender = new Mock < IQueueSender > ();  
  12.                 _queueMessages = new List < string > ();  
  13.                 _queueSender.Setup(x => x.SendMessageAsync(It.IsAny < string > (), It.IsAny < string > (), It.IsAny < string > (), It.IsAny < Dictionary < stringobject >> ())).Callback < stringstringstring, Dictionary < stringobject >> (async (a, b, d, e) => {  
  14.                     _queueMessages.Add($ "{a}");  
  15.                 });  
  16.             }  
  17.             [TestInitialize()]  
  18.         public virtual void Initialise() {}  
  19.             [TestMethod]  
  20.         public void SendMessageToQueue() {  
  21.             MessageQueueSender messageQueueSender = new MessageQueueSender(_queueSender.Object);  
  22.             messageQueueSender.SendMessageToQueue("testservicebus""Hello ServiceBus""sessionId1");  
  23.             //Check if message is delivered to queue  
  24.             Assert.AreEqual(1, _queueMessages.Count, "Message sending failed");  
  25.         }  
  26.     }  
  27. }  
I hope this article is helpful for everyone and please post your questions with anything related to service bus queue and topics. I have attached the solution file for reference.

Recommended Ebook

The Developer’s Guide to Microsoft Azure - Second Edition

Download Now!
Similar Articles