Sending messages to Azure Service Bus queue

To connect to Azure Service Bus you need to import nuget package: WindowsAzure.ServiceBus. Next step would be getting a connection string to your resource group. It can be found in Azure Portal, in Service Bus section.

It should look like this:

azure-connection-string

Copy connection string – primary key and paste it in App.config file. A key like this:

should already be generated when you imported the package.

    using Microsoft.ServiceBus.Messaging;
    using System.Configuration;

    class Program
    {
        static void Main(string[] args)
        {
            var queueName = "stockchangerequest";
            var connectionString = ConfigurationManager.AppSettings["Microsoft.ServiceBus.ConnectionString"];
            var queueClient = QueueClient.CreateFromConnectionString(connectionString, queueName);

            queueClient.Send(new BrokeredMessage("This is a test message content"));
        }
    }

Only few lines of code let you send  message to a queue. However, what if something goes wrong? This code can also be written asynchronous, so that sending a message would not block current thread. I’ll also add a try catch block with logging.

    using Microsoft.ServiceBus.Messaging;
    using System;
    using System.Configuration;
    using System.Threading.Tasks;

    class Program
    {
        static void Main(string[] args)
        {
            Task.Run(SendMessageAsync).GetAwaiter().GetResult();
        }

        static async Task SendMessageAsync()
        {
            try
            {
                var queueName = "stockchangerequest";
                var connectionString = ConfigurationManager.AppSettings["Microsoft.ServiceBus.ConnectionString"];
                var queueClient = QueueClient.CreateFromConnectionString(connectionString, queueName);

                await queueClient.SendAsync(new BrokeredMessage("This is a test message content"));
            }
            catch (Exception ex)
            {
                Console.WriteLine("An exception occured: " + ex.Message);
            }
        }
    }

Transient error and retry policy

This is an OK code. However, connecting to remote server such as Azure Service Bus will fail from time to time. Those situations are called transient, because they last for a very small amount of time. No matter how rarely it may occur or how fast it will be up, code have to prepared for that. In Azure Service Bus there is a mechanism implemented to cope with those problems – a retry policy.

Retry policies allows you to execute some operations repeatedly if an error occured. There are two types of retry policy: linear and exponential. Linear retry policy retries an operation periodically with same backoff period. An exponential retry policy execute operations again typically multiplying previous waiting time. Let’s see how it can be implemented.

queueClient.RetryPolicy = new RetryExponential(TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(30), 10);

This line meas that if there will be any problems with connection to Azure Service Bus queue client will seamlessly try again after waiting between 5 and 30 seconds and that wait time will grow exponentially.

More about good practices and patterns you can find in this amazing Microsoft article.

.Net Framework also provides NoRetry policy and gives you RetryPolicy base class to implement your own policy.

One thing also need mentioning. For sending large amount of messages, you can use SendBatch and SendBatchAsync.

Leave a Reply

Your email address will not be published. Required fields are marked *