In this article, let’s create Azure Event Grid resources using Azure CLI, register Event Grid resource provider and then configure topic and endpoint. Build a .NET console application using .NET client library to send custom events to Event Grid topic. Validate that event is successfully routed to the endpoint in web application.

Following tasks are performed in this exercise:

Create Azure Event Grid resources using Azure CLI

First basic task is to create and make ready Azure Event Grid resources to Azure using Azure CLI. Azure CLI (Azure Cloud Shell) is used to create the required resources. Azure CLI is the free Bash shell which can be run directly within the Azure portal. That is preinstalled and configured within the account. Perform the below steps one by one to achieve this.

Use Azure CLI (Azure Cloud Shell)

It is a free Bash shell which can be run directly within the Azure portal. It is preinstalled and configured within an account.

az group create \ 
     --name myResourceGroup1 \ 
     --location eastus2 
let rNum=$RANDOM
     resourceGroup=myResourceGroup1
     location=eastus2
     topicName="mytopic-evgtopic-${rNum}"
     siteName="evgsite-${rNum}"
     siteURL="https://${siteName}.azurewebsites.net"

Register Event Grid resource provider

Azure Resource Provider is a service which defines and manages specific type resources in Azure. Microsoft.EventGrid namespace is required to registered for the application. az provider register command is used to register namespaces as like below. This command will take few minutes to complete the registration process.

az provider register \
     --namespace Microsoft.EventGrid 

Configure Topic and Endpoint

In this section, lets create topic in event grid and create a message endpoint, and then subscribe to topic. One by one perform the following three steps to achieve this.

Create Topic in Event Grid

az eventgrid topic create command is used to create a topic and it will be used in .NET code later on in Event Grid. Name must be a unique name as it is a part of DNS entry.

az eventgrid topic create \
     --name $topicName \
     --location $location \
     --resource-group $resourceGroup

Create Message Endpoint

Now, create an endpoint for event message. Endpoint is used to take actions based on the event data. az deployment group create command is used to create a deployment at resource group from the remote template file. Deployed solution contains App Service plan, App Service web application and source code from the GitHub repository.

az deployment group create \
     --name myDeploymentGroup1 \
     --resource-group $resourceGroup \
     --template-uri "https://raw.githubusercontent.com/Azure-Samples/azure-event-grid-viewer/main/azuredeploy.json" \
     --parameters siteName=$siteName hostingPlanName=viewerhost

Subscribe to Topic

Once, message endpoint is created and ready to use next one task is to subscribe to the topic. az eventgrid event-subscription create command is used to subscribe to a topic specified. Subscribe to Event Grid topic is used to tell Event Grid which events to be tracked and where to send such events. Following script retrieves subscription ID from the account and used in next command to create the event subscription.

let endpoint="${siteURL}/api/updates" \
     topicId=$(az eventgrid topic show --resource-group $resourceGroup \
     --name $topicName --query "id" --output tsv)

az eventgrid event-subscription create \
     --source-resource-id $topicId \
     --name TopicSubscription \
     --endpoint $endpoint

Send event using .NET Client Library

Next step is to set-up the .NET console application to send an event by using .NET Client Library. Perform the following steps one by one using Cloud Shell to achieve this.

.NET Project Setup

Set up one console application to route events to custom endpoint with Azure Event Grid using .NET Client Library.

mkdir eventgrid1
cd eventgrid1
dotnet add package Azure.Messaging.EventGrid
dotnet add package dotenv.net

Configure Application

Let's create and update .env file. env file holds the secrets such as topic endpoint and access key to be used in .NET console application in next section. Hence, first retrieve the topic endpoint and access key to add into the .env file to hold the secrets.

az eventgrid topic show \
     --name $topicName  \
     -g $resourceGroup  \
     --query "endpoint"  \
     --output tsv
az eventgrid topic key list \
     --name $topicName \
     -g $resourceGroup \
     --query "key1"  \
     --output tsv
touch .env
code .env 
TOPIC_ENDPOINT="MY_TOPIC_ENDPOINT"
TOPIC_ACCESS_KEY="MY_TOPIC_ACCESS_KEY"

Application Code

Add the below code into the project and replace template code in Program.cs file by using editor in Cloud Shell. Here by with this article a complete code of Program.cs file is attached.

code Program.cs
using Azure.Messaging.EventGrid;
using dotenv.net;

// Load environment variables from the .env file 
DotEnv.Load();
var envVariables = DotEnv.Read();

// Retrieve the Event Grid topic endpoint and access key from the environment variables
var topicEndpoint = envVariables["TOPIC_ENDPOINT"];
var topicAccessKey = envVariables["TOPIC_ACCESS_KEY"];

// Validate required environment variables are set or not?
if (string.IsNullOrEmpty(topicEndpoint) || string.IsNullOrEmpty(topicAccessKey))
{
     Console.WriteLine("Set TOPIC_ENDPOINT and TOPIC_ACCESS_KEY environment variables in .env file. Press any key to continue!");
     Console.ReadLine();
     return;
}

// Start asynchronous process to send Event Grid event 
ProcessAsync().GetAwaiter().GetResult();

async Task ProcessAsync()
{
     // Create EventGridPublisherClient object to send events to specified topic
     EventGridPublisherClient objEventGridPublisherClient = new EventGridPublisherClient
          (new Uri(topicEndpoint),
          new Azure.AzureKeyCredential(topicAccessKey));

     // Create EventGridEvent object with sample details
     var objEventGridEvent = new EventGridEvent(
          subject: "TestingSubject1",
          eventType: "TestingEventType1",
          dataVersion: "1.0",
          data: new { Message = "This message is from the event grid!" }
     );    

     // Send event to Event Grid
     await objEventGridPublisherClient.SendEventAsync(objEventGridEvent);
     Console.WriteLine("Event has been sent successfully. Press any key to continue!");
     Console.ReadLine();
}

Sign in to Azure and Run application

Now application is ready to run. One by one execute the following commands in Azure CLI to run an application and perform the mentioned steps to verify the result outcomes.

az login
dotnet run
Event has been sent successfully. Press any key to continue!

Clean up resources

Once finished the exercise its recommended to delete cloud resources are being created to avoid the unnecessary resource usage and any future costs. Deleting a resource group will delete all resources contained within it. Perform following steps one by one into Azure Portal to achieve this:

One can also clean up resources using Azure CLI as following:

Delete event subscription - az eventgrid event-subscription delete command is used to remove event subscription for an Azure subscription.

az eventgrid event-subscription delete \
     --name TopicSubscription \
     --source-resource-id $topicId 

Delete deployment group - az deployment group command is used to remove a deployment at resource group.

az deployment group delete \
     --name myDeploymentGroup1 \
     --resource-group $resourceGroup \

Delete topic - az eventgrid topic delete command is used to delete a topic.

az eventgrid topic delete \
     --name $topicName \
     --resource-group $resourceGroup

Delete resource group - az group delete command is used to remove resource group.

az group delete \
     --name myResourceGroup1

Summary

Here, a complete process flow is described to route events to custom endpoint with Azure Event Grid using .NET Client Library. Azure Event Grid resource is created using Azure CLI, registered Event Grid resource provider and then configured topic and endpoint. A .NET console application is created to send the custom events to Event Grid topic. Validated that event is successfully routed to the endpoint or not. Finally, resources are cleaned up. A complete code of Program.cs file is attached with this article. Following is the list of key commands used in this article: