Search code examples
azureazure-servicebus-queuesazure-functions

How to write azure function that can get triggered when an item appears in azure service bus queue using C#?


The new azure function preview contains a few templates for C#. But there is no service bus queue template for C#. There is a trigger template for node with service bus. But on close inspection, it only supported Notification Hubs and not service bus queue. Is it even possible to write an azure function that can only be triggered when an item appears in azure service bus queue? If it is not possible now, will there be such a template in the near future?

Thanks. Raghu/..


Solution

  • Update: The below steps and information still hold, however we now have a "ServiceBusQueueTrigger - C#" template live in the portal, so the workaround steps are no longer necessary :)

    ServiceBus IS supported already for C#, we just need to add a template for it (we'll add very soon). In general, templates are just starting points - you can always modify templates by adding additional bindings, or start from the empty template and build up your own Function.

    Until we get the template uploaded, you can get this working yourself by starting from the C# Empty template. For example, you can enter binding info like the following in the Advanced Editor on the Integrate tab:

    {
      "bindings": [
        {
          "type": "serviceBusTrigger",
          "name": "message",
          "direction": "in",
          "queueName": "samples-input",
          "connection": "myServiceBus"
        }
      ]
    }
    

    Make sure your Function App has an AppSetting matching the name of the connection property, containing your ServiceBus connection string. It looks like we currently have some issues with the connection string picker for ServiceBus (which will also be fixed very soon), but you can use "Function app settings"/"Go to App Service Settings"/"Application Settings" to add this app setting. Then you can use the corresponding Function code:

    using System;
    using Microsoft.Azure.WebJobs.Host;
    
    public static void Run(string message, TraceWriter log)
    {
        log.Verbose($"C# ServiceBus Queue function processed message: {message}");
    }
    

    This function will then be invoked whenever new messages are added to ServiceBus queue samples-input.