Sunday, August 9, 2020

Azure - Service Bus Topic- C# Message Sender


In this article we will learn how to send messages to Azure Service Bus topics using C#.NET. As of writing this article, topics were available only on Standard tier Service Bus instances (and not in Basic tier). So if you want to try out this tutorial, then you must create a Standard tier Service Bus in your subscription.

Open Visual Studio and create a blank console C# project.

Then add “Microsoft.Azure.ServiceBus” from NuGet Manager.



After installing the required NuGet package, make note of the following values from the Azure Service Bus created in your subscription.

Navigate to Settings > Shared access policies

Then on the right-hand side panel, copy the Primary Connection String.

Use the copied connection string for the following variable.
var connectionString = “Endpoint=sb://sbus01.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=hcjHcaRdwGQNPdVA4K0GzXGCE9ceplF/HTq6glXEycA=”;

Next copy the name of the topic.

Use the copied topic name to set the following variable.

var queueName = “topic1”;

For sending messages to Azure Service Bus topic, create a C# console application targeting .NET Core Framework.

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

namespace ServiceBusMessageSender
{
    class Program
    {
        const string ServiceBusConnectionString = "Endpoint=sb://sbus01.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=hcjHcaRdwGQNPdVA4K0GzXGCE9ceplF/HTq6glXEycA=";
        const string TopicName = "topic1";
        static ITopicClient topicClient;

        public static async Task Main(string[] args)
        {
            const int numberOfMessages = 2;
            topicClient = new TopicClient(ServiceBusConnectionString, TopicName);

            Console.WriteLine("======================================================");
            Console.WriteLine("Press ENTER key to exit after sending all the messages.");
            Console.WriteLine("======================================================");

            // Send messages.
            await SendMessagesAsync(numberOfMessages);

            Console.ReadKey();

            await topicClient.CloseAsync();
        }

        static async Task SendMessagesAsync(int numberOfMessagesToSend)
        {
            try
            {
                for (var i = 0; i < numberOfMessagesToSend; i++)
                {
                    // Create a new message to send to the topic.
                    string messageBody = $"Message {i}";
                    var message = new Message(Encoding.UTF8.GetBytes(messageBody));

                    // Write the body of the message to the console.
                    Console.WriteLine($"Sending message: {messageBody}");

                    // Send the message to the topic.
                    await topicClient.SendAsync(message);
                }
            }
            catch (Exception exception)
            {
                Console.WriteLine($"{DateTime.Now} :: Exception: {exception.Message}");
            }
        }
    }
}


Run the program. Sometimes on some machine when running the program in debug mode you may receive the following pop up message on the screen. Just wait for 2-3- minutes and the pop up will disappear and the messages will get sent to the Service Bus topic.


Stats before sending messages.

Stats after sending a few messages. It takes a few minutes for the statistics to actually show up on the portal.


That's All!