azureeventhub

How to Get Azure Event Hub Connection String in C#?


Given a Event Hub Name, how can I get connection string in C#? I googled a bit, but nothing useful found so far. Thanks


Solution

  • Using AAD authentication for an EventHub

    var credential = new DefaultAzureCredential();
    // or use 
    // var credential = new Azure.Identity.ClientSecretCredential("tenantId", "clientId", "clientSecret");
    
    EventHubProducerClient producerClient = new EventHubProducerClient(txtNamespace.Text, txtEventHub.Text, credential
    var consumerClient = new EventHubConsumerClient(EventHubConsumerClient.DefaultConsumerGroupName, txtNamespace.Text, txtEventHub.Text, credential)
    
    

    Full example and docs

    Acquiring the Connection Strings of configured Access Policies

    You can use these two Nuget packages:

    Then you can use the resource group name and the eventhub name to retrieve the connection string. You will need to iterate the subscriptions and resource groups if you don't have this information.

    using Azure.Identity;
    using Azure.ResourceManager;
    using Azure.ResourceManager.EventHubs;
    
    
    ArmClient client = new ArmClient(new DefaultAzureCredential()); 
    // Or use
    // ArmClient client = new ArmClient(new Azure.Identity.ClientSecretCredential("tenantId", "clientId", "clientSecret"));
    
    var subscription = await client.GetDefaultSubscriptionAsync();
    var resourceGroup = await subscription.GetResourceGroupAsync("myresourcegroup");
    var eventhubNamespace = await resourceGroup.Value.GetEventHubsNamespaceAsync("namespacename");
    var rules = eventhubNamespace.Value.GetEventHubsNamespaceAuthorizationRules();
    foreach (var rule in rules)
    {
        var keys = await rule.GetKeysAsync();
        Console.WriteLine(keys.Value.PrimaryConnectionString);
        Console.WriteLine(keys.Value.SecondaryConnectionString);
    }