Publishing Events with the Event Grid .NET SDK

Azure Event Grid is now GA and along with it comes a nice collection of SDKs. This blog post will demonstrate the .NET SDK for publishing events.

The code for this post can be found in the following GitHub repository: https://github.com/dbarkol/azure-event-grid-samples.

Getting Started

We’ll need to provision a few things in Azure before using the SDK. For this, I’ll use the Azure CLI rather than go through the portal.

(1) Create a resource group:

az group create --name sdkdemo --location westus2

(2) Create a custom topic:

az eventgrid topic create     
  --name <topic-name>        
  --resource-group sdkdemo    
  --location westus2

(3) Retrieve the list of keys associated with the custom topic:

az eventgrid topic key list 
   --name <topic-name>
   --resource-group sdkdemo

Make a copy of one of the keys as well as the custom topic endpoint – we’ll need them for the event subscription.

(4) Create a RequestBin or Hookbin URL. Keep in mind that these are great sites for demos and basic testing. Do not expect these sites to display and capture each event, especially if you are sending a large collection of events within a short period of time.

Note: RequestBin no longer offers a hosted solution. You can try Hookbin or host your own with this alternative:

(5) Create an event subscription using one of the URLs from the previous step:

az eventgrid event-subscription create 
   --topic-name <topic-name>
   --name testsub 
   --endpoint <subscription-url> 
   --resource-group sdkdemo

Using the SDK from Visual Studio

For this example, we’ll use a simple console application that targets the .NET Framework. Using the Package Manager Console, we can add a reference to the NuGet package with the following command:

Install-Package Microsoft.Azure.EventGrid -Version 1.1.0-preview

Note that at the time of this post, the latest version of the package is set to 1.1.0-preview. To keep track of version history, see: https://www.nuget.org/packages/Microsoft.Azure.EventGrid.

Publishing an Event

Now, let’s get to the code! We’ll start with a basic class that has a few properties. This will be the payload we want to pass along with the event in the data property. For more details about the schema, please review: https://docs.microsoft.com/en-us/azure/event-grid/event-schema.

namespace PublishEvents.Data
{
  public class Musician
  {
    public string Name { get; set; }
    public string Instruments { get; set; }
  }
}

And now, the code that publishes the event:

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Azure.EventGrid;
using Microsoft.Azure.EventGrid.Models;
using PublishEvents.Data;

namespace PublishEvents
{
  internal class Program
  {
	// The custom topic host name
	// Example: {topicname}.westus2-1.eventgrid.azure.net
	private const string TopicHostName = "{topic-host-name}";

	// Custom topic access key
	private const string TopicKey = "{custom-topic-access-key}";

	private static void Main(string[] args)
	{
		PublishEvents().Wait();
	}

	private static async Task PublishEvents()
	{
		// Create service credential with the topic credential
		// class and custom topic access key
		ServiceClientCredentials credentials =
                       new TopicCredentials(TopicKey);

		// Create an instance of the event grid client class
		var client = new EventGridClient(credentials);

		// Retrieve a collection of events
		var events = GetEvents();

		// Publish the events
		await client.PublishEventsAsync(
			TopicHostName,
			events);
	}

	private static IList GetEvents()
	{
		// Return a list of events
		var events = new List
		{
			new EventGridEvent()
			{
				Id = Guid.NewGuid().ToString(),
				Data = new Musician()
				{
					Name = "Eddie Van Halen",
					Instruments = "Guitar, Keyboards"
				},
				EventTime = DateTime.Now,
				EventType = "EventGrid.Sample.MusicianAdded",
				Subject = "Musicians",
				DataVersion = "1.0"
			},
			new EventGridEvent()
			{
				Id = Guid.NewGuid().ToString(),
				Data = new Musician()
				{
					Name = "Slash",
					Instruments = "Guitar"
				},
				EventTime = DateTime.Now,
				EventType = "EventGrid.Sample.MusicianAdded",
				Subject = "Musicians",
				DataVersion = "1.0"
			}
		};

		return events;
	}
  }
}

Reviewing the Events

Note: If you are looking for an alternative to Request Bin, use this ASP.NET Core site to view incoming messages: https://madeofstrings.com/2018/03/14/azure-event-grid-viewer-with-asp-net-core-and-signalr/

An event sent to a Request Bin subscription looks like:

requestbin1

A Hookbin subscription:

hookbin1

 

Resources

 

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s