Skip to main content

Using azure event gird with a function app

Introduction

In this tutorial we will set up a simple azure event grid topic, with an function app as a subscriber to the topic. The function app will just log the messages, so we can se that it picked up the event.

Setting things up

First step is to create a resource group where we can add all the azure services we need

az group create --name myresourcegroup  --location norwayeast
We need to set up a storage account that can be used bye the function app.

az storage account create --name mystorageaccount --resource-group myresourcegroup --location eastus --sku Standard_LRS

Now that we have a storage account we can make the function app. Here we will set it up to be able to run .Net 6 functions

az functionapp create --name myFunctionApp --resource-group myresourcegroup --consumption-plan-location eastus --runtime dotnet --runtime-version 6.0 --functions-version 4 --storage-account mystorageaccount 

We have set up everything we need to create and deploy the function app. So now we can code it and call it.

The function app code:

using System;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.EventGrid;
using Microsoft.Extensions.Logging;
using Azure.Messaging.EventGrid;

namespace Mgmo.Functions
{
    public static class MgmoEventGridLogger
    {
        [FunctionName("MgmoEventGridLogger")]
        public static void Run([EventGridTrigger] EventGridEvent eventGridEvent, ILogger log)
        {
            log.LogInformation($"A event happed with the data {eventGridEvent.Data.ToString()}");
        }
    }
}

If you what no read more about coding function apps, this can be a good starting point.
Create a C# function using Visual Studio Code - Azure Functions | Microsoft Learn

One important set up if you want to teste the function app local is to add a connection string to a storage account in local.setting.json. I used the azure storage emulator, so I do not need to pay for a storage account while I'm developing. You can also just use the storage account created in this example. 

{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "",
    "FUNCTIONS_WORKER_RUNTIME": "dotnet"
  }
}

Deployed the function app using Visual Studio Code. 









To get the tools to deploy and work with functions apps in Visual Studio Code install this extension

Now that the function app is set up we can set up the event grid topic and subscription.

To set up the event grid use this command:

az eventgrid topic create --name myeventgridtopicname --resource-group myresourcegroup  --location norwayeast

Then to set up the subscription:

az eventgrid topic event-subscription create -n myeventgridtopicname -g mgmofunctionappsrg --topic-name myresourcegroup --endpoint /subscriptions/{subscriptionId}/resourceGroups/{resourcegroup}/providers/Microsoft.Web/sites/{functionappname}/functions/{functionname} --endpoint-type azurefunction

Now that you have set up the Azure resources needed to run the example we can test the event grid by creating an event using Postman.

An event grid message has to follow a specific "EventGridEvent" schema. Here is more information about the full schema https://learn.microsoft.com/en-us/azure/event-grid/event-schema 

Here in this example we are using the simplest form: 

[
  {
    "subject": "Test",
    "eventType": "CallFunctionApp",
    "eventTime": "2023-06-24T18:41:00.9584103Z",
    "id": "831e2t1650-001e-001b-66ab-eeb76e069631",
    "data": {
      "test": "Hello World"
    }
  }
]

The body is ready so we can set up the rest of the http request. The method used is a POST, with a security header "aeg-sas-key:{Key1}". On can get the key from the Evnet Grid Topic unser Access keys in Azure 










Set the header under Headers in postman like this










The url to call can be found in the Event Grid Topic Overview under "Topic Endpoint"







When all is set up in postman try to call the post request. The response has no body, but if the call was successful it will return with the http status code 200.

To see the message logged, go into the function app logs, under monitoring in the function. I may take some time before the message is visible (up to 5 minutes)









So that's it. Now you can set up custom event grids in azure, that can be picked up by an azure function and handled there. 

Comments

Popular posts from this blog

Getting the script folder in PowerShell

Today I needed to call another script file in the same folder as the main script. After a little searching on the web I found "$MyInvocation.MyCommand.Path". "$MyInvocation.MyCommand.Path" returns the path to the current script, With that I was able to get the current folder using Get-Item. This is my test scripts: ToRun.ps1: Write-Host $MyInvocation.MyCommand.Path $scriptDirectory  = (Get-Item $MyInvocation.MyCommand.Path).DirectoryName $scriptName = "HelloWorld.ps1" Write-Host calling $scriptName in $scriptDirectory & ($scriptDirectory + '\' + $scriptName) HelloWorld.ps1: Write-Host "Hello word" After running the script the output was: calling HelloWorld.ps1 in C:\scriptFun Hello word Simple but useful.

Separate frontend 1: Trying to separate GUI layer and data business layer.

I have seen in some projects where I have been part of. The dependency injection is done in the presentation part of the application. That can be the API front or the GUI part like in a ASP.Net web application. The way this is done is to have some interfaces to separate the business from the data layers. Often by having the interfaces for them self in a separate project. Then the presentation layer references the business layer, interfaces and data layer, and connects it all together using dependency injection. This makes it easier to test, and change storage or parts of the application. As the injector can just inject new implementations of the interfaces.  But to me that feels like the presentation layer has two large responsibilities,  to present data and connect all the different parts together. What if you needed to change the presentation.  Then you would have to implement the injections also. You can't just switch out the presentation or add new ones. What if the o...