Azure Event Grid Sample code

 Event Grid

Azure Event Grid is a fully managed event routing service that enables event-driven architectures by:

               Delivering events from sources to subscribers in near real-time.

               Supporting fan-out (sending the same event to multiple subscribers).

               Ensuring high reliability and scalability.

How Event Grid Fits in SOA

Decoupling Services:

SOA often involves tightly coupled services that rely on synchronous communication (e.g., REST or SOAP APIs). Event Grid enables asynchronous communication by routing events between services, reducing coupling and improving scalability.

Event-Driven Communication:

Instead of services polling for updates or making direct API calls, they can react to events published to Event Grid.

Example: A “Payment Processed” event independently triggers order fulfillment and notification services.

Integration with Other Azure Services:

Event Sources: Event Grid integrates with resources like Azure Blob Storage, Azure Functions, and Service Bus.

Event Subscribers: Services like Logic Apps, Functions, or third-party endpoints can act as subscribers.

Real-Time Data Flow:

Use cases like updating dashboards, triggering workflows, or alerting systems benefit from real-time event delivery.

Event-Driven SOA with Event Grid

Event-Driven Patterns in SOA

Publish-Subscribe Pattern:

How it Works: A service publishes events to Event Grid, and multiple subscribers act on the events.

Use Case: A shipping service subscribes to “Order Created” events and an inventory service updates stock levels.

Event Sourcing Pattern:

How it Works: Capture all state changes as events in an event store.

Use Case: An order management system records events like “Order Placed,” “Order Shipped,” etc., for auditability and recovery.

Fan-Out Pattern:

How it Works: An event triggers multiple downstream actions.

Use Case: A single “User Registered” event updates the CRM system, sends a welcome email, and logs the activity.

Choreography vs. Orchestration:

Choreography: Services act on events independently (loosely coupled).

Orchestration: A central controller (e.g., Logic Apps) coordinates service interactions using events.

Here’s a C# example demonstrating how to send an event to Azure Event Grid and process it in a subscriber.

1. Sending an Event-to-Event Grid

You can send an event using the EventGridPublisherClient class from the Azure SDK.

using System;

using System.Collections.Generic;

using System.Threading.Tasks;

using Azure.Messaging.EventGrid;

class Program

{

    static async Task Main(string[] args)

    {

        // Replace with your Event Grid topic endpoint and key

        string topicEndpoint = "<your-event-grid-topic-endpoint>";

        string topicKey = "<your-topic-key>";

        var credential = new Azure.AzureKeyCredential(topicKey);

        var client = new EventGridPublisherClient(new Uri(topicEndpoint), credential);

        // Create a new event

        var events = new List<EventGridEvent>

        {

            new EventGridEvent(

                subject: "NewItemCreated",

                eventType: "Contoso.Items.ItemCreated",

                dataVersion: "1.0",

                data: new

                {

                    ItemId = "12345",

                    ItemName = "Sample Item",

                    CreatedTime = DateTime.UtcNow

                })

        };

        // Send the event

        await client.SendEventsAsync(events);

        Console.WriteLine("Event sent successfully.");

    }

}

2. Receiving and Processing the Event

Example: Azure Function as a Subscriber

This Azure Function will receive and process the event:

 

using System;

using Microsoft.Azure.Functions.Worker;

using Microsoft.Extensions.Logging;

public class EventGridTriggerFunction

{

    private readonly ILogger _logger;

    public EventGridTriggerFunction(ILoggerFactory loggerFactory)

    {

        _logger = loggerFactory.CreateLogger<EventGridTriggerFunction>();

    }

    [Function("EventGridTriggerFunction")]

    public void Run([EventGridTrigger] EventGridEvent eventGridEvent)

    {

        _logger.LogInformation($"Event received: {eventGridEvent.Data.ToString()}");

        // Parse the event data

        dynamic eventData = eventGridEvent.Data;

        string itemId = eventData.ItemId;

        string itemName = eventData.ItemName;

        DateTime createdTime = eventData.CreatedTime;

        _logger.LogInformation($"Item ID: {itemId}");

        _logger.LogInformation($"Item Name: {itemName}");

        _logger.LogInformation($"Created Time: {createdTime}");

        // Process the event (e.g., update a database, send a notification, etc.)

    }

}

 Steps to Configure

            1.         Create an Event Grid Topic:

                        Go to the Azure portal and create an Event Grid Topic.

                        Copy the Topic Endpoint and the Access Key.

            2.         Add a Subscriber:

                        Deploy the Azure Function to Azure.

When configuring the Event Grid Topic, use the Function’s URL as the subscriber endpoint.

            3.         Test the Flow:

Run the C# sender code to publish an event.

Check the Azure Function logs to see the processed event data.


 

Comments

Post a Comment

Popular posts from this blog

Performance Optimization in Sitecore

Strategies for Migrating to Sitecore from legacy or upgrading from older Sitecore