CommunityEscrita e Ediçãogithub.com

microsoft/azure-eventgrid-dotnet

SDK do Azure Event Grid para .NET. Biblioteca cliente para publicar e consumir eventos com o Azure Event Grid. Use para arquiteturas orientadas a eventos, mensagens pub/sub, CloudEvents e EventGridEvents. Gatilhos: "Event Grid", "EventGridPublisherClient", "CloudEvent", "EventGridEvent", "publish events .NET", "orientado a eventos", "pub/sub".

O que é azure-eventgrid-dotnet?

Esta skill fornece a biblioteca cliente `Azure.Messaging.EventGrid` para .NET, permitindo que desenvolvedores publiquem eventos em tópicos, domínios e namespaces do Azure Event Grid, além de consumi-los por meio de entrega por push (tópicos/domínios) ou pull (namespaces). Suporta os esquemas nativos EventGridEvent e o padrão CloudEvents 1.0, com autenticação via chave de API, token SAS ou identidade gerenciada (Microsoft Entra ID). Inclui exemplos completos de publicação de eventos únicos ou em lote, recebimento e processamento com confirmação, liberação ou rejeição, além de integração com Azure Functions para disparo de eventos. Ideal para arquiteturas orientadas a eventos e padrões pub/sub em aplicações .NET.

Funciona com~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 Escrita e Edição skills: steipete/notion, langchain-ai/langchain, bytedance/podcast-generation · View all 6 →

Perguntar na sua IA favorita

Abre um novo chat com esta habilidade de agente já pré-carregada.

Documentação

Azure.Messaging.EventGrid (.NET)

Biblioteca cliente para publicar eventos em tópicos, domínios e namespaces do Azure Event Grid.

Instalação

# Para tópicos e domínios (entrega por push)
dotnet add package Azure.Messaging.EventGrid

# Para namespaces (entrega por pull)
dotnet add package Azure.Messaging.EventGrid.Namespaces

# Para interoperabilidade CloudEvents CloudNative
dotnet add package Microsoft.Azure.Messaging.EventGrid.CloudNativeCloudEvents

Versão Atual: 4.28.0 (estável)

Variáveis de Ambiente

EVENT_GRID_TOPIC_ENDPOINT=https://<nome-do-topico>.<regiao>.eventgrid.azure.net/api/events  # Obrigatório: endpoint do tópico ou domínio do Event Grid
EVENT_GRID_TOPIC_KEY=<chave-de-acesso>  # Obrigatório apenas para autenticação AzureKeyCredential
EVENT_GRID_NAMESPACE_ENDPOINT=https://<namespace>.<regiao>.eventgrid.azure.net  # Opcional: endpoint do namespace do Event Grid
EVENT_GRID_TOPIC_NAME=<nome-do-topico>  # Obrigatório: nome do tópico do Event Grid
EVENT_GRID_SUBSCRIPTION_NAME=<nome-da-assinatura>  # Opcional: nome da assinatura do Event Grid
AZURE_TOKEN_CREDENTIALS=prod  # Obrigatório apenas se DefaultAzureCredential for usado em produção

Hierarquia de Clientes

Entrega por Push (Tópicos/Domínios)
└── EventGridPublisherClient
    ├── SendEventAsync(EventGridEvent)
    ├── SendEventsAsync(IEnumerable<EventGridEvent>)
    ├── SendEventAsync(CloudEvent)
    └── SendEventsAsync(IEnumerable<CloudEvent>)

Entrega por Pull (Namespaces)
├── EventGridSenderClient
│   └── SendAsync(CloudEvent)
└── EventGridReceiverClient
    ├── ReceiveAsync()
    ├── AcknowledgeAsync()
    ├── ReleaseAsync()
    └── RejectAsync()

Autenticação

Autenticação por Chave de API

using Azure;
using Azure.Messaging.EventGrid;

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

Credencial de Token Microsoft Entra

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

// Desenvolvimento local: DefaultAzureCredential. Produção: defina AZURE_TOKEN_CREDENTIALS=prod ou AZURE_TOKEN_CREDENTIALS=<credencial_especifica>
var credential = new DefaultAzureCredential(
    DefaultAzureCredential.DefaultEnvironmentVariableName
);
// Ou use uma credencial específica diretamente em produção:
// Consulte 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);

Autenticação por Token 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);

Publicando Eventos

Esquema EventGridEvent

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

// Evento único
EventGridEvent egEvent = new(
    subject: "orders/12345",
    eventType: "Order.Created",
    dataVersion: "1.0",
    data: new { OrderId = "12345", Amount = 99.99 });

await client.SendEventAsync(egEvent);

// Lote de eventos
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);

Esquema 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);

// Lote 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);

Publicando em um Domínio do Event Grid

// Eventos devem especificar a propriedade Topic para roteamento no domínio
List<EventGridEvent> events = new()
{
    new EventGridEvent(
        subject: "orders/12345",
        eventType: "Order.Created",
        dataVersion: "1.0",
        data: new { OrderId = "12345" })
    {
        Topic = "orders-topic"  // Nome do tópico do domínio
    },
    new EventGridEvent(
        subject: "inventory/item-1",
        eventType: "Inventory.Updated",
        dataVersion: "1.0",
        data: new { ItemId = "item-1" })
    {
        Topic = "inventory-topic"
    }
};

await client.SendEventsAsync(events);

Serialização Personalizada

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);

Entrega por Pull (Namespaces)

Envio de Eventos para Tópico de Namespace

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

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

// Envio de evento único
CloudEvent cloudEvent = new("employee_source", "Employee.Created", 
    new { Name = "John", Age = 30 });
await senderClient.SendAsync(cloudEvent);

// Envio em lote
await senderClient.SendAsync(new[]
{
    new CloudEvent("source", "type", new { Name = "Alice" }),
    new CloudEvent("source", "type", new { Name = "Bob" })
});

Recebimento e Processamento de Eventos

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

// Receber eventos
ReceiveResult result = await receiverClient.ReceiveAsync(maxEvents: 10);

List<string> tokensBloqueioParaConfirmar = new();
List<string> tokensBloqueioParaLiberar = new();

foreach (ReceiveDetails detail in result.Details)
{
    CloudEvent cloudEvent = detail.Event;
    string lockToken = detail.BrokerProperties.LockToken;
    
    try
    {
        // Processar o evento
        Console.WriteLine($"Evento: {cloudEvent.Type}, Dados: {cloudEvent.Data}");
        tokensBloqueioParaConfirmar.Add(lockToken);
    }
    catch (Exception)
    {
        // Liberar para nova tentativa
        tokensBloqueioParaLiberar.Add(lockToken);
    }
}

// Confirmar eventos processados com sucesso
if (tokensBloqueioParaConfirmar.Any())
{
    await receiverClient.AcknowledgeAsync(tokensBloqueioParaConfirmar);
}

// Liberar eventos para nova tentativa
if (tokensBloqueioParaLiberar.Any())
{
    await receiverClient.ReleaseAsync(tokensBloqueioParaLiberar);
}

Rejeitar Eventos (Dead Letter)

// Rejeitar eventos que não podem ser processados
await receiverClient.RejectAsync(new[] { lockToken });

Consumindo Eventos (Azure Functions)

Gatilho 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($"Tipo do Evento: {eventGridEvent.EventType}");
        log.LogInformation($"Assunto: {eventGridEvent.Subject}");
        log.LogInformation($"Dados: {eventGridEvent.Data}");
    }
}

Gatilho 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($"Tipo do Evento: {cloudEvent.Type}");
        logger.LogInformation($"Fonte: {cloudEvent.Source}");
        logger.LogInformation($"Dados: {cloudEvent.Data}");
    }
}

Análise de Eventos

Analisar EventGridEvent

// A partir de string JSON
string json = "..."; // Payload do webhook do Event Grid
EventGridEvent[] events = EventGridEvent.ParseMany(BinaryData.FromString(json));

foreach (EventGridEvent egEvent in events)
{
    if (egEvent.TryGetSystemEventData(out object systemEvent))
    {
        // Manipular evento do sistema
        switch (systemEvent)
        {
            case StorageBlobCreatedEventData blobCreated:
                Console.WriteLine($"Blob criado: {blobCreated.Url}");
                break;
        }
    }
    else
    {
        // Manipular evento personalizado
        var customData = egEvent.Data.ToObjectFromJson<MyCustomData>();
    }
}

Analisar CloudEvent

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

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

Eventos do Sistema

// Tipos comuns de evento do sistema
using Azure.Messaging.EventGrid.SystemEvents;

// Eventos de Storage
StorageBlobCreatedEventData blobCreated;
StorageBlobDeletedEventData blobDeleted;

// Eventos de Recurso
ResourceWriteSuccessEventData resourceCreated;
ResourceDeleteSuccessEventData resourceDeleted;

// Eventos do App Service
WebAppUpdatedEventData webAppUpdated;

// Eventos do Container Registry
ContainerRegistryImagePushedEventData imagePushed;

// Eventos do IoT Hub
IotHubDeviceCreatedEventData deviceCreated;

Referência de Tipos Principais

TipoFinalidade
EventGridPublisherClientPublicar em tópicos/domínios
EventGridSenderClientEnviar para tópicos de namespace
EventGridReceiverClientReceber de assinaturas de namespace
EventGridEventEsquema nativo do Event Grid
CloudEventEsquema CloudEvents 1.0
ReceiveResultResposta de entrega por pull
ReceiveDetailsEvento com propriedades do broker
BrokerPropertiesToken de bloqueio, contagem de entrega

Comparação de Esquemas de Evento

FuncionalidadeEventGridEventCloudEvent
PadrãoEspecífico do AzurePadrão CNCF
Campos obrigatóriossubject, eventType, dataVersion, datasource, type
ExtensibilidadeLimitadaAtributos de extensão
InteroperabilidadeApenas AzureMultiplataforma

Melhores Práticas

  1. Use CloudEvents — Prefira CloudEvents para novas implementações (padrão da indústria)
  2. Lote de eventos — Envie múltiplos eventos em uma única chamada para eficiência
  3. Use Entra ID — Prefira identidade gerenciada em vez de chaves de acesso
  4. Manipuladores idempotentes — Eventos podem ser entregues mais de uma vez
  5. Defina TTL do evento — Configure o time-to-live para eventos de namespace
  6. Lide com falhas parciais — Confirme/libere eventos individualmente
  7. Use dead-letter — Configure dead-letter para eventos com falha
  8. Valide esquemas — Valide os dados do evento antes do processamento

Tratamento de Erros

using Azure;

try
{
    await client.SendEventAsync(cloudEvent);
}
catch (RequestFailedException ex) when (ex.Status == 401)
{
    Console.WriteLine("Falha na autenticação - verifique as credenciais");
}
catch (RequestFailedException ex) when (ex.Status == 403)
{
    Console.WriteLine("Falha na autorização - verifique as permissões RBAC");
}
catch (RequestFailedException ex) when (ex.Status == 413)
{
    Console.WriteLine("Payload muito grande - máximo 1MB por evento, 1MB total do lote");
}
catch (RequestFailedException ex)
{
    Console.WriteLine($"Erro do Event Grid: {ex.Status} - {ex.Message}");
}

Padrão de Failover

try
{
    var primaryClient = new EventGridPublisherClient(primaryUri, primaryKey);
    await primaryClient.SendEventsAsync(events);
}
catch (RequestFailedException)
{
    // Failover para região secundária
    var secondaryClient = new EventGridPublisherClient(secondaryUri, secondaryKey);
    await secondaryClient.SendEventsAsync(events);
}

SDKs Relacionados

SDKFinalidadeInstalação
Azure.Messaging.EventGridTópicos/Domínios (este SDK)dotnet add package Azure.Messaging.EventGrid
Azure.Messaging.EventGrid.NamespacesEntrega por pulldotnet add package Azure.Messaging.EventGrid.Namespaces
Azure.IdentityAutenticaçãodotnet add package Azure.Identity
Microsoft.Azure.WebJobs.Extensions.EventGridGatilho Azure Functionsdotnet add package Microsoft.Azure.WebJobs.Extensions.EventGrid

Links de Referência

RecursoURL
Pacote NuGethttps://www.nuget.org/packages/Azure.Messaging.EventGrid
Referência da APIhttps://learn.microsoft.com/dotnet/api/azure.messaging.eventgrid
Início Rápidohttps://learn.microsoft.com/azure/event-grid/custom-event-quickstart
Entrega por Pullhttps://learn.microsoft.com/azure/event-grid/pull-delivery-overview
Código Fonte no 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.

Habilidades Relacionadas