Movatterモバイル変換


[0]ホーム

URL:


Skip to main content

This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

Download Microsoft EdgeMore info about Internet Explorer and Microsoft Edge
Table of contentsExit editor mode

Quickstart: Send and receive messages from an Azure Event Grid namespace topic (.NET)

Feedback

In this article

In this quickstart, you do the following steps:

  1. Create an Event Grid namespace, using the Azure portal.
  2. Create an Event Grid namespace topic, using the Azure portal.
  3. Create an event subscription, using the Azure portal.
  4. Write a .NET console application to send a set of messages to the topic
  5. Write a .NET console application to receive those messages from the topic.

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.

Prerequisites

If you're new to the service, seeEvent Grid overview before you do this quickstart.

  • Azure subscription. To use Azure services, including Azure Event Grid, you need a subscription. If you don't have an existing Azure account, you can sign up for afree trial.
  • Visual Studio 2022. The sample application makes use of new features that were introduced in C# 10. To use the latest syntax, we recommend that you install .NET 6.0, or higher and set the language version tolatest. If you're using Visual Studio, versions before Visual Studio 2022 aren't compatible with the tools needed to build C# 10 projects.

Create a namespace in the Azure portal

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:

  1. Sign in to theAzure portal.

  2. In the search box, enterEvent Grid Namespaces and selectEvent Grid Namespaces from the results.

    Screenshot showing Event Grid Namespaces in the search results.

  3. On theEvent Grid Namespaces page, select+ Create.

    Screenshot showing Event Grid Namespaces page with the Create button on the toolbar selected.

  4. On theBasics page, follow these steps.

    1. Select the Azure subscription in which to create the namespace.

    2. Select an existingResource group or create a resource group.

    3. Enter aName for the namespace.

    4. Select theLocation for the namespace.

    5. SelectReview + create.

      Screenshot showing the Basics tab of Create namespace page.

  5. On theReview + create tab, review your settings. Then selectCreate.

  6. On theDeployment succeeded page, selectGo to resource to navigate to your namespace.

Create a namespace topic

  1. 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.

  2. On theEvent Grid Namespace page, underEvent broker, selectTopics.

  3. On theTopics page, select+ Topic.

    Screenshot showing Event Grid namespace topic creation.

  4. On theCreate Topic page, type the name of the topic you want to create and selectCreate.

    Screenshot showing Event Grid namespace topic creation basics.

Create an event subscription

  1. 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.

    Screenshot showing Event Grid topics page with a topic selected.

  2. On theEvent Grid Namespace Topic page, selectSubscriptions option in theEntities section on the left menu.

  3. On theSubscriptions page, select "+ Subscription" button on the command bar.

    Screenshot showing Event Grid event subscription create.

  4. In theBasics tab, follow these steps:

    1. Enter aname for the subscription you want to create

    2. Confirm that thedelivery schema is setCloud Events v1.0.

    3. Confirm that thedelivery mode is set toQueue (pull mode).

    4. SelectNext: Filters at the bottom of the page.

      Screenshot showing Event Grid event subscription create basics.

  5. 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.

    Screenshot showing Event Grid event subscription create filters.

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

    Screenshot showing Event Grid event subscription create additional features.

  7. SelectCreate to create the event subscription.

Authenticate the app to Azure

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:

  1. On theEvent Grid Namespace page, selectTopics.

  2. Select the topic you need to access.

  3. 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.

    Screenshot that shows the access key for an Event Grid topic.

Launch Visual Studio

Launch Visual Studio. If you see theGet started window, select theContinue without code link in the right pane.

Send messages to the topic

This section shows you how to create a .NET console application to send messages to an Event Grid topic.

Create a console application

  1. In Visual Studio, selectFile ->New ->Project menu.

  2. 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.

    1. SelectC# for the programming language.

    2. SelectConsole for the type of the application.

    3. SelectConsole App from the results list.

    4. Then, selectNext.

      Screenshot showing the Create a new project dialog box with C# and Console selected.

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

    Screenshot showing the solution and project names in the Configure your new project dialog box.

  4. On theAdditional information page, selectCreate to create the solution and the project.

Add the NuGet packages to the project

  1. SelectTools >NuGet Package Manager >Package Manager Console from the menu.

  2. Run the following command to install theAzure.Messaging.EventGrid NuGet package:

    Install-Package Azure.Messaging.EventGrid.Namespaces

Add code to send event to the namespace topic

  1. Replace 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; }}
  2. Build the project, and ensure that there are no errors.

  3. 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.

  4. In the Azure portal, follow these steps:

    1. Navigate to your Event Grid namespace.

    2. On theOverview page, you see the number of events posted to the namespace in the chart.

      Screenshot showing the Event Grid Namespace page in the Azure portal.

Pull messages from the topic

In this section, you create a .NET console application that receives messages from the topic.

Create a project to receive the published CloudEvents

  1. In the Solution Explorer window, right-click theEventGridQuickStart solution, point toAdd, and selectNew Project.
  2. SelectConsole application, and selectNext.
  3. EnterEventReceiver for theProject name, and selectCreate.
  4. In theSolution Explorer window, right-clickEventReceiver, and selectSet as a Startup Project.

Add the NuGet packages to the project

  1. SelectTools >NuGet Package Manager >Package Manager Console from the menu.

  2. 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

    Screenshot showing EventReceiver project selected in the Package Manager Console.

Add the code to receive events from the topic

In this section, you add code to retrieve messages from the queue.

  1. 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("-----------------");
  2. 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; }}
  3. In theSolution Explorer window, right-clickEventReceiver project, and selectSet as Startup project.

  4. Build the project, and ensure that there are no errors.

  5. Run theEventReceiver application and confirmation you see the three events in the output window.

    Screenshot showing the output from the Receiver app.

Clean up resources

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.

Related topics

See.NET API reference.


Feedback

Was this page helpful?

YesNoNo

Need help with this topic?

Want to try using Ask Learn to clarify or guide you through this topic?

Suggest a fix?

  • Last updated on

In this article

Was this page helpful?

YesNo
NoNeed help with this topic?

Want to try using Ask Learn to clarify or guide you through this topic?

Suggest a fix?