Event Grid Trigger to Cosmos DB Azure Function v2

I have about five different Microsoft Cloud Workshops (MCW)s that I support.  Every couple of months we have to update them due to the changes that are made to Azure UI and changes to the core functionality.

One of the MCWs is based on serverless architecture.  Part of the labs has you deploy an Azure function from Visual Studio, and another part has you manually create the Azure functions.  The thing is, they utilize CosmosDB as the output from a Event Grid trigger with “JavaScript”.

Turns out, they removed “JavaScript” from the list of options (actually, there are no more options) for some reason, although they did hint at it being an unsupported language.  So what does that mean for us?  Well, I had to convert the javascript to C# 2.0 function code and let’s just say, it took a while.  Here’s the original code for the JavaScript version of the function:

module.exports = function (context, eventGridEvent) {
        context.log(typeof eventGridEvent);
        context.log(eventGridEvent);
        context.bindings.outputDocument = {
            fileName : eventGridEvent.Data["fileName"],
            licensePlateText : eventGridEvent.Data["licensePlateText"],
            timeStamp : eventGridEvent.Data["timeStamp"],
            exported : false
        }
        context.done();
    };
Here is the C# v2.0 version of the function:

#r "Microsoft.Azure.EventGrid"
#r "Microsoft.Azure.WebJobs"
#r "Newtonsoft.Json"
#r "Microsoft.Azure.DocumentDB.Core"
#r "Microsoft.Azure.WebJobs.Extensions.CosmosDB"
using Microsoft.Azure.EventGrid.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.CosmosDB;
using Microsoft.Azure.WebJobs.Host;
using System.Collections.Generic;
using Microsoft.Extensions.Logging;

public static void Run(JObject eventGridEvent, out JObject outputDocument, ILogger log)
{
log.LogInformation(eventGridEvent.ToString());
dynamic data = eventGridEvent["data"];

outputDocument = new JObject();
outputDocument["fileName"] = data.fileName;
outputDocument["licensePlateText"] = data.licensePlateText;
outputDocument["timeStamp"] = data.timeStamp;
outputDocument["exported"] = false;
}

Enjoy!
Chris

Leave a Reply