Introduction to Azure Service Bus With C# Example

Azure Service Bus

Azure Service Bus is a fully managed messaging service from Microsoft that allows applications to send messages to each other and receive messages reliably, without having to worry about the underlying infrastructure. This service is often used for scenarios where decoupled communication between applications is required, such as microservices architecture, or for enabling communication between cloud and on-premises systems.

This article will explore Azure Service Bus, what it does, and how it can be used in a C# application.

Azure Service Bus

What is Azure Service Bus?

Azure Service Bus is a messaging service that enables applications to send and receive messages in a reliable, secure, and scalable manner. This service is built on top of Azure's Service Fabric and provides a messaging infrastructure that can handle many messages and support multiple messaging patterns.

One of the key features of Azure Service Bus is its ability to support multiple messaging patterns, such as point-to-point messaging, publish/subscribe messaging, and request/reply messaging. This makes it an ideal solution for many use cases, such as enabling communication between microservices, sending and receiving messages between cloud and on-premises systems, and handling background jobs or workflows.

What is the Difference Between an Azure Service Bus and a Queue?

Azure Service Bus provides two primary messaging patterns: queues and topics/subscriptions. Both queues and topics/subscriptions enable the decoupling of the sender and receiver, but they differ in how they handle message delivery.

A queue is a unidirectional channel that holds messages until the recipient retrieves them. When a message is sent to a queue, it is stored in the queue until a consumer actively retrieves it. The queue guarantees that messages will be delivered in the order they were received, and each message will be delivered to a single consumer.

On the other hand, a topic is a publish/subscribe channel that allows multiple subscribers to receive messages that are published to a single topic. Subscribers can filter the messages they receive based on message properties, and messages can be delivered to multiple subscribers at once. Messages sent to a topic are held in a subscription until they are actively consumed, but they are not deleted when a subscriber receives them.

The main difference between an Azure Service Bus queue and a topic is that a queue provides a one-to-one message delivery model, while a topic provides a one-to-many message delivery model. Additionally, topics support message filtering and subscription, while queues do not.

Getting Started with Azure Service Bus in C#

To start using Azure Service Bus in a C# application, you'll need to create a Service Bus namespace and set up an Azure Service Bus Queue or a topic/subscription. A namespace is a container that holds all the messaging entities, such as queues and topics, for a given solution.

Once you have created a namespace, you can use Microsoft.Azure.ServiceBus NuGet package to interact with the Service Bus from your C# application. This package provides a simple and convenient API for sending and receiving messages, as well as managing messaging entities.

Just like connecting to a database, you will need an Azure Service Bus connection string. You can see an example in the code below.

Sending a Message to a Queue

Here is a simple example of how you can send a message to a Service Bus queue in C#,

using Microsoft.Azure.ServiceBus;
namespace ServiceBusExample {
    class Program {
        static void Main(string[] args) {
            const string serviceBusConnectionString = "Endpoint=sb://your-namespace.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=your-key";
            const string queueName = "your-queue-name";
            var queueClient = new QueueClient(serviceBusConnectionString, queueName);
            var message = new Message(Encoding.UTF8.GetBytes("Hello, World!"));
            queueClient.SendAsync(message).GetAwaiter().GetResult();
            Console.WriteLine("Message sent to the queue successfully.");
            queueClient.Close();
        }
    }
}

Receiving a Message

using Microsoft.Azure.ServiceBus;
namespace ServiceBusExample {
    class Program {
        static void Main(string[] args) {
            const string serviceBusConnectionString = "Endpoint=sb://your-namespace.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=your-key";
            const string queueName = "your-queue-name";
            var queueClient = new QueueClient(serviceBusConnectionString, queueName);
            var messageHandlerOptions = new MessageHandlerOptions(ExceptionReceivedHandler) {
                MaxConcurrentCalls = 1,
                    AutoComplete = false
            };
            queueClient.RegisterMessageHandler(ProcessMessagesAsync, messageHandlerOptions);
            Console.WriteLine("Listening for messages...");
            Console.ReadLine();
            queueClient.Close();
        }
        static Task ProcessMessagesAsync(Message message, CancellationToken cancellationToken) {
            Console.WriteLine($ "Received message: SequenceNumber:{message.SystemProperties.SequenceNumber} Body:{Encoding.UTF8.GetString(message.Body)}");
            return Task.CompletedTask;
        }
        static Task ExceptionReceivedHandler(ExceptionReceivedEventArgs exceptionReceivedEventArgs) {
            Console.WriteLine($ "Message handler encountered an exception {exceptionReceivedEventArgs.Exception}.");
            return Task.CompletedTask;
        }
    }
}

In this example, we first define the connection string and the name of the queue we want to send and receive messages from. To receive messages, we create an instance of the QueueClient class and use its RegisterMessageHandler method to register a message handler delegate that will process the received messages. The ProcessMessagesAsync method is called for each message received and prints the message's sequence number and body. The ExceptionReceivedHandler method is called if any exceptions are encountered during message processing.

Azure Function Service Bus Triggers

Connecting cloud services together is one of the features that make cloud applications scale and easier to maintain. Azure functions allow you to create small applications that execute when triggered.

One of the triggers available in Azure Functions is the Service Bus trigger, which allows you to process messages from a Service Bus queue or topic.

When you create an Azure Function with a Service Bus trigger, the function is automatically invoked whenever a new message is added to the specified queue or topic. The message is passed to the function as a parameter, and you can write code to process the message in any way you like.

For example, you can write a function that processes orders submitted by customers and have the function triggered whenever a new order message is added to a Service Bus queue. The function can read the message, extract the necessary data, and then perform any additional processing or actions required, such as sending a confirmation email to the customer or updating a database.

Summary

For Azure Service Bus pricing please check the Azure website for the most up-to-date rates.

Finally, we call queueClient.Close to close the connection to the Service Bus when we're done.

Thanks for reading my article.