Liam
Liam

Reputation: 29714

How can I access the ApplicationProperties of a service bus message in a Azure Function isolated process?

I have a service bus message that has some ApplicationProperties added to it:

ServiceBusMessage serviceBusMessage
serviceBusMessage.ApplicationProperties.Add("TenantId", tenantId);
serviceBusMessage.ApplicationProperties.Add("Serialization", "JSON");

I need to access these from my Azure function. In a class library style function app I can use ServiceBusReceivedMessage but there doesn't seem to be an equivalent in out of proc?

Upvotes: 1

Views: 4677

Answers (2)

Seboun
Seboun

Reputation: 61

I might arrive after the battle but there is an easy way to get access to the ApplicationProperties. Just replace the type string (which will return you only the content of the message) with the type Azure.Messaging.ServiceBus.ServiceBusReceivedMessage.

public async Task OnServiceBusAsync(
    [ServiceBusTrigger(topicName: "TOPIC", subscriptionName: "SUBSCRIPTION", Connection = "CONNECTION")]
    Azure.Messaging.ServiceBus.ServiceBusReceivedMessage message,
    ILogger log)

Then you would be able to get access to a specific custom property

    var vcountry = message.ApplicationProperties.GetValueOrDefault("BusinessCountry").ToString();

Upvotes: 6

Liam
Liam

Reputation: 29714

After much much digging I realised that the a) there is an overload for the function that includes a FunctionContext class.

so my function has the following signature:

[Function("ExternalProviderChanged")]
        public void ExternalProviderChanged([ServiceBusTrigger("topic",
            "subscription",
            Connection = "ServiceBus")]
            string myQueueItem, FunctionContext context)

and b) inside the FunctionContext the application settings are available, though pretty hidden. The function context exposes the following a context.BindingContext.BindingData which is a context.BindingContext.BindingData. Inside this dictionary is a property UserProperties (yes the old name not the one MS changed it to) and that property contains the ApplicationProperties in JSON format. So for me to get property x I had to do:

IReadOnlyDictionary<string, object> bindingData = context.BindingContext.BindingData;

if (bindingData.ContainsKey("UserProperties") == false)
{
    throw new Exception("Service bus message is missing UserProperties binding data");
}

string userPropertiesStr = bindingData["UserProperties"].ToString();
if (string.IsNullOrEmpty(userPropertiesStr))
{
    throw new Exception("UserProperties is null or empty");
}

JsonDocument json = JsonDocument.Parse(userPropertiesStr);
JsonElement xProp = json.RootElement.GetProperty("x");
string x = serializationProp.GetString();

Upvotes: 1

Related Questions