Azure Service Bus .NET SDK Deep Dive – Sending a message

Explains send a message to a queue, for more posts in this series go to Contents.

In the previous post we looked at how queues can be created with the management client. For being able to send messages to queues we required the Microsoft.Azure.ServiceBus package. If you search for Azure Service Bus on nuget you might stumble over the WindowsAzure.ServiceBus package, be aware that this is the old and new legacy Azure Service Bus client. For any new development you want to use the Microsoft.Azure.ServiceBus client.

Once you have the connection string to Azure Service Bus you can start sending messages to queues by using the QueueClient. The QueueClient provides the necessary bits to interact with queues.

var destination = "queue";
var client = new QueueClient(connectionString, destination);
var message = new Message();
message.Body = Encoding.UTF8.GetBytes("Deep Dive");
await client.SendAsync(message);
await client.CloseAsync();

As you can see in the above snippet the constructor of the QueueClient accepts the connection string as well as the destination queue to send to. Then we create the actual message, assign the body to it and use the queue client send method to send it to the destination. Once the send operations are done the client is closed.

For the sake of this example I’m using a simple approach to get the byte array for the message body by leveraging Encoding.UTF8.GetBytes. Imagine for production scenarios you might want to apply techniques like byte array buffering to reduce the allocations.

The message object allows to set more properties of the message. For example in cases when metadata should be added without having to deserialize the payload it is possible to add that metadata to the UserProperties.

message.UserProperties.Add("TenantId", "MyTenantId");

Let’s see what happens when we execute the above code.

When trying to send a message to a destination that doesn’t exist a MessageEntityNotFoundException is raised. Let’s fix this briefly with the Service Bus Explorer tool (of course if you have read my previous post you would also know how to do this with code).

Creating the queue with Service Bus Explorer

After the destination queue is available the above code executes without any issues and the destination queue contains the message sent including all the user properties associated with the message.

Executing the same code again *fingers crossed*
The message has arrived

We have seen how it is possible with a few lines of code to send a message to an Azure Service Bus Queue using the QueueClient. Next up we’ll see how it is possible to programmatically receive the messages out of the queue again.

About the author

Daniel Marbach

2 comments

By Daniel Marbach

Recent Posts