Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using BrokeredMessage with ServiceBus Queue Trigger in Azure Function

I've created an Azure Function that is triggered any time a new message is added to an Azure ServiceBus queue. With this code it works fine:

#r "Newtonsoft.Json"
#load "..\shared\person.csx"

using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;

public static void Run(string message, TraceWriter log)
{
    var person = JsonConvert.DeserializeObject<Person>(message, 
            new JsonSerializerSettings() {ContractResolver = new CamelCasePropertyNamesContractResolver()});
    log.Verbose($"From DeserializeObject: {person.FirstName} {person.LastName}");
}

I've seen that I can also bind the message to a POCO like that:

public static void Run(Person message, TraceWriter log)
{
    log.Verbose($"From DeserializeObject: {message.FirstName} {message.LastName}");
}

Now I would like to bind the message to a BrokeredMessage because I need to have access to the properties of the message.

like image 244
Thomas Avatar asked Apr 19 '16 01:04

Thomas


People also ask

How do I trigger Service Bus queue in Azure?

Right-click on the project and click on project -> Click on Add -> Select New Azure Function. Select Azure function and give it a name and click on Add button. Now select Service Bus Queue Trigger and specify queue name and click on Add button. That's it -- our Service Bus trigger function is created.


2 Answers

Edit New SDK supports the servicebus sdk using #r directive

#r "Microsoft.ServiceBus"
using Microsoft.ServiceBus.Messaging;

public static void Run(BrokeredMessage msg, TraceWriter log)
{
    log.Info($"C# ServiceBus queue trigger function processed message: {msg}");
}

Old version

Only two steps:

I've create a project.json file to add a reference to the WindowsAzure.ServiceBus Nuget package (see SO Post):

{
    "frameworks": {
        "net46":{
            "dependencies": {
                "WindowsAzure.ServiceBus": "2.7.6"
            }
        }
    }
}

I've added a reference to the brokered message:

using Microsoft.ServiceBus.Messaging;

public static void Run(BrokeredMessage  message, TraceWriter log)
{
    log.Verbose("Function has been triggered !!!");
}
like image 83
Thomas Avatar answered Nov 10 '22 01:11

Thomas


I tried Thomas' solution and it seems that this does not work anymore.

The documentation states:

In addition, the following assemblies are special cased and may be referenced by simplename (e.g. #r "AssemblyName"):

  • ...
  • Microsoft.ServiceBus

So without touching the project.json file the following works:

#r "Microsoft.ServiceBus"

using Microsoft.ServiceBus.Messaging;

public static void Run(BrokeredMessage msg, TraceWriter log)
{
    log.Info($"C# ServiceBus queue trigger function processed message: {msg}");
}
like image 36
officer Avatar answered Nov 10 '22 02:11

officer