Reading event schema stored in JSON format in Azure Event Hubs Schema Registry, in C#

77 views Asked by At

I have an event schema stored in JSON format in Azure Event Hubs Schema Registry. I need to read that schema in my C# code, without hard coding the schema in the code. Schema needs to be read into a JSON object in the code. I am looking for some sample code to get started. I have not found anything in the manuals or elsewhere.

Please help.

2

There are 2 answers

3
Anup Das Gupta On

Here is an example of how you might achieve this:

using System;
using Azure;
using Azure.Messaging.EventHubs;
using Azure.Messaging.EventHubs.Producer;
using Azure.Messaging.EventHubs.Consumer;
using Azure.Messaging.EventHubs.SchemaRegistry;

class Program
{
    static async Task Main(string[] args)
    {
        string connectionString = "YOUR_EVENT_HUBS_CONNECTION_STRING";
        string eventHubName = "YOUR_EVENT_HUB_NAME";
        string schemaGroup = "YOUR_SCHEMA_GROUP_NAME";
        string schemaName = "YOUR_SCHEMA_NAME";

        var client = new SchemaRegistryClient(connectionString);
        
        try
        {
            using (var schema = await client.GetSchemaAsync(schemaGroup, schemaName))
            {
                string schemaContent = schema.Content;
                Console.WriteLine(schemaContent); // Output the schema content (for demonstration purposes)

                // Parse the schema content into a JSON object
                dynamic schemaObject = Newtonsoft.Json.JsonConvert.DeserializeObject(schemaContent);

                // Use the schema object in your code as needed
                // (schemaObject will contain the parsed JSON schema)
            }
        }
        catch (RequestFailedException ex)
        {
            Console.WriteLine($"An error occurred: {ex.Message}");
        }
    }
}

Please ensure you have installed the necessary NuGet packages like Azure.Messaging.EventHubs, Azure.Messaging.EventHubs.Producer, Azure.Messaging.EventHubs.Consumer, and Azure.Messaging.EventHubs.SchemaRegistry for this code to work.

0
Jesse Squire On

This scenario is documented in the Retrieve a schema example in the Azure.Data.SchemaRegistry overview:

var client = new SchemaRegistryClient(
    "your-hostname.servicebus.windows.net", 
    new DefaultAzureCredential());

SchemaRegistrySchema schema = client.GetSchema("your-id");
string schemaContent = schema.Definition;

This works no matter the format of the schema, including JSON. More examples and discussion are available in the Schema Registry README and samples.