skip to Main Content

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

2

Answers


  1. Not sure if this is what you mean, but if you want to access an Event Hub through C# you need to provide the EH connection string into your code. This can be retrieved by adding a Shared access policy for the Event hub that you are trying to access.

    connection string for EH

    Edit: If you are trying to actually create the connection string yourself you could follow this sample where you create the SAS-token yourself. But you would still need to provide the Primary key that is set on the policy from Azure.

    Login or Signup to reply.
  2. 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);
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search