Page 29 - MSDN Magazine, February 2018
P. 29

Figure 6 Implementation for the New Employee Event Handler
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http; using Microsoft.Azure.WebJobs.Host;
using Newtonsoft.Json;
namespace NewEmployeeApp {
public static class NewEmployeeHandler {
public class GridEvent<T> where T : class {
public string Id { get; set; }
public string EventType { get; set; } public string Subject { get; set; } public DateTime EventTime { get; set; } public T Data { get; set; }
public string Topic { get; set; }
}
[FunctionName("newemployeehandler")]
public static async Task<HttpResponseMessage> Run(
[HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequestMessage req,
TraceWriter log)
{
log.Info("New Employee Handler Triggered");
// Retrieve the contents of the request and
// deserialize it into a grid event object.
var jsonContent = await req.Content.ReadAsStringAsync(); var gridEvent =
JsonConvert.DeserializeObject<List<GridEvent<Dictionary<string, string>>>>(jsonContent)
?.SingleOrDefault();
// Check to see if the event is available and // return an error response if its missing. if (gridEvent == null)
{
return req.CreateErrorResponse(HttpStatusCode.BadRequest, $@"Missing event details");
}
// Check the header to identify the type of request
// from Event Grid. A subscription validation request
// must echo back the validation code.
var gridEventType = req.Headers.GetValues("Aeg-Event-Type").
FirstOrDefault();
if (gridEventType == "SubscriptionValidation") {
var code = gridEvent.Data["validationCode"]; return req.CreateResponse(HttpStatusCode.OK,
new { validationResponse = code }); }
else if (gridEventType == "Notification") {
// Pseudo code: place message into a queue // for further processing.
return req.CreateResponse(HttpStatusCode.OK);
} else {
return req.CreateErrorResponse(HttpStatusCode.BadRequest, $@"Unknown request type");
} }
} }
Because there aren’t any subscribers, there isn’t anything to observe yet. The next step will be to see
this in action by creating a few event han-
dlers for Event Grid to push the events to.
of Visual Studio (I used version 15.5.2 for this article). Let’s start by creating a new project and selecting Azure Functions from the Cloud tem- plates. In the New Project dialog box, select the HTTP trigger option and keep
Handling Events with
an Azure Function
Now comes the fun part of subscribing to events. Our first handler will be an Azure Function. To learn the basics of creating a Function, see bit.ly/2A6pFgu. For this situation, I want to specifically subscribe to events for recently added employees. Additionally, and just as important, this handler must only be invoked for employees that belong to theengineering department.
Most examples walk through the creation of a Function using the Azure Portal—which is super-easy and quick. I’d like to show you how to do this locally, from Visual Studio. This will pave the way for more production-ready code. I’ll also use a utility called ngrok (see ngrok.com) to support local debugging with Event Grid.
If you’d like to follow along, you’ll need ngrok, as well as an up-to-date version msdnmagazine.com
Figure 7 Creating an Event Subscription from the Portal
the default values.
Update the code for the function to
reflect what’s represented in Figure 6. Feel free to rename the file to reflect the function name.
There is some important code to review here. At the very beginning is a class called GridEvent that’s intended to reflect the payload and event schema from Event Grid. Ideally, I would place this class in a common library so it can be reused. For this example, it’s used to deserialize the contents of the request into a strongly typed object.
Event Grid will send to its subscribers two types of requests—Subscription- Validation and Notification—that you can identify by inspecting a value from the header. The validation request is important to ensure that all subscribers are added explicitly. All I must do here is echo back the validation code to acknowl- edge that I can receive messages:
February 2018 25


































































































   27   28   29   30   31