This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
Note
Access to this page requires authorization. You can trysigning in orchanging directories.
Access to this page requires authorization. You can trychanging directories.
In this quickstart, you do the following steps:
Note
This quick start provides step-by-step instructions to implement a simple scenario of sending a batch of messages to an Event Grid Namespace Topic and then receiving them. For an overview of the .NET client library, seeAzure Event Grid client library for .NET. For more samples, seeEvent Grid .NET samples on GitHub.
If you're new to the service, seeEvent Grid overview before you do this quickstart.
latest. If you're using Visual Studio, versions before Visual Studio 2022 aren't compatible with the tools needed to build C# 10 projects.Anamespace in Azure Event Grid is a logical container for one or more topics, clients, client groups, topic spaces, and permission bindings. With an Azure Event Grid namespace, you can group together related resources and manage them as a single unit in your Azure subscription. A unique namespace allows you to have multiple resources in the same Azure region.
To create a namespace:
Sign in to theAzure portal.
In the search box, enterEvent Grid Namespaces and selectEvent Grid Namespaces from the results.

On theEvent Grid Namespaces page, select+ Create.

On theBasics page, follow these steps.
Select the Azure subscription in which to create the namespace.
Select an existingResource group or create a resource group.
Enter aName for the namespace.
Select theLocation for the namespace.
SelectReview + create.

On theReview + create tab, review your settings. Then selectCreate.
On theDeployment succeeded page, selectGo to resource to navigate to your namespace.
If you aren't on the Event Grid Namespace page, follow thecreate, view, and manage namespaces steps to view the namespace you want to use to create the topic.
On theEvent Grid Namespace page, underEvent broker, selectTopics.
On theTopics page, select+ Topic.
On theCreate Topic page, type the name of the topic you want to create and selectCreate.

If you are on theTopics page of your Event Grid namespace in the Azure portal, select your topic from the list of topics. If you are on theTopics page, follow instructions fromcreate, view, and manage a namespace topics to identify the topic you want to use to create the event subscription.
On theEvent Grid Namespace Topic page, selectSubscriptions option in theEntities section on the left menu.
On theSubscriptions page, select "+ Subscription" button on the command bar.
In theBasics tab, follow these steps:
Enter aname for the subscription you want to create
Confirm that thedelivery schema is setCloud Events v1.0.
Confirm that thedelivery mode is set toQueue (pull mode).
SelectNext: Filters at the bottom of the page.

In theFilters tab, add the names of the event types you want to filter in the subscription and add context attribute filters you want to use in the subscription. Then, selectNext: Additional features at the bottom of the page.

In theAdditional features tab, you can specify the event retention, maximum delivery count, lock duration, and dead-lettering settings.

SelectCreate to create the event subscription.
This quick start shows you ways of connecting to Azure Event Grid:connection string. This section shows you how to use a connection string to connect to an Event Grid namespace. If you're new to Azure, the connection string option is easier to follow. Creating a new Event Grid namespace automatically generates an initial primary and secondary key that each grant full control over all aspects of the namespace or topics. A client can use the connection string to connect to the Event Grid namespace. To copy the access keys for your namespace topic, follow these steps:
On theEvent Grid Namespace page, selectTopics.
Select the topic you need to access.
On theAccess keys page, select the copy button next toKey 1 or Key 2, to copy the access keys to your clipboard for later use. Paste this value into Notepad or some other temporary location.
Launch Visual Studio. If you see theGet started window, select theContinue without code link in the right pane.
This section shows you how to create a .NET console application to send messages to an Event Grid topic.
In Visual Studio, selectFile ->New ->Project menu.
On theCreate a new project dialog box, do the following steps: If you don't see this dialog box, selectFile on the menu, selectNew, and then selectProject.
SelectC# for the programming language.
SelectConsole for the type of the application.
SelectConsole App from the results list.
Then, selectNext.

EnterEventSender for the project name,EventGridQuickStart for the solution name, and then selectNext.

On theAdditional information page, selectCreate to create the solution and the project.
SelectTools >NuGet Package Manager >Package Manager Console from the menu.
Run the following command to install theAzure.Messaging.EventGrid NuGet package:
Install-Package Azure.Messaging.EventGrid.NamespacesReplace the contents ofProgram.cs with the following code. The important steps are outlined, with additional information in the code comments.
Important
Update placeholder values (<NAMESPACE-ENDPOINT> ,<TOPIC-NAME>,<TOPIC-ACCESS-KEY>) in the code snippet with your namespace endpoint, topic name, and topic key.
using Azure.Messaging;using Azure;using Azure.Messaging.EventGrid.Namespaces;// TODO: Replace the following placeholders with appropriate values// Endpoint of the namespace that you can find on the Overview page for your Event Grid namespace. Prefix it with https://.// Should be in the form: https://namespace01.eastus-1.eventgrid.azure.net. var namespaceEndpoint = "<NAMESPACE-ENDPOINT>";// Name of the topic in the namespacevar topicName = "<TOPIC-NAME>";// Access key for the topicvar topicKey = "<TOPIC-ACCESS-KEY>";// Construct the client using an Endpoint for a namespace as well as the access keyvar client = new EventGridSenderClient(new Uri(namespaceEndpoint), topicName, new AzureKeyCredential(topicKey));// Publish a single CloudEvent using a custom TestModel for the event data.var @ev = new CloudEvent("employee_source", "type", new TestModel { Name = "Bob", Age = 18 });await client.SendAsync(ev);// Publish a batch of CloudEvents.await client.SendAsync(new[] { new CloudEvent("employee_source", "type", new TestModel { Name = "Tom", Age = 55 }), new CloudEvent("employee_source", "type", new TestModel { Name = "Alice", Age = 25 })});Console.WriteLine("Three events have been published to the topic. Press any key to end the application.");Console.ReadKey();public class TestModel{ public string Name { get; set; } public int Age { get; set; }}Build the project, and ensure that there are no errors.
Run the program and wait for the confirmation message.
Three events have been published to the topic. Press any key to end the application.Important
In most cases, it will take a minute or two for the role assignment to propagate in Azure. In rare cases, it may take up toeight minutes. If you receive authentication errors when you first run your code, wait a few moments and try again.
In the Azure portal, follow these steps:
In this section, you create a .NET console application that receives messages from the topic.
SelectTools >NuGet Package Manager >Package Manager Console from the menu.
Run the following command to install theAzure.Messaging.EventGrid NuGet package. SelectEventReceiver for theDefault project if it's not already set.
Install-Package Azure.Messaging.EventGrid.Namespaces
In this section, you add code to retrieve messages from the queue.
Within theProgram class, add the following code:
Important
Update placeholder values (<NAMESPACE-ENDPOINT> ,<TOPIC-NAME>,<TOPIC-ACCESS-KEY>,<TOPIC-SUBSCRIPTION-NAME>) in the code snippet with your namespace endpoint, topic name, topic key, topic's subscription name.
using Azure;using Azure.Messaging;using Azure.Messaging.EventGrid.Namespaces;// TODO: Replace the following placeholders with appropriate values// Endpoint of the namespace that you can find on the Overview page for your Event Grid namespace// Example: https://namespace01.eastus-1.eventgrid.azure.net. var namespaceEndpoint = "<NAMESPACE-ENDPOINT>"; // Should be in the form: https://namespace01.eastus-1.eventgrid.azure.net. // Name of the topic in the namespacevar topicName = "<TOPIC-NAME>";// Access key for the topicvar topicKey = "<TOPIC-ACCESS-KEY>";// Name of the subscription to the topicvar subscriptionName = "<TOPIC-SUBSCRIPTION-NAME>";// Maximum number of events you want to receiveconst short MaxEventCount = 3;// Construct the client using an Endpoint for a namespace as well as the access keyvar client = new EventGridReceiverClient(new Uri(namespaceEndpoint), topicName, subscriptionName, new AzureKeyCredential(topicKey));// Receive the published CloudEvents. ReceiveResult result = await client.ReceiveAsync(MaxEventCount);Console.WriteLine("Received Response");Console.WriteLine("-----------------");Append the following methods to the end of theProgram class.
// handle received messages. Define these variables on the top.var toRelease = new List<string>();var toAcknowledge = new List<string>();var toReject = new List<string>();// Iterate through the results and collect the lock tokens for events we want to release/acknowledge/resultforeach (ReceiveDetails detail in result.Details){ CloudEvent @event = detail.Event; BrokerProperties brokerProperties = detail.BrokerProperties; Console.WriteLine(@event.Data.ToString()); // The lock token is used to acknowledge, reject or release the event Console.WriteLine(brokerProperties.LockToken); Console.WriteLine(); // If the event is from the "employee_source" and the name is "Bob", we are not able to acknowledge it yet, so we release it if (@event.Source == "employee_source" && @event.Data.ToObjectFromJson<TestModel>().Name == "Bob") { toRelease.Add(brokerProperties.LockToken); } // acknowledge other employee_source events else if (@event.Source == "employee_source") { toAcknowledge.Add(brokerProperties.LockToken); } // reject all other events else { toReject.Add(brokerProperties.LockToken); }}// Release/acknowledge/reject the eventsif (toRelease.Count > 0){ ReleaseResult releaseResult = await client.ReleaseAsync(toRelease); // Inspect the Release result Console.WriteLine($"Failed count for Release: {releaseResult.FailedLockTokens.Count}"); foreach (FailedLockToken failedLockToken in releaseResult.FailedLockTokens) { Console.WriteLine($"Lock Token: {failedLockToken.LockToken}"); Console.WriteLine($"Error Code: {failedLockToken.Error}"); Console.WriteLine($"Error Description: {failedLockToken.ToString}"); } Console.WriteLine($"Success count for Release: {releaseResult.SucceededLockTokens.Count}"); foreach (string lockToken in releaseResult.SucceededLockTokens) { Console.WriteLine($"Lock Token: {lockToken}"); } Console.WriteLine();}if (toAcknowledge.Count > 0){ AcknowledgeResult acknowledgeResult = await client.AcknowledgeAsync(toAcknowledge); // Inspect the Acknowledge result Console.WriteLine($"Failed count for Acknowledge: {acknowledgeResult.FailedLockTokens.Count}"); foreach (FailedLockToken failedLockToken in acknowledgeResult.FailedLockTokens) { Console.WriteLine($"Lock Token: {failedLockToken.LockToken}"); Console.WriteLine($"Error Code: {failedLockToken.Error}"); Console.WriteLine($"Error Description: {failedLockToken.ToString}"); } Console.WriteLine($"Success count for Acknowledge: {acknowledgeResult.SucceededLockTokens.Count}"); foreach (string lockToken in acknowledgeResult.SucceededLockTokens) { Console.WriteLine($"Lock Token: {lockToken}"); } Console.WriteLine();}if (toReject.Count > 0){ RejectResult rejectResult = await client.RejectAsync(toReject); // Inspect the Reject result Console.WriteLine($"Failed count for Reject: {rejectResult.FailedLockTokens.Count}"); foreach (FailedLockToken failedLockToken in rejectResult.FailedLockTokens) { Console.WriteLine($"Lock Token: {failedLockToken.LockToken}"); Console.WriteLine($"Error Code: {failedLockToken.Error}"); Console.WriteLine($"Error Description: {failedLockToken.ToString}"); } Console.WriteLine($"Success count for Reject: {rejectResult.SucceededLockTokens.Count}"); foreach (string lockToken in rejectResult.SucceededLockTokens) { Console.WriteLine($"Lock Token: {lockToken}"); } Console.WriteLine();}public class TestModel{ public string Name { get; set; } public int Age { get; set; }}In theSolution Explorer window, right-clickEventReceiver project, and selectSet as Startup project.
Build the project, and ensure that there are no errors.
Run theEventReceiver application and confirmation you see the three events in the output window.
Navigate to your Event Grid namespace in the Azure portal, and selectDelete on the Azure portal to delete the Event Grid namespace and the topic in it.
Was this page helpful?
Need help with this topic?
Want to try using Ask Learn to clarify or guide you through this topic?
Was this page helpful?
Want to try using Ask Learn to clarify or guide you through this topic?