CommunityRédaction et éditiongithub.com

microsoft/azure-eventgrid-dotnet

SDK Azure Event Grid pour .NET. Bibliothèque client pour publier et consommer des événements avec Azure Event Grid. Utilisé pour les architectures événementielles, la messagerie pub/sub, CloudEvents et EventGridEvents.

Qu'est-ce que azure-eventgrid-dotnet ?

Cette compétence fournit un kit de développement logiciel (SDK) .NET complet pour interagir avec Azure Event Grid, le service de routage d'événements hautement évolutif d'Azure. Elle permet aux développeurs de publier des événements sur des rubriques (topics), des domaines et des espaces de noms (namespaces) Event Grid, ainsi que de consommer des événements par tirage (pull delivery) ou via des déclencheurs Azure Functions. La compétence prend en charge deux schémas d'événements principaux : le schéma natif `EventGridEvent` et le standard industriel `CloudEvent`, offrant une flexibilité d'intégration. Elle inclut des exemples de code détaillés pour l'authentification (clé API, jeton Entra ID, SAS), la publication d'événements uniques ou par lots, la réception et l'accusé de réception d'événements (pull delivery) ainsi que la gestion des erreurs et des reprises. La compétence est conçue pour fonctionner avec divers agents d'IA (tels que Claude Code, Cursor, Codex) qui peuvent utiliser ces instructions pour générer du code de publication ou de consommation d'événements dans un contexte .NET.

Compatible avec~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/microsoft/agent-skills/tree/main/.github/plugins/azure-sdk-dotnet/skills/azure-eventgrid-dotnet

Installed? Explore more Rédaction et édition skills: steipete/notion, langchain-ai/langchain, bytedance/podcast-generation · View all 6 →

Demander à votre IA préférée

Ouvre une nouvelle conversation avec cette compétence d'agent déjà préchargée.

Documentation

Azure.Messaging.EventGrid (.NET)

Bibliothèque cliente pour publier des événements sur les rubriques, domaines et espaces de noms Azure Event Grid.

Installation

# Pour les rubriques et domaines (livraison par push)
dotnet add package Azure.Messaging.EventGrid

# Pour les espaces de noms (livraison par pull)
dotnet add package Azure.Messaging.EventGrid.Namespaces

# Pour l'interopérabilité CloudNative CloudEvents
dotnet add package Microsoft.Azure.Messaging.EventGrid.CloudNativeCloudEvents

Version actuelle : 4.28.0 (stable)

Variables d'environnement

EVENT_GRID_TOPIC_ENDPOINT=https://<topic-name>.<region>.eventgrid.azure.net/api/events  # Requis : point de terminaison de la rubrique ou du domaine Event Grid
EVENT_GRID_TOPIC_KEY=<access-key>  # Requis uniquement pour l'authentification AzureKeyCredential
EVENT_GRID_NAMESPACE_ENDPOINT=https://<namespace>.<region>.eventgrid.azure.net  # Optionnel : point de terminaison de l'espace de noms Event Grid
EVENT_GRID_TOPIC_NAME=<topic-name>  # Requis : nom de la rubrique Event Grid
EVENT_GRID_SUBSCRIPTION_NAME=<subscription-name>  # Optionnel : nom de l'abonnement Event Grid
AZURE_TOKEN_CREDENTIALS=prod  # Requis uniquement si DefaultAzureCredential est utilisé en production

Hiérarchie des clients

Livraison par poussée (Rubriques/Domaines)
└── EventGridPublisherClient
    ├── SendEventAsync(EventGridEvent)
    ├── SendEventsAsync(IEnumerable<EventGridEvent>)
    ├── SendEventAsync(CloudEvent)
    └── SendEventsAsync(IEnumerable<CloudEvent>)

Livraison par tirage (Espaces de noms)
├── EventGridSenderClient
│   └── SendAsync(CloudEvent)
└── EventGridReceiverClient
    ├── ReceiveAsync()
    ├── AcknowledgeAsync()
    ├── ReleaseAsync()
    └── RejectAsync()

Authentification

Authentification par clé API

using Azure;
using Azure.Messaging.EventGrid;

EventGridPublisherClient client = new(
    new Uri("https://mytopic.eastus-1.eventgrid.azure.net/api/events"),
    new AzureKeyCredential("<access-key>"));

Jeton d'identification Microsoft Entra

using Azure.Identity;
using Azure.Messaging.EventGrid;

// Développement local : DefaultAzureCredential. Production : définir AZURE_TOKEN_CREDENTIALS=prod ou AZURE_TOKEN_CREDENTIALS=<credential_spécifique>
var credential = new DefaultAzureCredential(
    DefaultAzureCredential.DefaultEnvironmentVariableName
);
// Ou utiliser directement un credential spécifique en production :
// Voir https://learn.microsoft.com/dotnet/api/overview/azure/identity-readme?view=azure-dotnet#credential-classes
// var credential = new ManagedIdentityCredential();
EventGridPublisherClient client = new(
    new Uri("https://mytopic.eastus-1.eventgrid.azure.net/api/events"),
    credential);

Authentification par jeton SAS

string sasToken = EventGridPublisherClient.BuildSharedAccessSignature(
    new Uri(topicEndpoint),
    DateTimeOffset.UtcNow.AddHours(1),
    new AzureKeyCredential(topicKey));

var sasCredential = new AzureSasCredential(sasToken);
EventGridPublisherClient client = new(
    new Uri(topicEndpoint),
    sasCredential);

Publication d'événements

Schéma EventGridEvent

EventGridPublisherClient client = new(
    new Uri(topicEndpoint),
    new AzureKeyCredential(topicKey));

// Événement unique
EventGridEvent egEvent = new(
    subject: "orders/12345",
    eventType: "Order.Created",
    dataVersion: "1.0",
    data: new { OrderId = "12345", Amount = 99.99 });

await client.SendEventAsync(egEvent);

// Lot d'événements
List<EventGridEvent> events = new()
{
    new EventGridEvent(
        subject: "orders/12345",
        eventType: "Order.Created",
        dataVersion: "1.0",
        data: new OrderData { OrderId = "12345", Amount = 99.99 }),
    new EventGridEvent(
        subject: "orders/12346",
        eventType: "Order.Created",
        dataVersion: "1.0",
        data: new OrderData { OrderId = "12346", Amount = 149.99 })
};

await client.SendEventsAsync(events);

Schéma CloudEvent

CloudEvent cloudEvent = new(
    source: "/orders/system",
    type: "Order.Created",
    data: new { OrderId = "12345", Amount = 99.99 });

cloudEvent.Subject = "orders/12345";
cloudEvent.Id = Guid.NewGuid().ToString();
cloudEvent.Time = DateTimeOffset.UtcNow;

await client.SendEventAsync(cloudEvent);

// Lot de CloudEvents
List<CloudEvent> cloudEvents = new()
{
    new CloudEvent("/orders", "Order.Created", new { OrderId = "1" }),
    new CloudEvent("/orders", "Order.Updated", new { OrderId = "2" })
};

await client.SendEventsAsync(cloudEvents);

Publication vers un domaine Event Grid

// Les événements doivent spécifier la propriété Topic pour le routage au sein du domaine
List<EventGridEvent> events = new()
{
    new EventGridEvent(
        subject: "orders/12345",
        eventType: "Order.Created",
        dataVersion: "1.0",
        data: new { OrderId = "12345" })
    {
        Topic = "orders-topic"  // Nom de la rubrique du domaine
    },
    new EventGridEvent(
        subject: "inventory/item-1",
        eventType: "Inventory.Updated",
        dataVersion: "1.0",
        data: new { ItemId = "item-1" })
    {
        Topic = "inventory-topic"
    }
};

await client.SendEventsAsync(events);

Sérialisation personnalisée

using System.Text.Json;

var serializerOptions = new JsonSerializerOptions
{
    PropertyNamingPolicy = JsonNamingPolicy.CamelCase
};

var customSerializer = new JsonObjectSerializer(serializerOptions);

EventGridEvent egEvent = new(
    subject: "orders/12345",
    eventType: "Order.Created",
    dataVersion: "1.0",
    data: customSerializer.Serialize(new OrderData { OrderId = "12345" }));

await client.SendEventAsync(egEvent);

Livraison par tirage (Espaces de noms)

Envoyer des événements à une rubrique d'espace de noms

using Azure;
using Azure.Messaging;
using Azure.Messaging.EventGrid.Namespaces;

var senderClient = new EventGridSenderClient(
    new Uri(namespaceEndpoint),
    topicName,
    new AzureKeyCredential(topicKey));

// Envoyer un événement unique
CloudEvent cloudEvent = new("employee_source", "Employee.Created", 
    new { Name = "John", Age = 30 });
await senderClient.SendAsync(cloudEvent);

// Envoyer un lot
await senderClient.SendAsync(new[]
{
    new CloudEvent("source", "type", new { Name = "Alice" }),
    new CloudEvent("source", "type", new { Name = "Bob" })
});

Recevoir et traiter des événements

var receiverClient = new EventGridReceiverClient(
    new Uri(namespaceEndpoint),
    topicName,
    subscriptionName,
    new AzureKeyCredential(topicKey));

// Recevoir des événements
ReceiveResult result = await receiverClient.ReceiveAsync(maxEvents: 10);

List<string> lockTokensToAck = new();
List<string> lockTokensToRelease = new();

foreach (ReceiveDetails detail in result.Details)
{
    CloudEvent cloudEvent = detail.Event;
    string lockToken = detail.BrokerProperties.LockToken;
    
    try
    {
        // Traiter l'événement
        Console.WriteLine($"Événement : {cloudEvent.Type}, Données : {cloudEvent.Data}");
        lockTokensToAck.Add(lockToken);
    }
    catch (Exception)
    {
        // Libérer pour une nouvelle tentative
        lockTokensToRelease.Add(lockToken);
    }
}

// Accuser réception des événements traités avec succès
if (lockTokensToAck.Any())
{
    await receiverClient.AcknowledgeAsync(lockTokensToAck);
}

// Libérer les événements pour une nouvelle tentative
if (lockTokensToRelease.Any())
{
    await receiverClient.ReleaseAsync(lockTokensToRelease);
}

Rejeter des événements (Lettre morte)

// Rejeter les événements qui ne peuvent pas être traités
await receiverClient.RejectAsync(new[] { lockToken });

Consommation d'événements (Azure Functions)

Déclencheur EventGridEvent

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

public static class EventGridFunction
{
    [FunctionName("ProcessEventGridEvent")]
    public static void Run(
        [EventGridTrigger] EventGridEvent eventGridEvent,
        ILogger log)
    {
        log.LogInformation($"Type d'événement : {eventGridEvent.EventType}");
        log.LogInformation($"Sujet : {eventGridEvent.Subject}");
        log.LogInformation($"Données : {eventGridEvent.Data}");
    }
}

Déclencheur CloudEvent

using Azure.Messaging;
using Microsoft.Azure.Functions.Worker;

public class CloudEventFunction
{
    [Function("ProcessCloudEvent")]
    public void Run(
        [EventGridTrigger] CloudEvent cloudEvent,
        FunctionContext context)
    {
        var logger = context.GetLogger("ProcessCloudEvent");
        logger.LogInformation($"Type d'événement : {cloudEvent.Type}");
        logger.LogInformation($"Source : {cloudEvent.Source}");
        logger.LogInformation($"Données : {cloudEvent.Data}");
    }
}

Analyse d'événements

Analyser EventGridEvent

// Depuis une chaîne JSON
string json = "..."; // Charge utile webhook Event Grid
EventGridEvent[] events = EventGridEvent.ParseMany(BinaryData.FromString(json));

foreach (EventGridEvent egEvent in events)
{
    if (egEvent.TryGetSystemEventData(out object systemEvent))
    {
        // Gérer un événement système
        switch (systemEvent)
        {
            case StorageBlobCreatedEventData blobCreated:
                Console.WriteLine($"Blob créé : {blobCreated.Url}");
                break;
        }
    }
    else
    {
        // Gérer un événement personnalisé
        var customData = egEvent.Data.ToObjectFromJson<MyCustomData>();
    }
}

Analyser CloudEvent

CloudEvent[] cloudEvents = CloudEvent.ParseMany(BinaryData.FromString(json));

foreach (CloudEvent cloudEvent in cloudEvents)
{
    var data = cloudEvent.Data.ToObjectFromJson<MyEventData>();
    Console.WriteLine($"Type : {cloudEvent.Type}, Données : {data}");
}

Événements système

// Types d'événements système courants
using Azure.Messaging.EventGrid.SystemEvents;

// Événements Storage
StorageBlobCreatedEventData blobCreated;
StorageBlobDeletedEventData blobDeleted;

// Événements Resource
ResourceWriteSuccessEventData resourceCreated;
ResourceDeleteSuccessEventData resourceDeleted;

// Événements App Service
WebAppUpdatedEventData webAppUpdated;

// Événements Container Registry
ContainerRegistryImagePushedEventData imagePushed;

// Événements IoT Hub
IotHubDeviceCreatedEventData deviceCreated;

Référence des types clés

TypeObjectif
EventGridPublisherClientPublier sur des rubriques/domaines
EventGridSenderClientEnvoyer vers des rubriques d'espace de noms
EventGridReceiverClientRecevoir depuis des abonnements d'espace de noms
EventGridEventSchéma natif Event Grid
CloudEventSchéma CloudEvents 1.0
ReceiveResultRéponse de livraison par tirage
ReceiveDetailsÉvénement avec propriétés du broker
BrokerPropertiesJeton de verrouillage, nombre de livraisons

Comparaison des schémas d'événements

FonctionnalitéEventGridEventCloudEvent
StandardSpécifique AzureStandard CNCF
Champs obligatoiressubject, eventType, dataVersion, datasource, type
ExtensibilitéLimitéeAttributs d'extension
InteropérabilitéAzure uniquementMulti-plateforme

Bonnes pratiques

  1. Utilisez CloudEvents — Privilégiez CloudEvents pour les nouvelles implémentations (standard industriel)
  2. Regroupez les événements — Envoyez plusieurs événements en un seul appel pour plus d'efficacité
  3. Utilisez Entra ID — Préférez l'identité managée aux clés d'accès
  4. Gestionnaires idempotents — Les événements peuvent être livrés plusieurs fois
  5. Définissez la TTL des événements — Configurez la durée de vie pour les événements d'espace de noms
  6. Gérez les échecs partiels — Accusez réception/libérez les événements individuellement
  7. Utilisez la lettre morte — Configurez la lettre morte pour les événements en échec
  8. Validez les schémas — Validez les données d'événement avant le traitement

Gestion des erreurs

using Azure;

try
{
    await client.SendEventAsync(cloudEvent);
}
catch (RequestFailedException ex) when (ex.Status == 401)
{
    Console.WriteLine("Échec de l'authentification - vérifiez les informations d'identification");
}
catch (RequestFailedException ex) when (ex.Status == 403)
{
    Console.WriteLine("Échec de l'autorisation - vérifiez les autorisations RBAC");
}
catch (RequestFailedException ex) when (ex.Status == 413)
{
    Console.WriteLine("Charge utile trop volumineuse - max 1 Mo par événement, 1 Mo total par lot");
}
catch (RequestFailedException ex)
{
    Console.WriteLine($"Erreur Event Grid : {ex.Status} - {ex.Message}");
}

Modèle de basculement

try
{
    var primaryClient = new EventGridPublisherClient(primaryUri, primaryKey);
    await primaryClient.SendEventsAsync(events);
}
catch (RequestFailedException)
{
    // Basculement vers la région secondaire
    var secondaryClient = new EventGridPublisherClient(secondaryUri, secondaryKey);
    await secondaryClient.SendEventsAsync(events);
}

Kits SDK associés

SDKObjectifInstallation
Azure.Messaging.EventGridRubriques/Domaines (ce SDK)dotnet add package Azure.Messaging.EventGrid
Azure.Messaging.EventGrid.NamespacesLivraison par tiragedotnet add package Azure.Messaging.EventGrid.Namespaces
Azure.IdentityAuthentificationdotnet add package Azure.Identity
Microsoft.Azure.WebJobs.Extensions.EventGridDéclencheur Azure Functionsdotnet add package Microsoft.Azure.WebJobs.Extensions.EventGrid

Liens de référence

RessourceURL
Package NuGethttps://www.nuget.org/packages/Azure.Messaging.EventGrid
Référence APIhttps://learn.microsoft.com/dotnet/api/azure.messaging.eventgrid
Démarrage rapidehttps://learn.microsoft.com/azure/event-grid/custom-event-quickstart
Livraison par tiragehttps://learn.microsoft.com/azure/event-grid/pull-delivery-overview
Source GitHubhttps://github.com/Azure/azure-sdk-for-net/tree/main/sdk/eventgrid/Azure.Messaging.EventGrid

Individual skills in this repo

This repo contains 12 individual skills — each has its own dedicated page.

microsoft/azure-ai-agents-persistent-dotnet

Azure AI Agents Persistent SDK for .NET. Low-level SDK for creating and managing AI agents with threads, messages, runs, and tools. Use for agent CRUD, conversation threads, streaming responses, function calling, file search, and code interpreter. Triggers: "PersistentAgentsClient", "persistent agents", "agent threads", "agent runs", "streaming agents", "function calling agents .NET".

microsoft/azure-ai-document-intelligence-dotnet

Azure AI Document Intelligence SDK for .NET. Extract text, tables, and structured data from documents using prebuilt and custom models. Use for invoice processing, receipt extraction, ID document analysis, and custom document models. Triggers: "Document Intelligence", "DocumentIntelligenceClient", "form recognizer", "invoice extraction", "receipt OCR", "document analysis .NET".

microsoft/azure-ai-openai-dotnet

Azure OpenAI SDK for .NET. Client library for Azure OpenAI and OpenAI services. Use for chat completions, embeddings, image generation, audio transcription, and assistants. Triggers: "Azure OpenAI", "AzureOpenAIClient", "ChatClient", "chat completions .NET", "GPT-4", "embeddings", "DALL-E", "Whisper", "OpenAI .NET".

microsoft/azure-ai-projects-dotnet

Azure AI Projects SDK for .NET. High-level client for Azure AI Foundry projects including agents, connections, datasets, deployments, evaluations, and indexes. Use for AI Foundry project management, versioned agents, and orchestration. Triggers: "AI Projects", "AIProjectClient", "Foundry project", "versioned agents", "evaluations", "datasets", "connections", "deployments .NET".

microsoft/azure-ai-voicelive-dotnet

Azure AI Voice Live SDK for .NET. Build real-time voice AI applications with bidirectional WebSocket communication. Use for voice assistants, conversational AI, real-time speech-to-speech, and voice-enabled chatbots. Triggers: "voice live", "real-time voice", "VoiceLiveClient", "VoiceLiveSession", "voice assistant .NET", "bidirectional audio", "speech-to-speech".

microsoft/azure-eventhub-dotnet

Azure Event Hubs SDK for .NET. Use for high-throughput event streaming: sending events (EventHubProducerClient, EventHubBufferedProducerClient), receiving events (EventProcessorClient with checkpointing), partition management, and real-time data ingestion. Triggers: "Event Hubs", "event streaming", "EventHubProducerClient", "EventProcessorClient", "send events", "receive events", "checkpointing", "partition".

microsoft/azure-identity-dotnet

Azure Identity library for .NET. Authentication library for Azure SDK clients using Microsoft Entra ID. Use for DefaultAzureCredential, managed identity, service principals, and developer credentials. Triggers: "Azure Identity", "DefaultAzureCredential", "ManagedIdentityCredential", "ClientSecretCredential", "authentication .NET", "Azure auth", "credential chain".

microsoft/azure-kusto-graph

Build and query Kusto graphs from natural language. Covers transient graphs (make-graph), persistent graph models/snapshots, pattern matching (graph-match), shortest paths, connected components, and graph-to-table export. Generates the edges-first thinking: define edges, define node lookups, union, make-graph. WHEN: make-graph, graph-match, graph-shortest-paths, graph-to-table, graph-mark-components, persistent graph, graph model, graph snapshot, build a graph from data, find paths between nodes, pattern matching in graph, connected components, transient graph, Kusto graph, KQL graph.

microsoft/azure-kusto-irql

Compose IRQL (Incident Response Query Language) queries for Kusto cybersecurity investigations. Translates natural language hunting questions into composable IRQL pipelines using Get_*, Extract_*, and Enrich_* functions. WHEN: IRQL query, security hunt, threat hunting KQL, incident response query, compose hunting pipeline, failed logins, phishing investigation, lateral movement, process execution, file creation events.

microsoft/azure-kusto-irql-graph

Apply IRQL graph functions to KQL or IRQL query results for Kusto Explorer visualization. Generates Lift_To_Graph mappings and composes Graph_Render_View, Graph_Fold_By_Property, Extract_Node_*, Enrich_Node_*, and Enrich_Graph_* calls. Accepts a supplied query or limited basic natural-language source request; it is not a general natural-language-to-KQL/IRQL skill. WHEN: Lift_To_Graph, Graph_Render_View, Graph_Fold_By_Property, IRQL graph enrichment, graph mapping for existing query results, icon-decorated graph, fold graph nodes. Use azure-kusto-graph for native make-graph analysis, graph-match, shortest paths, components, or persistent graphs.

microsoft/azure-local

Plan, deploy, operate, and troubleshoot Azure Local (formerly Azure Stack HCI): sizing and prerequisites, Arc registration, lifecycle updates, workloads (Azure Local VMs, AKS on Azure Local, images, disks, logical networks), SDN and network security, and failure triage — starting read-only and confirming before risky changes. WHEN: Azure Local, Azure Stack HCI, Arc resource bridge, custom location, Azure Local VM, Arc VM, AKS on Azure Local, AKS hybrid, SDN, Lifecycle Manager, Azure Local update, disconnected site.

microsoft/azure-local-multi-rack

Plan, deploy, operate, and troubleshoot multi-rack (rack scale) deployments of Azure Local — preintegrated racks scaling to hundreds of machines, built on Network Fabric Controller, Cluster Manager, SAN storage, and managed network fabric. Use for the Microsoft.NetworkCloud and Microsoft.ManagedNetworkFabric control plane. NOT for standard 1-16 node Azure Local, and NOT for rack-aware clusters (two racks as availability zones, up to 8 nodes, synchronous replication) — those are standard scale. WHEN: multi-rack, rack scale Azure Local, aggregation rack, compute rack, Network Fabric Controller, NFC, Cluster Manager, network fabric, isolation domain, az networkcloud, az networkfabric, multi-rack logical network, multi-rack Arc VM.

Skills associés