Skip to content

Commit 7cf0d4e

Browse files
authored
Merge pull request #210305 from spelluru/ehubadal0906
updated to use MSAL
2 parents a312317 + dddc52b commit 7cf0d4e

File tree

1 file changed

+125
-34
lines changed

1 file changed

+125
-34
lines changed

articles/event-hubs/event-hubs-management-libraries.md

Lines changed: 125 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
title: Management libraries - Azure Event Hubs| Microsoft Docs
33
description: This article provides information on the library that you can use to manage Azure Event Hubs namespaces and entities from .NET.
44
ms.topic: article
5-
ms.date: 09/23/2021
5+
ms.date: 09/06/2022
66
ms.devlang: csharp
77
ms.custom: devx-track-csharp
88
---
@@ -19,49 +19,140 @@ You can use the Azure Event Hubs management libraries to dynamically provision E
1919

2020
## Prerequisites
2121

22-
To get started using the Event Hubs management libraries, you must authenticate with Azure Active Directory (AAD). AAD requires that you authenticate as a service principal, which provides access to your Azure resources. For information about creating a service principal, see one of these articles:
22+
To get started using the Event Hubs management libraries, you must authenticate with Azure Active Directory (Azure AD). Azure AD requires that you authenticate as a service principal, which provides access to your Azure resources. For information about creating a service principal, see one of these articles:
2323

2424
* [Use the Azure portal to create Active Directory application and service principal that can access resources](../active-directory/develop/howto-create-service-principal-portal.md)
2525
* [Use Azure PowerShell to create a service principal to access resources](../active-directory/develop/howto-authenticate-service-principal-powershell.md)
2626
* [Use Azure CLI to create a service principal to access resources](/cli/azure/create-an-azure-service-principal-azure-cli)
2727

28-
These tutorials provide you with an `AppId` (Client ID), `TenantId`, and `ClientSecret` (authentication key), all of which are used for authentication by the management libraries. You must have **Owner** permissions for the resource group on which you want to run.
28+
These tutorials provide you with an `AppId` (Client ID), `TenantId`, and `ClientSecret` (authentication key), all of which are used for authentication by the management libraries. The Azure AD application must be added to the **Azure Event Hubs Data Owner** role at the resource group level.
2929

30-
## Programming pattern
30+
## Sample code
3131

3232
The pattern to manipulate any Event Hubs resource follows a common protocol:
3333

34-
1. Obtain a token from AAD using the `Microsoft.IdentityModel.Clients.ActiveDirectory` library.
35-
```csharp
36-
var context = new AuthenticationContext($"https://login.microsoftonline.com/{tenantId}");
37-
38-
var result = await context.AcquireTokenAsync(
39-
"https://management.core.windows.net/",
40-
new ClientCredential(clientId, clientSecret)
41-
);
42-
```
43-
34+
1. Obtain a token from Azure AD using the `Microsoft.Identity.Client` library.
4435
1. Create the `EventHubManagementClient` object.
45-
```csharp
46-
var creds = new TokenCredentials(token);
47-
var ehClient = new EventHubManagementClient(creds)
48-
{
49-
SubscriptionId = SettingsCache["SubscriptionId"]
50-
};
51-
```
52-
53-
1. Set the `CreateOrUpdate` parameters to your specified values.
54-
```csharp
55-
var ehParams = new EventHubCreateOrUpdateParameters()
56-
{
57-
Location = SettingsCache["DataCenterLocation"]
58-
};
59-
```
60-
61-
1. Execute the call.
62-
```csharp
63-
await ehClient.EventHubs.CreateOrUpdateAsync(resourceGroupName, namespaceName, EventHubName, ehParams);
64-
```
36+
1. Then, use the client object to create an Event Hubs namespace and an event hub.
37+
38+
Here's the sample code to create an Event Hubs namespace and an event hub.
39+
40+
```csharp
41+
42+
namespace event_hub_dotnet_management
43+
{
44+
using System;
45+
using System.Threading.Tasks;
46+
using Microsoft.Azure.Management.EventHub;
47+
using Microsoft.Azure.Management.EventHub.Models;
48+
using Microsoft.Identity.Client;
49+
using Microsoft.Rest;
50+
51+
52+
public static class EventHubManagementSample
53+
{
54+
private static string resourceGroupName = "<YOUR EXISTING RESOURCE GROUP NAME>";
55+
private static string namespaceName = "<EVENT HUBS NAMESPACE TO BE CREATED>";
56+
private const string eventHubName = "<EVENT HUB TO BE CREATED>";
57+
private const string location = "<REGION>"; //for example: "eastus"
58+
59+
public static async Task Main()
60+
{
61+
// get a token from Azure AD
62+
var token = await GetToken();
63+
64+
// create an EventHubManagementClient
65+
var creds = new TokenCredentials(token);
66+
var ehClient = new EventHubManagementClient(creds)
67+
{
68+
SubscriptionId = "<AZURE SUBSCRIPTION ID>"
69+
};
70+
71+
// create an Event Hubs namespace using the EventHubManagementClient
72+
await CreateNamespace(ehClient);
73+
74+
// create an event hub using the EventHubManagementClient
75+
await CreateEventHub(ehClient);
76+
77+
Console.WriteLine("Press a key to exit.");
78+
Console.ReadLine();
79+
}
80+
81+
// Get an authentication token from Azure AD first
82+
private static async Task<string> GetToken()
83+
{
84+
try
85+
{
86+
Console.WriteLine("Acquiring token...");
87+
88+
var tenantId = "<AZURE TENANT ID>";
89+
90+
// use the Azure AD app that's a member of Azure Event Hubs Data Owner role at the resource group level
91+
var clientId = "<AZURE APPLICATION'S CLIENT ID>";
92+
var clientSecret = "<CLIENT SECRET>";
93+
94+
IConfidentialClientApplication app;
95+
96+
app = ConfidentialClientApplicationBuilder.Create(clientId)
97+
.WithClientSecret(clientSecret)
98+
.WithAuthority($"https://login.microsoftonline.com/{tenantId}")
99+
.Build();
100+
101+
var result = await app.AcquireTokenForClient(new[] { $"https://management.core.windows.net/.default" })
102+
.ExecuteAsync()
103+
.ConfigureAwait(false);
104+
105+
// If the token isn't a valid string, throw an error.
106+
if (string.IsNullOrEmpty(result.AccessToken))
107+
{
108+
throw new Exception("Token result is empty!");
109+
}
110+
111+
return result.AccessToken;
112+
}
113+
catch (Exception e)
114+
{
115+
Console.WriteLine("Could not get a new token...");
116+
Console.WriteLine(e.Message);
117+
throw e;
118+
}
119+
}
120+
121+
// Create an Event Hubs namespace
122+
private static async Task CreateNamespace(EventHubManagementClient ehClient)
123+
{
124+
try
125+
{
126+
Console.WriteLine("Creating namespace...");
127+
await ehClient.Namespaces.CreateOrUpdateAsync(resourceGroupName, namespaceName, new EHNamespace { Location = location });
128+
Console.WriteLine("Created namespace successfully.");
129+
}
130+
catch (Exception e)
131+
{
132+
Console.WriteLine("Could not create a namespace...");
133+
Console.WriteLine(e.Message);
134+
}
135+
}
136+
137+
138+
// Create an event hub
139+
private static async Task CreateEventHub(EventHubManagementClient ehClient)
140+
{
141+
try
142+
{
143+
Console.WriteLine("Creating Event Hub...");
144+
await ehClient.EventHubs.CreateOrUpdateAsync(resourceGroupName, namespaceName, eventHubName, new Eventhub());
145+
Console.WriteLine("Created Event Hub successfully.");
146+
}
147+
catch (Exception e)
148+
{
149+
Console.WriteLine("Could not create an Event Hub...");
150+
Console.WriteLine(e.Message);
151+
}
152+
}
153+
}
154+
}
155+
```
65156

66157
## Next steps
67158
* [.NET Management sample](https://github.com/Azure-Samples/event-hubs-dotnet-management/)

0 commit comments

Comments
 (0)