Usama Arshad

 © 2023 itsusamaarshad

Send and receive message from a Azure Service Bus queue by using .NET Core.

Recent Post​

What is Azure Service Bus.

  • Azure Service Bus is a cloud-based messaging service provided by Microsoft Azure.
  • It is a fully managed message broker that allows you to decouple the components of your distributed applications. It provides reliable messaging and allows for the exchange of messages between applications or services that may be running on different platforms, devices, or networks.
  • Azure Service Bus supports several messaging patterns, including point-to-point messaging, publish/subscribe messaging, and request/response messaging. It provides a variety of features such as message queuing, message filtering, and message routing, to ensure that messages are delivered reliably and efficiently.

Send and receive message from a Service Bus queue by using .NET Core 6.

 

1. Open Azure Portal and search Service Bus.

2. Create Azure Service bus namespace.

3. Select queues from side menu and create a new queue.

4. First, create a new ASP.NET Core Web API project in Visual Studio 2022 to send a message.

5. Install the Microsoft.Azure.ServiceBus package by running the following command in the Package Manager Console.

Install-Package Microsoft.Azure.ServiceBus

6. Create a Product Controller and paste the following below code.

using AzureServiceBusSender.Models;
using AzureServiceBusSender.Services;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.ServiceBus;

namespace AzureServiceBusSender.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ProductsController : ControllerBase
    {
        private readonly ServiceBusManager _serviceBusManager;
        private readonly string _queueName = "Your Queue Name Here.";

        public ProductsController(ServiceBusManager serviceBusManager)
        {
            _serviceBusManager = serviceBusManager;
        }

        [HttpPost]
        public async Task<IActionResult> SendMessage([FromBody] Product message)
        {
            try
            {
                await _serviceBusManager.SendMessageToQueue(_queueName, message);
                return Ok();
            }
            catch (Exception ex)
            {
                return StatusCode(500, ex.Message);
            }
        }
    }
}

7. Create a Product.cs in Model folder and paste below code .

namespace AzureServiceBusSender.Models
{
    public class Product
    {
        public int Id { get; set; }
        public string Name { get; set; } = string.Empty;
        public string Description { get; set; } = string.Empty;
        public string Category { get; set; } = string.Empty;
        public string CategoryName { get; set; } = string.Empty;
        public string CategoryDescription { get; set; } = string.Empty;
    }
}

8. Create a ServiceManger Class and paste below code.

using Microsoft.Azure.ServiceBus;

namespace AzureServiceBusSender.Services
{
    public class ServiceBusManager
    {
        private readonly string _connectionString;

        public ServiceBusManager(string connectionString)
        {
            _connectionString = connectionString;
        }

        public async Task SendMessageToQueue<T>(string queueName, T message)
        {
            var queueClient = new QueueClient(_connectionString, queueName);
            var encodedMessage = new Message(SerializeMessage(message));
            await queueClient.SendAsync(encodedMessage);
            await queueClient.CloseAsync();
        }

        private byte[] SerializeMessage<T>(T message)
        {
            // Replace with your preferred serialization method
            // For example, using Newtonsoft.Json:
            var serializedMessage = Newtonsoft.Json.JsonConvert.SerializeObject(message);
            return System.Text.Encoding.UTF8.GetBytes(serializedMessage);
        }
    }
}

9. Paste below code in appsetting.json file.

"ConnectionStrings": {
    "ServiceBus": "Your connection string"
  }

10. Inject ServiceManger class in Program.cs file.

var serviceBusConnectionString = builder.Configuration.GetConnectionString("ServiceBus");
builder.Services.AddSingleton(new ServiceBusManager(serviceBusConnectionString));

Create a console application in visual studio 2022 to receive message.

11. Paste below code in program.cs File

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

namespace AzureServiceBusSender
{
    class Program
    {
        const string ServiceBusConnectionString = "Your Connection String";
        const string QueueName = "Your Queue Name";
        static IQueueClient queueClient;
        static async Task Main(string[] args)
        {
            queueClient = new QueueClient(ServiceBusConnectionString, QueueName);

            RegisterOnMessageHandlerAndReceiveMessages();

            Console.ReadKey();

            await queueClient.CloseAsync();
        }
        static void RegisterOnMessageHandlerAndReceiveMessages()
        {
            var messageHandlerOptions = new MessageHandlerOptions(ExceptionReceivedHandler)
            {
                MaxConcurrentCalls = 1,
                AutoComplete = false
            };
            queueClient.RegisterMessageHandler(ProcessMessagesAsync, messageHandlerOptions);
        }
        static async Task ProcessMessagesAsync(Message message, CancellationToken token)
        {
            Console.WriteLine($"Received message: SequenceNumber:{message.SystemProperties.SequenceNumber} Body:{Encoding.UTF8.GetString(message.Body)}");
            await queueClient.CompleteAsync(message.SystemProperties.LockToken);
        }
        static Task ExceptionReceivedHandler(ExceptionReceivedEventArgs exceptionReceivedEventArgs)
        {
            Console.WriteLine($"Message handler encountered an exception {exceptionReceivedEventArgs.Exception}.");
            var context = exceptionReceivedEventArgs.ExceptionReceivedContext;
            Console.WriteLine("Exception context for troubleshooting:");
            Console.WriteLine($"- Endpoint: {context.Endpoint}");
            Console.WriteLine($"- Entity Path: {context.EntityPath}");
            Console.WriteLine($"- Executing Action: {context.Action}");
            return Task.CompletedTask;
        }
    }
}

12. Run the both app parallel and see below result.