Page 32 - MSDN Magazine, February 2018
P. 32
Figure 9 A Web API Controller That Receives Events
using System;
using System.Collections.Generic; using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json;
namespace EmployeeRecords.Controllers {
public class GridEvent<T> where T : class {
public string Id { get; set; }
public string Subject { get; set; } public string EventType { get; set; } public T Data { get; set; }
public DateTime EventTime { get; set; }
}
[Produces("application/json")] [Route("api/EmployeeUpdates")]
public class EmployeeUpdatesController : Controller {
private bool EventTypeSubcriptionValidation
=> HttpContext.Request.Headers["aeg-event-type"].FirstOrDefault() ==
"SubscriptionValidation";
private bool EventTypeNotification
=> HttpContext.Request.Headers["aeg-event-type"].FirstOrDefault() ==
"Notification";
[HttpPost]
public async Task<HttpResponseMessage> Post() {
using (var reader = new StreamReader(Request.Body, Encoding.UTF8)) {
var jsonContent = await reader.ReadToEndAsync(); var gridEvent =
JsonConvert.DeserializeObject<List<GridEvent<Dictionary<string, string>>>>(jsonContent)
.SingleOrDefault();
if (gridEvent == null) {
return new HttpResponseMessage { StatusCode = HttpStatusCode.BadRequest}; }
// Check the event type from Event Grid. if (EventTypeSubcriptionValidation)
{
// Retrieve the validation code and echo back.
var validationCode = gridEvent.Data["validationCode"]; var validationResponse =
JsonConvert.SerializeObject(new { validationResponse = validationCode });
return new HttpResponseMessage {
StatusCode = HttpStatusCode.OK,
Content = new StringContent(validationResponse) };
}
else if (EventTypeNotification) {
// Pseudo code: Update records
return new HttpResponseMessage { StatusCode = HttpStatusCode.OK }; }
else {
return new HttpResponseMessage { StatusCode = HttpStatusCode.BadRequest }; }
} }
} }
{
"id": "40000",
"eventType": "employeeAdded",
"subject": "department/finance", "eventTime": "2017-12-20T10:10:20+00:00", "data":{
"employeeId": "24",
"employeeName": "David St. Hubbins", "employeeEmail": "david@contoso.com", "manager": "finance@contoso.com", "managerId": "10"
}
Next, the filter for the event type must be done with a condition action. This is a slight departure from how the event subscription was created with the Function because there isn’t a way to select this option in the Event Grid trigger.
The last step sends an email to the employee. It uses the properties that were retrieved from the second step to populate the recipient address and subject fields of the email. To test the Logic App, click Run from the designer and send a message to the endpoint like before.
The last event subscription is a basic HTTP callback, or WebHook. I’ll update an existing ASP.NET Core application with a Web API for incoming events. The code for the WebHook will be very sim- ilar to the Azure Function I wrote earlier. Some subtle differences include the way header values are retrieved to inspect the request type, as seen in Figure 9.
When creating the event subscription, the event type registered should be employeeRemoved. This change satisfies the requirement that the handler only wants to receive messages for an employee
that’s removed from the organization. Also notice that neither the prefix nor suffix filters are used because the subscriber wants to be notified for each occurrence, regardless of the department:
az eventgrid event-subscription create --name <event-subscription-name> \ --resource-group <resource group name> \
--topic-name <topic name> \
--included-event-type employeeRemoved \
--endpoint <function endpoint>
Last, remember that the endpoint for the event subscription must be secure. If you reference an App Service on Azure, you have to specify HTTPS in the address, or adding the subscription will fail.
Wrapping Up
Azure Event Grid is truly a game-changing service. In this article, I addressed a common application integration scenario. Event Grid was used as the enabling technology to connect the application to other services such as an Azure Function, a Logic App and even a custom WebHook that could reside anywhere. When comple- mented with serverless apps, Event Grid really shines, as the two together can take advantage of the tremendous scale and integration features that Azure supports. The code in this article can be found at github.com/dbarkol/AzureEventGrid. n
DaviD Barkol is an Azure Specialist at Microsoft on the Global Black Belt Team. Contact him on Twitter: @dbarkol or through email at dabarkol@microsoft.com.
Thanks to the following Microsoft technical experts for reviewing this article: Bahram Banisadr and Dan Rosanovsanova
}
28 msdn magazine
Microsoft Azure