6 minute read

As of yesterday (16-8-2017) the public preview of Azure Event Grid is live. Azure Event Grid is a fully managed event routing service. Azure Event Grid greatly simplifies the development of event-based applications and simplifies serverless workflow creation. Using a single service, Azure Event Grid manages all routing of events from any source, to any destination, for any application.

Microsoft explains Azure Event Grid as follows:

“Azure Event Grid allows you to easily build applications with event-based architectures. You select the Azure resource you would like to subscribe to, and give the event handler or WebHook endpoint to send the event to. Event Grid has built-in support for events coming from Azure services, like storage blobs and resource groups. Event Grid also has custom support for application and third-party events, using custom topics and custom webhooks.

As explained above there is support for custom topics and webhooks. Setting up custom events needs the following within Azure.

 

Azure Event Grid

The Event Grid Topic is the Azure Service were the events are sent to, and the Subscriptions are the applications that need to receive the events. So let's get this to work within Azure and Visual Studio.

Create the Event Grid Topic

First create the Event Grid Topic in Azure. With this topic we know were we need to send the events.

  1. Open the Azure Portal (https://portal.azure.com)
  2. Click on the “+” icon and search for “Event Grid Topic”.
  3. Click on “Create” to create the topic.
  4. Fill in the correct information and click on “Create”

Azure Event Grid Topic

You now have a Topic were events can be send too.

Sending Events to the Event Grid Topic

With the Topic in place the events can be send. In order to send events we need two things: the endpoint and the key from the topic. Both things are available on the Azure Event Grid Topic Blade.

  1. Open the Event Grid Topic Blade to find the Endpoint and Key of the Topic.

Event Grid Topic

The Endpoint is used to Post a request to and The key as an authentication to the topic and is placed in the header with the key: “aeg-sas-key”.

  1. The event itself needs should be in the form of a json message with specific properties. On the documentation site of Azure Event Grid you will find information on the schema: Event Grid event schema. Good to notice on the schema and the example provided is that the event is an array.
[
  {
    "topic": "/subscriptions/{subscription-id}/resourceGroups/Storage/providers/Microsoft.EventGrid/topics/myeventgridtopic",
    "subject": "/myapp/vehicles/motorcycles",    
    "id": "b68529f3-68cd-4744-baa4-3c0498ec19e2",
    "eventType": "recordInserted",
    "eventTime": "2017-06-26T18:41:00.9584103Z",
    "data":{
      "make": "Ducati",
      "model": "Monster"
    }
  }
]
subject string Path to the event subscription it is used for filtering and routing the requests
eventType string The event type
eventTime string The time the event is generated based on the provider's UTC time. During testing I  needed to give a date time offset.
id string Unique identifier for the event. Can be a Guid provided as string value.
data object Your specific event data.
  1. Open Visual Studio and Create a new Console Application Project. In this project add the below code.
static void Main(string[] args) {
    var eventNew = MakeRequestEvent();
    eventNew.Wait();            
    Console.WriteLine(eventNew.Result.Content.ReadAsStringAsync().Result);

    Console.ReadKey();
}

private static async Task<HttpResponseMessage> MakeRequestEvent() {
    string topicEndpoint = "[endpoint]";
    var httpClient = new HttpClient();
    httpClient.DefaultRequestHeaders.Add("aeg-sas-key", "[key]");

    List<CustomEvent<Account>> events = new List<CustomEvent<Account>>();
    var customEvent = new CustomEvent<Account>();
    customEvent.EventType = "eventgridtest";
    customEvent.Subject = "/msft/test";
    customEvent.Data = new Account() { Name = "Maik", Gender = "Male" };
    events.Add(customEvent);

    string jsonContent = JsonConvert.SerializeObject(events);
    Console.WriteLine(jsonContent);

    var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
    return await httpClient.PostAsync(topicEndpoint, content);            
}

The code above make an http post call to the topic endpoint with the key in the “aeg-sas-key” header.

The event (json) is placed in the body which is a serialized version of the CustomEvent object I created myself. This object has the default properties for an event. For the data every object could be used as it based on generics. The Accounts class used is a basic class with only a Name and Gender property.

public class CustomEvent<T> {

    public string Id { get; private set; }

    public string EventType { get; set; }

    public string Subject { get; set; }

    public string EventTime { get; private set; }

    public T Data { get; set; }

    public CustomEvent(){
        Id = Guid.NewGuid().ToString();

        DateTime localTime = DateTime.Now;
        DateTime utcTime = DateTime.UtcNow;
        DateTimeOffset localTimeAndOffset = new DateTimeOffset(localTime, TimeZoneInfo.Local.GetUtcOffset(localTime));
        EventTime = localTimeAndOffset.ToString("o");
     }
}

If the event is posted successfully the response will be empty.

Subscribing application

The subscribing application will be a simple web application with one API method. This method will add a custom event in Application Insights.

  1. Create a new project within Visual Studio make this a ASP.Net Web application.
  2. Use a API project as the template for the application.
  3. Add the Application Insights nuget package.
  4. Add a EventsController and add the below code.
public class EventsController : ApiController {
    // POST api/events
    public void Post([FromBody]List<CustomEvent<Account>> value) {
        foreach(var eventValue in value) {
            string data = JsonConvert.SerializeObject(eventValue);
            Dictionary<string, string> allData = new Dictionary<string, string>();
            allData.Add("event id", eventValue.Id);
            allData.Add("eventdata", data);

            TelemetryClient client = new TelemetryClient();
            client.TrackEvent("Event Received", allData);
        }
    }
}

This method reads the event from the body and places the data within Application Insights with the name Event Received.

  1. Publish the application to Azure and remember the endpoint of the API method [url]/api/events.

Configure the Event Grid Subscriber

With all applications in place the Event Grid Topic needs to know were to send the events to. For this an Event Grid Subscriber needs to be configured.

  1. Open the Event Grid Blade and click on Event Subscription.

Add Azure Event Grid Subscription

  1. Fill in the correct properties. The EventType property can be used to filter on the eventtype of the event. The prefix and suffix properties can be used to filter on the subject.

Create Event Grid Subscription

  1. Click on create to create the subscription.

Azure Event Grid with Subscription

The Test

With everything in place we can start using the Event Grid.

  1. Fire up the console application the application will give you the json message as output. If something goes wrong during the event you will see the error message within the console window.