Event Grid – End to End Custom events in .net

Event Grid is a new Azure offering that allows you to listen to a number of events from different Azure sources. One source that interested my is ‘Custom Event’. How can you get this working in .net? This is one way;

First I followed the steps in this;
Quick Start – Create and route custom events with Azure Event Grid

That provides you with the custom topic you need. In my case ‘pmtopic’. A quick note, make sure you create/have a resource group in “West US2”. I found that parts of it worked in other resource groups but other parts failed with strange errors.

Next up, create an app to ‘publish’ a custom event. I chose a Console app, but it’s just plain .net.

        public enum EventType
        {
            recordInserted
        }

        public abstract class EventTopic
        {
            
            [JsonProperty(PropertyName = "id")]
            public string Id { get; set; }

            [JsonProperty(PropertyName = "subject")]
            public string Subject { get; set; }

            [JsonProperty(PropertyName = "eventtype")]
            [JsonConverter(typeof(StringEnumConverter))]
            public EventType EventType { get; set; }

            [JsonProperty(PropertyName = "eventtime")]
            public DateTime EventTime { get; set; }

        }

        public class SomeData
        {
            public string Name { get; set; }
            public double Rate { get; set; }

        }
        public class PaulsTopic : EventTopic
        {
            [JsonProperty(PropertyName = "data")]
            public SomeData Data { get; set; }
        }

        static void Main(string[] args)
        {

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

            

            var messageBody = JsonConvert.SerializeObject(paulsTopic);

            PostMessage(messageBody).Wait();           
        }

        private static async Task PostMessage(string messageBody)
        {            
            using (var httpClient = new HttpClient())
            {
                StringContent content = new StringContent(messageBody);
                var request = new HttpRequestMessage()
                {
                    RequestUri = new Uri("https://<your topic endpoint here>"),
                    Method = HttpMethod.Post,
                    Content = content
                };

                request.Headers.Add("aeg-sas-key", "<your key here>");


                var response = await httpClient.SendAsync(request);
                if (!response.IsSuccessStatusCode)
                {
                    Console.WriteLine(response.ReasonPhrase);
                    var body = response.Content.ReadAsStringAsync().Result;
                }
            }
        }

The key parts appear to be that you need to set the properties in EventTopic, they don’t have to be anything specific but they need to be there. If you are following the Quick Start guide then you should be able to run the above and a new message will appear at RequestBin. I also wanted to use .net to listen to the event. For this I chose to create an Azure Function. For this I followed;
Create Serviceless Function. My function looked list this;

using System.Net;

public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
{
    log.Info("C# HTTP trigger function processed a request.");
      
   // 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);
}

I also switched diagnostics to ‘Info’ so I could see the output in the Function monitoring system. Note that you are sending in an array of messages so remember to get an array from the message. One missing bit of the jigsaw is you now have create the subscription from your topic to the function. To do that select the Function and ‘Get Function URL’. Insert that into the following CLI/Powershell script;

az eventgrid topic event-subscription create --name functionlistener --endpoint <function endpoint URL>  -g gridResourceGroup --topic-name <your topic name>

Now when you run your publishing app you should see an invocation in the Function monitoring system, nice 🙂

Next stop, I need to start experimenting with case sensitivity and security, but in truth it wasn’t that hard to get here and it looks like a interesting event mechanism.

Edit – see also this great post; Azure Custom Events

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

One Response to Event Grid – End to End Custom events in .net

  1. Pingback: Event Grid – Filters with Custom Events | IT Bytes

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