Joydip Kanjilal
Contributor

How to work with Azure Service Bus queues in .Net

how-to
May 07, 20185 mins
Cloud ComputingMicrosoft .NETMicrosoft Azure

Take advantage of Azure Service Bus queues for scalable, cloud-based, asynchronous, and reliable messaging in your .Net applications

mail blackboard woman
Credit: Thinkstock

A queue is a data structure that works on a FIFO (first in first out) basis. Items are inserted at the end of the queue and removed from the beginning. The term “Enqueue” describes the operation that inserts data in the queue, while the term “Dequeue” denotes the removal of data from the queue.

Azure Service Bus is a scalable message fabric that provides reliable messaging as an Azure cloud service. You can use it for three different types of messaging: service relays between on-prem and cloud environments, topics for one-to-many publish/subscribe communications, and queues. This article will illustrate how we can work with Azure Service Bus queues using .Net.

Getting started with Azure Service Bus

First you will need to create a free Microsoft Azure account if you don’t have one. Then, to work with Azure Service Bus queues, we will follow these steps.

  1. Create a Service Bus namespace (if you don’t already have one) in the Azure portal
  2. Create a Service Bus queue in the Azure portal
  3. Create an application to send and receive one or more messages to the queue

Creating a Service Bus namespace in Azure

Assuming that you have created an account in Azure, follow these steps to create a Service Bus in Azure.

  1. Log into the Azure portal using your credentials
  2. Click Create a resource -> Enterprise Integration -> Service Bus
  3. Provide the name of the namespace, choose the appropriate pricing tier, and choose or provide a resource group
  4. Click Create when done

You can optionally click the “Pin to dashboard” checkbox to ensure that the resource you create can be viewed in the dashboard of your Azure account as well. To view the primary and secondary keys and connection strings, select the namespace you just created and then click on Shared Access Policies -> RootManageSharedAccessKey.

Creating and configuring a Service Bus queue in Azure

Now that the Service Bus has been created, follow these steps to create a new queue.

  1. From the Azure Dashboard, select the Service Bus you just created to open the Service Bus Namespace window
  2. From the menu at the top of the Service Bus Namespace window, click Queue to open the Create queue window
  3. In the Create queue window, enter the name of the queue and specify the values for the properties (max size, message time to live, duration, etc.) as appropriate
  4. Click Create when done

And that’s it! You have successfully created a Service Bus namespace and a Service Bus queue in Azure. You can refer to the notifications displayed in your Azure portal for the status of these operations. Once the queue has been successfully created, the message “Your queue was successfully created” will appear at the top right corner of the screen.

Programming the Azure Service Bus queue in .Net

Let’s now dig into the coding. In this section we will explore how we can send and retrieve messages to and from the Azure Service Bus queue. Create a console application project in Visual Studio and install the WindowsAzure.ServiceBus package via the NuGet Package Manager.

The following code snippet illustrates how you can send a message to a queue. Note how the SendAsync method has been used to send a message asynchronously.

public async static Task SendMessageAsync()
{
  var connectionString ="Specify the connection string here.";
  var queue ="Specify the name of the queue here.";
  var queueClient = QueueClient.CreateFromConnectionString(connectionString, queue);
  var brokeredMessage = new BrokeredMessage(“Test Message”);
  await queueClient.SendAsync(brokeredMessage);
  await queueClient.CloseAsync();
}

To retrieve messages from the queue, you can use the ReceiveAsync method as shown below.

public async static Task GetMessageAsync()
{
  var connectionString ="Specify the connection string here.";
  var queue ="Specify the name of the queue here.";
  var queueClient = QueueClient.CreateFromConnectionString(connectionString, queue);
  var brokeredMessage = await queueClient.ReceiveAsync();
  string text = brokeredMessage.GetBody<string>();
  Console.WriteLine(text);
  await queueClient.CloseAsync();
}

Note that for the sake of simplicity our GetMessageAsync method above uses Console.WriteLine to display a message retrieved from the queue at the console window. Ideally, you should return the message back to the caller method, i.e., the method from which the GetMessageAsync method would be called.

The snippet below shows how you can invoke these asynchronous methods from the Main method.

static void Main(string[] args)
        {
            SendMessageAsync().GetAwaiter().GetResult();
            GetMessageAsync().GetAwaiter().GetResult();
            Console.Read();
        }

Finally, you should ensure that the following namespaces are included in your program.

using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.ServiceBus;

Brokered messaging such as that provided by Azure Service Bus enables you to build a scalable, distributed, loosely coupled, event-driven, service-oriented architecture. In this post we have seen how we can work with an Azure Service Bus queue in .Net. I plan to discuss more advanced concepts related to Azure Service Bus in a future post here.

Joydip Kanjilal
Contributor

Joydip Kanjilal is a Microsoft Most Valuable Professional (MVP) in ASP.NET, as well as a speaker and the author of several books and articles. He received the prestigious MVP award for 2007, 2008, 2009, 2010, 2011, and 2012.

He has more than 20 years of experience in IT, with more than 16 years in Microsoft .Net and related technologies. He has been selected as MSDN Featured Developer of the Fortnight (MSDN) and as Community Credit Winner several times.

He is the author of eight books and more than 500 articles. Many of his articles have been featured at Microsoft’s Official Site on ASP.Net.

He was a speaker at the Spark IT 2010 event and at the Dr. Dobb’s Conference 2014 in Bangalore. He has also worked as a judge for the Jolt Awards at Dr. Dobb's Journal. He is a regular speaker at the SSWUG Virtual Conference, which is held twice each year.

More from this author