List azure Workspaces By Resource Group in C# .NET

2019-08-18 02:22发布

问题:

How do I get the list of workspaces by ressource group ?

I found this Rest call : List workspace by ressource group

The ressource to call is :

GET https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Databricks/workspaces?api-version=2018-04-01

under log analytics rest api documentation, but it seems like there is no equivalent to this call in azure .NET SDK .

Do I have to make the Rest call from my C# code using something like HttpClient or there is a more simple way to issue the query ?

回答1:

As you mentioned two resource OperationalInsights and Databricks in your post, not clear which one you want to use, so I list both of them.

For OperationalInsights, you can download Microsoft.Azure.Management.OperationalInsights to use the SDK.

While for Databricks, I don't find any SDK either in .NET SDK document. Calling REST API is a standard way, and there seems no easier method AFAIK.

Using SDK or REST both require you to get necessary info(appId, secretKey, tenantId) by registering AD App and assigning role to application. Please follow this tutorial.

And then use code snippet below. Remeber to install Microsoft.IdentityModel.Clients.ActiveDirectory to generate credential.

var appId = "ApplicationID";
var secretKey = "SecretKey";
var tenantId = "TenantID(aka DirectoryID)";
var subscriptionId = "SubscriptionId";
var resourceGroupName = "ResourceGroupName";

var context = new AuthenticationContext("https://login.windows.net/" + tenantId);
ClientCredential clientCredential = new ClientCredential(appId, secretKey);
var tokenResponse = context.AcquireTokenAsync("https://management.azure.com/", clientCredential).Result;
var accessToken = tokenResponse.AccessToken;

//OperationalInsights
var opsClient = new OperationalInsightsManagementClient(new TokenCredentials(accessToken))
{
     SubscriptionId = subscriptionId
};
var workspaces = opsClient.Workspaces.ListByResourceGroupAsync(resourceGroupName).Result;


// Databricks
using (var client = new HttpClient())
{
     client.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken);
     client.BaseAddress = new Uri("https://management.azure.com/");

     using (var response = await client.GetAsync(
                $"subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Databricks/workspaces?api-version=2018-04-01"))
     {
          response.EnsureSuccessStatusCode();
          var content = await response.Content.ReadAsStringAsync();
          JObject json = JObject.Parse(content);
          Console.WriteLine(json);
     }
}


标签: c# rest azure