I have created the application Insights using ARM template with C# code.
var creds = new AzureCredentialsFactory().FromServicePrincipal(client, key, tenant, AzureEnvironment.AzureGlobalCloud);
IAzure azure = Microsoft.Azure.Management.Fluent.Azure.Authenticate(creds).WithSubscription(subscription);
IDeployment deployement = azure.Deployments.Define("my-app")
.WithExistingResourceGroup("my-rg-grp")
.WithTemplate(template)
.WithParameters("{}")
.WithMode(DeploymentMode.Incremental)
.CreateAsync();
deployment doesn't have the InstrumentationKey in response.
How could I get the InstrumentationKey just after the Application Insights creation using ARM?
You can use ApplicationInsightsManagementClient class to get the ApplicationInsights resources and the relevant property. The class is defined at Microsoft.Azure.Management.ApplicationInsights v0.3.0-preview package
ApplicationInsightsManagementClient applicationInsightsManagementClient =
new ApplicationInsightsManagementClient(creds) { SubscriptionId = subscriptionId };
var appliationInsightComponents = await applicationInsightsManagementClient.Components.ListAsync();
var requiredApplicationInsightComponent = appliationInsightComponents.SingleOrDefault(a =>
a.ApplicationId.Equals("<<Name of resource>>", StringComparison.OrdinalIgnoreCase));
// to get the InstrumentationKey use
requiredApplicationInsightComponent.InstrumentationKey
Related
I've recently started working as a junior c# developer. My boss asked me to build methods to CRUD teams in our AAD using the microsoft graph API. I've achieved this with a test application like that:
public async Task<string> createTeam()
{
// readying data from registry
var clientId = "********************"; //application (client) ID
var clientSecret = "********************";
var redirectUri = "https://login.microsoftonline.com/common/oauth2/nativeclient";
var authority = "https://login.microsoftonline.com/********************/v2.0";
var cca = ConfidentialClientApplicationBuilder.Create(clientId)
.WithAuthority(authority)
.WithRedirectUri(redirectUri)
.WithClientSecret(clientSecret)
.Build();
List<string> scopes = new List<string>
{
"https://graph.microsoft.com/.default"
};
//
var authenticationProvider = new MsalAuthenticationProvider(cca, scopes.ToArray());
//
GraphServiceClient graphClient = new GraphServiceClient(authenticationProvider);
// Code to create a Team
var team = new Team
{
DisplayName = "0000My Sample Team",
Description = "My Sample Team’s Description",
AdditionalData = new Dictionary<string, object>()
{
{"template#odata.bind", "https://graph.microsoft.com/v1.0/teamsTemplates('standard')"}
}
};
var result = await graphClient.Teams.Request().AddAsync(team);
return result.DisplayName;
}
With that piece of code working, I've created an asp.net web Application (.net framework) and added the class to it. The plan was to deploy it to an IIS server and and publish the methods as web services.
[WebMethod]
public async Task<string> createTeamAsync()
{
//The class where my methods reside
TeamServices ts = new TeamServices();
var result = await ts.createTeam();
return "OK";
}
I registered the app and deployed but when I try to use it, it does not create any Team.
Do you know what I'm doing wrong of what I should learn next get the app working? Im just a few weeks in c# and I'm completely lost in all that .net echosystem
Thanks in advance
Problem is creating Container group with identity and log analytics diagnostics in Azure using .NET SDK with nugets
Microsoft.Azure.Management.Fluent
Microsoft.Azure.Management.ContainerInstance
Microsoft.Azure.Management.ContainerInstance.Fluent
So the question is:
Is there a way to create container group in Azure with identity and diagnostics specified using latest .NET Core SDK fluent API?
OR
Is there a way to create plain constructor built container group in Azure using latest .NET Core SDK?
There are plenty of examples to use the fluent API eg.
// Create the container group
var containerGroup = azure.ContainerGroups.Define(containerGroupName)
.WithRegion(azureRegion)
.WithExistingResourceGroup(resourceGroupName)
.WithLinux()
.WithPublicImageRegistryOnly()
.WithoutVolume()
.DefineContainerInstance(containerGroupName + "-1")
.WithImage(containerImage)
.WithExternalTcpPort(80)
.WithCpuCoreCount(1.0)
.WithMemorySizeInGB(1)
.Attach()
.WithDnsPrefix(containerGroupName)
.Create();
Although, I haven't found a way to declare identity or diagnostics to this container group.
On the other hand I found a way to create ContainerGroup object with class constructors (yes, my code is in F#):
// Create containers
let containers =
[| minCount .. maxCount |]
|> Array.map (fun i ->
Container(
name = (sprintf "%s-%i" containerName i),
image = image,
resources = resources,
EnvironmentVariables = envVariables))
// Create container group for containers
let containerGroup =
ContainerGroup(
containers = containers,
osType = "linux",
name = groupName,
location = location,
identity = identity, // missing from fluent
imageRegistryCredentials = imageCredentials,
restartPolicy = restartType,
diagnostics = diag) // missing from fluent
However, with these plain constructor built objects, I haven't found a method to create them in Azure.
I was able to to send the plain constructor built objects to azure using ContainerInstanceManagementClient function from assembly Microsoft.Azure.Management.ContainerInstance.
let creds = SdkContext.AzureCredentialsFactory.FromServicePrincipal(client, key, tenant, AzureEnvironment.AzureGlobalCloud)
let client = new ContainerInstanceManagementClient(creds)
client.SubscriptionId <- subscriptionId
let _ =
client.ContainerGroups.CreateOrUpdate(
resourceGroupName = rgName,
containerGroupName = name,
containerGroup = containerGroup) // Container group from the question
As the Microsoft.Azure.Management.ContainerInstance package is now deprecated I switched to the Azure.ResourceManager but had a similar problem. After some debugging I found that the credentials of the ArmClient are not propagated to the Docker registry pull request, you have to do that explicitly by adding a ImageRegistryCredentials, see code below. It might be a good thing once you know, because now you can use different credentials for pulling the Docker image.
var credential = (TokenCredential)new ClientSecretCredential(tenantId, user, clientSecret);
var armClient = new ArmClient(credential);
var subscription = await armClient.GetDefaultSubscriptionAsync().ConfigureAwait(false);
var resourceGroup = (await subscription.GetResourceGroupAsync(resourceGroupName).ConfigureAwait(false)).Value;
var containerGroups = resourceGroup.GetContainerGroups();
var resourceRequirements = new ContainerResourceRequirements(new ContainerResourceRequestsContent(8, 2));
var container = new ContainerInstanceContainer(containerGroupName, containerImage, resourceRequirements);
var containerGroupData = new ContainerGroupData(AzureLocation.WestEurope,
new List<ContainerInstanceContainer> { container }, ContainerInstanceOperatingSystemType.Linux);
var registryCredential = new ContainerGroupImageRegistryCredential(containerRegistry, user)
{
Password = clientSecret
};
containerGroupData.ImageRegistryCredentials.Add(registryCredential);
var containerGroup = await containerGroups.CreateOrUpdateAsync(WaitUntil.Completed, containerGroupName,
containerGroupData);
await containerGroup.Value.StartAsync(WaitUntil.Completed);
I am trying to implement a feature in a local C#.NET application. The application has my AAD credentials stored in variables (username and password).
I can't seem to find any way to do what Get-AzureRMResourceGroups does in PowerShell, in C#. I have tried to use Microsoft.Azure.Management.Fluent without any success.
All I can find is how to access Azure resources, passing data and such - which I am not interested in. I want to list resource groups, resources and their permissions. If possible, I would like to be able to alter them, but for now I just want to list subscription related information.
Thanks, and please don't hesitate to edit this question to improve it.
You are going to need to use ResourceManagementClient, something like:
using Microsoft.Azure.Management.ResourceManager;
...
var tenantId = Environment.GetEnvironmentVariable("AZURE_TENANT_ID");
var clientId = Environment.GetEnvironmentVariable("AZURE_CLIENT_ID");
var secret = Environment.GetEnvironmentVariable("AZURE_SECRET");
var subscriptionId = Environment.GetEnvironmentVariable("AZURE_SUBSCRIPTION_ID");
// Build the service credentials and Azure Resource Manager clients
var serviceCreds = await ApplicationTokenProvider.LoginSilentAsync(tenantId, clientId, secret);
var resourceClient = new ResourceManagementClient(serviceCreds);
resourceClient.SubscriptionId = subscriptionId;
// Getting the resource groups
var groups=resourceClient.ResourceGroups.List().ToList();
Thanks for lead #octavioccl
I used:
using Microsoft.Azure.Management.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core;
var credentials = SdkContext.AzureCredentialsFactory.FromServicePrincipal(
clientId: clientId,
clientSecret: secretKey,
tenantId: tenantId,
environment: AzureEnvironment.AzureGlobalCloud
);
var azure = Azure
.Configure()
.WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
.Authenticate(credentials)
.WithSubscription(subscriptionId: subscriptionId)
//.WithDefaultSubscription()
;
var lorg = azure.ResourceGroups.List();
I'm trying to connect my Azure Scheduler via my .Net Application however, at the current state I'm getting KeyNotFoundException: The given key was not present in the dictionary.
I have tried to example in https://github.com/Azure-Samples/scheduler-dotnet-getting-started/tree/master/SchedulerArmSDKTemplate
The problem with the above example is, I think it is based on previous version of the packages. So on the latest version, I tried to make it work by myself but I wasn't able to. The amount of documentation around this and AD Connect is really limited, especially when it comes to new Portal and latest versions. My code sample is below, I'm not sure what I'm doing wrong at this point:
var tenantId = "{tenantId}"; // I have put objectId from Azure AD Properties
var clientId = "{clientId}"; // Here, I have created new App Registration in Azure AD and copied the AppId value
var subscriptionId = "{subscriptionId}"; //Subscription Id of the scheduler resource
UserLoginInformation loginInformation = new UserLoginInformation()
{
ClientId = clientId
};
ServiceClientCredentials serviceClientCredentials = new AzureCredentials(loginInformation, tenantId, AzureEnvironment.AzureGlobalCloud);
SchedulerManagementClient schedulerManagementClient =
new SchedulerManagementClient(serviceClientCredentials) { SubscriptionId = subscriptionId };
var schedulers = await schedulerManagementClient.JobCollections.GetWithHttpMessagesAsync("{resourceGroup}", "{jobCollectionName}");
Tennat Id is not the application objectid. We could get it from the Azure portal, more detail please refer to the screenshot.
If user is not required multi-factor authentication. please have a try to use the following code.
var tenantId = "tenantId"; // Not the object id, it is Azure directory Id
var clientId = "client Id"; // Here, I have created new App Registration in Azure AD and copied the AppId value
var subscriptionId = "subscription Id"; //Subscription Id of the scheduler resource
var resourceGroup = "resource group";
var jobCollectionName = "job name";
UserLoginInformation loginInformation = new UserLoginInformation()
{
ClientId = clientId,
UserName = "xxx#example.com",
Password = "xxxxxx"
};
ServiceClientCredentials serviceClientCredentials = new AzureCredentials(loginInformation, tenantId, AzureEnvironment.AzureGlobalCloud);
SchedulerManagementClient schedulerManagementClient =
new SchedulerManagementClient(serviceClientCredentials) { SubscriptionId = subscriptionId };
var schedulers = await schedulerManagementClient.JobCollections.GetWithHttpMessagesAsync($"{resourceGroup}", $"{jobCollectionName}");
How to get list of resource for a Resource Group using Azure Resource Management API
I have install Microsoft.Azure.Management.ResourceManager.Fluent Nuget package
The below script only give me only list of resource groups but not list of resources per resource group.
var credentials = SdkContext.AzureCredentialsFactory.FromServicePrincipal(clientId, clientSecret, tenantId, AzureEnvironment.AzureGlobalCloud);
var azure = Azure.Configure().Authenticate(credentials).WithSubscription(subscriptionID);
var resourecelist = azure.ResourceGroups.List().ToList();
I am looking for something similar to which is available in powershell
Get-AzureRmResource -ResourceGroupName $batchResourceGroup -ResourceType 'Microsoft.Batch/batchAccounts'
Please have a try to following code to get list of resources. I test it on my side, it works correctly. We also could use the Resources - List By Resource Group Rest API to do that.
var resouceManagementClient = new ResourceManagementClient(credentials) {SubscriptionId = subscriptionId};
var resource = resouceManagementClient.ResourceGroups.ListResourcesAsync(resourceGroup,new ODataQuery<GenericResourceFilterInner>(x=>x.ResourceType == "Microsoft.Batch/batchAccounts")).Result;
The above answer is out-of-date, so here's my code snippet that works in Dec 2020.
Azure.IAuthenticated _azure;
string _subscriptionId;
RestClient _restClient;
async Task Main()
{
Connect();
// Get resource groups
var resourceManagementClient = new ResourceManagementClient(_restClient)
{
SubscriptionId = _subscriptionId
};
var resourceList = (await resourceManagementClient.ResourceGroups.ListAsync()).ToList().OrderBy(r => r.Name);
// ...
}
void Connect()
{
_subscriptionId = "XXX";
var tenantId = "YYY";
var clientId = "ZZZ";
var secret = "QQQ";
var credentials = SdkContext.AzureCredentialsFactory.FromServicePrincipal(
clientId, secret, tenantId,
AzureEnvironment.AzureGlobalCloud)
.WithDefaultSubscription(_subscriptionId);
_restClient = RestClient
.Configure()
.WithEnvironment(AzureEnvironment.AzureGlobalCloud)
.WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
.WithCredentials(credentials)
.Build();
var creds = new AzureCredentialsFactory().FromServicePrincipal(
clientId, secret, tenantId,
AzureEnvironment.AzureGlobalCloud
);
_azure = Azure.Authenticate(creds);
}
The usings/imports/NuGet. (you do not need all of these...):
Microsoft.Azure.Management.AppService.Fluent
Microsoft.Azure.Management.AppService.Fluent.Models
Microsoft.Azure.Management.Fluent
Microsoft.Azure.Management.ResourceManager.Fluent
Microsoft.Azure.Management.ResourceManager.Fluent.Authentication
Microsoft.Azure.Management.ResourceManager.Fluent.Core
Microsoft.IdentityModel.Clients.ActiveDirectory
Microsoft.Rest
Microsoft.ServiceBus.Messaging
System.Threading.Tasks
Microsoft.Rest.Azure