Custom and System Properties in Azure Service Bus Messages using Azure.Messaging.ServiceBus

February 26, 2022

I’ve recently been revisiting and revising an old talk on Service Bus. One of the things that I’m updating is the Azure SDK library.

In this post, I’m going to discuss defining custom properties in a service bus message. In this previous post we discussed how the SystemProperties have been replaced by first class defined properties, making them more discoverable.

Using the old Microsoft.Azure.ServiceBus library, you would do something like this to write a UserProperty:



var queueClient = new QueueClient(connectionString, QUEUE\_NAME);

string messageBody = $"{DateTime.Now}: {messageText} ({Guid.NewGuid()})";
var message = new Message(Encoding.UTF8.GetBytes(messageBody));
message.UserProperties.Add("MyProperty", "test property value");

await queueClient.SendAsync(message);
await queueClient.CloseAsync();

And to read it back:




var messageReceiver = new MessageReceiver(connectionString, QUEUE\_NAME, ReceiveMode.PeekLock);
var message = await messageReceiver.ReceiveAsync();

var result = message.UserProperties["MyProperty"]


This feature is really useful - it means that you can pass a set of key/value pairs along with your message. Typically these will be additional metadata about the message itself. In Azure.Messaging.ServiceBus, you would write the same thing slightly differently:



await using var serviceBusClient = new ServiceBusClient(connectionString);
var sender = serviceBusClient.CreateSender(QUEUE\_NAME);

string messageBody = $"{DateTime.Now}: {messageText} ({Guid.NewGuid()})";
var message = new ServiceBusMessage(Encoding.UTF8.GetBytes(messageBody));
message.ApplicationProperties.Add("MyProperty", "Some property value");

await sender.SendMessageAsync(message);            

And to read it:



await using var serviceBusClient = new ServiceBusClient(connectionString);
var options = new ServiceBusReceiverOptions()
{
    ReceiveMode = ServiceBusReceiveMode.PeekLock
};
var messageReceiver = serviceBusClient.CreateReceiver(QUEUE\_NAME, options);
var message = await messageReceiver.ReceiveMessageAsync();

var result = message.ApplicationProperties["MyProperty"]


Because there are no longer User and System properties, there can now just be Application properties.

References

A previous post on deferred messages Azure Service Bus

A previous post on reading the dead letter queue



Profile picture

A blog about one man's journey through code… and some pictures of the Peak District
Twitter

© Paul Michaels 2024