Event Grid – Filters with Custom Events

In End-To-End Custom Events I posted about how to create a .net publisher and a c# Azure Function to listen to the post. However, Event Grid comes with some additional tricks, one of these is Filters. To test this I created two additional Azure Functions, HttpTriggerCSharpOranges and HttpTriggerCSharpApples. For this example they are exactly the same bar the log text, here is the Orange variant, you can guess what the Apple one looks like 😉

using System.Net;

public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
{
    log.Info("C# HTTP trigger function processed an Orange request.");
   

    //var message = await req.Content.ReadAsStringAsync();
    //log.Error(message);

   // Get request body
   dynamic data = await req.Content.ReadAsAsync<object>();

   // Set name to query string or body data
   string subject = data[0].subject;
   log.Info(subject);

   return subject == null
                ? req.CreateResponse(HttpStatusCode.BadRequest, "Please pass a subject on the query string or in the request body")
                : req.CreateResponse(HttpStatusCode.OK, "Hello " + subject);
}

The next step is to create the filtered subscriptions. The REST API pointed the way but it wasn’t that clear what I needed to define in AZ. So I entered;

az eventgrid topic event-subscription  create -h

That led to the following two filtered subscription definitions (remember to grab the Function URL by selecting the function ‘Copy Function URL;

az eventgrid topic event-subscription create --name functionlisteneroranges --endpoint <function URL to oranges> -g gridResourceGroup --topic-name <your topic> --subject-begins-with oranges

az eventgrid topic event-subscription create --name functionlistenerapples --endpoint <function URL for apples> -g gridResourceGroup --topic-name <your topic> --subject-begins-with apples

All that’s left is to change the subject in the calling code to start with either apples or oranges;

new PaulsTopic
{
  Id = Guid.NewGuid().ToString(),
  EventTime = DateTime.UtcNow,
  EventType = EventType.recordInserted,
  Subject = "oranges\\paulstopics\\mytest",
  Data = new SomeData
  {
    Name = "Paul",
    Rate = 99.9
   }
}

Now when you run the subscription pushes the correct message to the correct listener. Nice 🙂

Advertisements
This entry was posted in Azure, Uncategorized and tagged , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s