Getting Started with Azure Service Bus Queues & ASP.NET Core - Part 1
Tags: azure, dotnet, serverless, beginners
Published: 2020-07-17 14:37:30

In this article, we are going to discuss to about [Microsoft Azure Service Bus](https://docs.microsoft.com/en-us/azure/service-bus-messaging/service-bus-messaging-overview) Queues. First, we will see what is Azure Service Bus and then discuss about queues. We are also going to build a simple application to send and receive message in queues using ASP.NET Core. So let’s grab a cup of coffee and start learning.

# What is Azure Service Bus

Azure Service Bus is message broker service which is hosted on Azure platform and it provides functionality to publish messages to various application and also decouple the applications.

According to Microsoft [documentation](https://docs.microsoft.com/en-us/azure/service-bus-messaging/service-bus-messaging-overview):
> Microsoft Azure Service Bus is a fully managed enterprise integration message broker. Service Bus can decouple applications and services. Service Bus offers a reliable and secure platform for asynchronous transfer of data and state.

> Data is transferred between different applications and services using messages. A message is in binary format and can contain JSON, XML, or just text.

Microsoft service bus comes in different flavors:
* Queues
* Topic (we will cover this in next articles) 

# Azure Service Bus: Queues

Queues follow First-In-First-Out (FIFO) pattern. Queues provide the one-way transport like the sender is going to send message in the queue and the receiver would collect messages from queue. In queues, there is a 1:1 relationship between the sender and receiver. Messages are present in queue until the receiver process and complete the messages.

![queue-dig](https://dev-to-uploads.s3.amazonaws.com/i/tivotkjmcunluvcg0fnm.PNG)


The queue contains a secondary sub-queue, called a dead-letter queue (DLQ). Whenever we create a queue DLQ is automatically added in our main queue. When the messages are not delivered to the receiver or can not be processed by the receiver then such messages are pushed to DLQ.

Now we have discussed enough regarding Queues so let's create queues in Azure and build a simple application to send and receive messages from the queue.

# Creating a simple application to send and receive messages from the queue.

#### Prerequisites
* [Azure](https://portal.azure.com) account(If you don't have an Azure subscription, [create a free trial account](https://azure.microsoft.com/free).)
* Basic knowledge of Asp.net Core Web API

#### Overview of application
We will be creating a simple application which consists of 3 parts:
* Create Azure Service Bus Queue using Azure Portal(Covering in this article)
* Create Web API to push the message into Queue(Covering in this article)
* Create a Background Service to receive a message from Queue(Covered in next article)

![App Structure](https://dev-to-uploads.s3.amazonaws.com/i/h6v77l1g5vu74ijwcahz.png)

## Creating Azure Service Bus Queue using Azure Portal

* Login to [Azure](https://portal.azure.com) and click on **Create a resource** button.
* In search box type *service bus* and select it.

![service-bus-new](https://dev-to-uploads.s3.amazonaws.com/i/kra38pensuduu2jvca3j.PNG)

* Click on **Create** button. You will see the Create Namespace page.

![create-namespace-page](https://dev-to-uploads.s3.amazonaws.com/i/qvy1g6osxg7w5j3ygkj5.PNG)

* Azure has Resource Groups(RG) which acts as a container for your resources. So now we are going to create a Service bus resource then first we need to create Resource Group. If you have already created RG then you can use the same here. Under Resource group click on Create New button and give unique RG name.

![new-rg](https://dev-to-uploads.s3.amazonaws.com/i/yd7l8uqs4zi1hcre4nwa.PNG)

* Now we have to specify the Namespace name. A namespace is a container for all messaging components. Multiple queues and topics can be in a single namespace, and namespaces often serve as application containers.
* Select the location.
* Select pricing tier. Azure provides 3 pricing tiers:
   1 Basic
   2 Standard
   3 Premium

![pricing-tier](https://dev-to-uploads.s3.amazonaws.com/i/b4sao64l9xq62h9jek8b.PNG)

* We have filled all details the click on **Review + create** button.

![all-filled](https://dev-to-uploads.s3.amazonaws.com/i/7ds23czw9m25sug8nics.PNG)

* Review everything added property and finally click on **Create** button.

![final-create](https://dev-to-uploads.s3.amazonaws.com/i/ex28y2j2i4rl3mp3rlf1.PNG) 

* Creating resources will take time.

![deployment-processing](https://dev-to-uploads.s3.amazonaws.com/i/mhzy7o1p5v4mj6y8lo0h.PNG)
   
* Now our order queue is created successfully. 

![order-queue](https://dev-to-uploads.s3.amazonaws.com/i/6xkqn5wlisnf3uusosfe.PNG)
 
* Go to the Queues section in the left panel and click on Queue and give a unique name for queue and click on the Create button.

![create-queue](https://dev-to-uploads.s3.amazonaws.com/i/qs1flm359yzmm66z967m.PNG)


## Create Web API to push the message into Queue

#### *Prerequisites*
* Visual Studio 19(if you are using .NET Core 3.1)
* .NET Core 3.1 SDK installed

First thing is to create a new ASP.NET Core Web API project. For those who are new to ASP.NET Core, I have listed down the steps to create a new Web API project.

* Open Visual Studio and click on File -> New -> Project. Then select **ASP.NET Core Web Application** and click on the Next button.
* Give the project name and click on **Create** button.
* After that select **API** and click on **Create** button.
* So now your ASP.NET Core Web API project is setup.

* First we need to install Azure Service Bus NuGet package:

![asb-nuget] (https://dev-to-uploads.s3.amazonaws.com/i/kjkdpbbda8nbbl7tgz2a.PNG)

* Create a new class called *Order.cs* and add below properties:
```
namespace Order.Web.API
{
    public class Order
    {
        public int Id { get; set; }
        public int Quantity { get; set; }
        public decimal Price { get; set; }
    }
}

```

* To interact with Azure Service Bus *Microsoft.Azure.ServiceBus* package provides called QueueClient which accepts queue connection string and queue name as input and returns the QueueClient object. First, we grab the connection string of Queue from Azure Portal. So open the queue and click on *Shared access policies* then select RootManageSharedAccessKey and copy it into appsettings.json file.

![connection-string](https://dev-to-uploads.s3.amazonaws.com/i/f99cq1x0939njdwzlvv1.PNG)

appsettings.json
```
{
  "QueueConnectionString": "<replace your RootManageSharedAccessKey here>",
  "QueueName":  "order-queue",
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"
}

```
* Create a new controller called *OrdersController* and add below code to push message into queue:

```
using System;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.ServiceBus;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;

namespace Order.Web.Api.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class OrdersController : ControllerBase
    {
        private readonly IConfiguration _configuration;

        public OrdersController(IConfiguration configuration)
        {
            _configuration = configuration;
        }

        [HttpPost]
        public async Task<IActionResult> CreateOrderAsync([FromBody] Order order)
        {
            IQueueClient queueClient = new QueueClient(_configuration["QueueConnectionString"], _configuration["QueueName"]);
            var orderJSON = JsonConvert.SerializeObject(order);
            var orderMessage = new Message(Encoding.UTF8.GetBytes(orderJSON))
            {
                MessageId = Guid.NewGuid().ToString(),
                ContentType = "application/json"
            };
            await queueClient.SendAsync(orderMessage).ConfigureAwait(false);

            return Ok("Create order message has been successfully pushed to queue");
        }
    }
}

```
* So we have created QueueClient object and then we created Message. We used SendAsync() method to push message to the queue.

* We are testing this using postman. Run the app and hit post API to push order into Queue.

![postman](https://dev-to-uploads.s3.amazonaws.com/i/tukkc0gsvhzdlmgs0w1r.PNG)

* After a successful POST call let's go to Azure Portal and see if the message is pushed to the queue. So we have 1 active message in the queue.

![queue-message](https://dev-to-uploads.s3.amazonaws.com/i/nrg8ilmx8804l9tkkrnt.PNG)

# Conclusion

In this Part 1 of the Azure Service Bus Queue series, we have learned how to create a queue through Azure Portal and also we have created a Web API that pushes a message to the Queue. In Part 2 we will create a Background Service which will read messages from the Queue. 

I really hope that you enjoyed this article, share it with friends and please do not hesitate to send me your thoughts or comments.

You can follow me on twitter [@sumitkharche01](https://twitter.com/sumitkharche01)

Happy Coding!!