Publish a message to Azure Queue with C#

Share this post

In this short post, we’ll see how to post a message to an Azure Queue (also known as Azure Queue Storage). I won’t be going over how to setup an Azure account or how to create a queue, we’ll cover this in a different post, instead, I’ll demonstrate how to send a message that is actually a POCO serialized to a JSON string.

What is Azure Queue?

Azure Queue storage is a service for storing large numbers of messages that can be accessed from anywhere in the world via authenticated calls using HTTP or HTTPS.

From Introduction to Azure Queues – Azure Storage | Microsoft Docs

Pre-requisites

In order to be able to send a message to an Azure Queue, you need an active Azure Account set with an Azure Queue Storage service, and have the following NuGet packages in your project:

Code recipes

Adding a message to a queue

public static void PublishMessageToQueue(string QueueName, MessageInterchange messageInterchange, TraceWriter log)
{
    log.Verbose("Enqueue message to " + QueueName + " : " + JsonConvert.SerializeObject(messageInterchange));
    string StorageAccountConnectionString = ConfigurationManager.AppSettings["saconnection"];
    if (string.IsNullOrEmpty(StorageAccountConnectionString))
    {
        log.Warning("Using alternative connection string");
        StorageAccountConnectionString = [Storage account connection string]
    }
    // Retrieve storage account from connection string.
    CloudStorageAccount storageAccount = CloudStorageAccount.Parse(StorageAccountConnectionString);

    // Create the queue client.
    CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient();

    // Retrieve a reference to a queue.
    CloudQueue queue = queueClient.GetQueueReference(QueueName);

    // Create a message and add it to the queue.
    CloudQueueMessage message = new CloudQueueMessage(JsonConvert.SerializeObject(messageInterchange));
    queue.AddMessage(message);
}

 

Leave a Reply

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