0

I want to create an Azure Function that will fulfill the following requirements:

  • Trigger upon an HTTP request
  • Looks at an Azure Service Bus Subscription and gets the next message based on a set of filters specified in the HTTP Request.
Neko
  • 21
  • 6

1 Answers1

0

If you are using C# you can do something like this:

using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Microsoft.Azure.ServiceBus;
using Microsoft.Azure.ServiceBus.Core;

namespace HttpTriggerSBRead
{
    public static class ReadSBOnHttpTrigger
    {
        const string ServiceBusConnectionString = "{service bus connection string}";
        const string TopicName = "{name of your topic}";
        const string SubscriptionName = "{name of your subscription}";

        [FunctionName("ReadSBOnHttpTrigger")]
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            string filter = req.Query["filter"];

            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            dynamic data = JsonConvert.DeserializeObject(requestBody);
            filter = filter ?? data?.filter;

            SubscriptionClient sqlFilterOnlySubscriptionClient = new SubscriptionClient(ServiceBusConnectionString,
                TopicName, SubscriptionName);

            await sqlFilterOnlySubscriptionClient.AddRuleAsync(new RuleDescription
            {
                Filter = new SqlFilter(filter),
                Name = filter
            });
            await ReceiveMessagesAsync(SubscriptionName, log);
            await sqlFilterOnlySubscriptionClient.RemoveRuleAsync(filter);

            return filter != null
                ? (ActionResult)new OkObjectResult($"{filter}")
                : new BadRequestObjectResult("Please pass a filter on the query string or in the request body");
        }

        static async Task ReceiveMessagesAsync(string subscriptionName, ILogger log)
        {
            string subscriptionPath = EntityNameHelper.FormatSubscriptionPath(TopicName, subscriptionName);
            IMessageReceiver subscriptionReceiver = new MessageReceiver(ServiceBusConnectionString, subscriptionPath, ReceiveMode.ReceiveAndDelete);

            log.LogInformation($"{DateTime.Now} :: Receiving Messages From Subscription: {subscriptionName}");
            var receivedMessage = await subscriptionReceiver.ReceiveAsync(TimeSpan.FromSeconds(30));

            if (receivedMessage != null)
            {
                log.LogInformation($"Lable Property = {receivedMessage.Label}");
            }

            log.LogInformation($"{DateTime.Now} :: Messages From Subscription: {subscriptionName}");
        }
    }
}

To use it you need to pass in the filter parameter to your function. For example something like this:

http://localhost:7071/api/ReadSBOnHttpTrigger?filter=sys.Label=%27test%27 or http://localhost:7071/api/ReadSBOnHttpTrigger?filter=sys.To=%27test%27

Just for the reference, I used this code as source with some small modifications: https://github.com/Azure/azure-service-bus/tree/master/samples/DotNet/GettingStarted/Microsoft.Azure.ServiceBus/TopicSubscriptionWithRuleOperationsSample

hujtomi
  • 1,540
  • 2
  • 17
  • 23