private List <Provider> ListResourceProviders() { ProviderListResult result = ResourceManagementClient.Providers.List(null); List <Provider> providers = new List <Provider>(result.Providers); while (!string.IsNullOrEmpty(result.NextLink)) { result = ResourceManagementClient.Providers.ListNext(result.NextLink); providers.AddRange(result.Providers); } return(providers); }
private List <Provider> GetProviders(IResourceManagementClient client) { if (ResourceManagerProviders == null) { ResourceManagerProviders = new List <Provider>(); ProviderListResult result = client.Providers.List(null); ResourceManagerProviders.AddRange(result.Providers); while (!string.IsNullOrEmpty(result.NextLink)) { result = client.Providers.ListNext(result.NextLink); ResourceManagerProviders.AddRange(result.Providers); } } return(ResourceManagerProviders); }
/// <summary> /// Get a list of deployments. /// </summary> /// <param name='nextLink'> /// Required. NextLink from the previous successful call to List /// operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// List of resource providers. /// </returns> public async Task <ProviderListResult> ListNextAsync(string nextLink, CancellationToken cancellationToken) { // Validate if (nextLink == null) { throw new ArgumentNullException("nextLink"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("nextLink", nextLink); TracingAdapter.Enter(invocationId, this, "ListNextAsync", tracingParameters); } // Construct URL string url = nextLink; // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result ProviderListResult result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ProviderListResult(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { Provider providerInstance = new Provider(); result.Providers.Add(providerInstance); JToken idValue = valueValue["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); providerInstance.Id = idInstance; } JToken namespaceValue = valueValue["namespace"]; if (namespaceValue != null && namespaceValue.Type != JTokenType.Null) { string namespaceInstance = ((string)namespaceValue); providerInstance.Namespace = namespaceInstance; } JToken registrationStateValue = valueValue["registrationState"]; if (registrationStateValue != null && registrationStateValue.Type != JTokenType.Null) { string registrationStateInstance = ((string)registrationStateValue); providerInstance.RegistrationState = registrationStateInstance; } JToken resourceTypesArray = valueValue["resourceTypes"]; if (resourceTypesArray != null && resourceTypesArray.Type != JTokenType.Null) { foreach (JToken resourceTypesValue in ((JArray)resourceTypesArray)) { ProviderResourceType providerResourceTypeInstance = new ProviderResourceType(); providerInstance.ResourceTypes.Add(providerResourceTypeInstance); JToken resourceTypeValue = resourceTypesValue["resourceType"]; if (resourceTypeValue != null && resourceTypeValue.Type != JTokenType.Null) { string resourceTypeInstance = ((string)resourceTypeValue); providerResourceTypeInstance.Name = resourceTypeInstance; } JToken locationsArray = resourceTypesValue["locations"]; if (locationsArray != null && locationsArray.Type != JTokenType.Null) { foreach (JToken locationsValue in ((JArray)locationsArray)) { providerResourceTypeInstance.Locations.Add(((string)locationsValue)); } } } } } } JToken odatanextLinkValue = responseDoc["@odata.nextLink"]; if (odatanextLinkValue != null && odatanextLinkValue.Type != JTokenType.Null) { string odatanextLinkInstance = ((string)odatanextLinkValue); result.NextLink = odatanextLinkInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return(result); } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } }
/// <summary> /// Gets a list of resource providers. /// </summary> /// <param name='parameters'> /// Optional. Query parameters. If null is passed returns all /// deployments. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// List of resource providers. /// </returns> public async Task <ProviderListResult> ListAsync(ProviderListParameters parameters, CancellationToken cancellationToken) { // Validate // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters); } // Construct URL string url = "/subscriptions/" + (this.Client.Credentials.SubscriptionId == null ? "" : Uri.EscapeDataString(this.Client.Credentials.SubscriptionId)) + "/providers?"; if (parameters != null && parameters.Top != null) { url = url + "$top=" + Uri.EscapeDataString(parameters.Top.Value.ToString()); } url = url + "&api-version=2014-04-01-preview"; string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result ProviderListResult result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ProviderListResult(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { Provider providerInstance = new Provider(); result.Providers.Add(providerInstance); JToken idValue = valueValue["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); providerInstance.Id = idInstance; } JToken namespaceValue = valueValue["namespace"]; if (namespaceValue != null && namespaceValue.Type != JTokenType.Null) { string namespaceInstance = ((string)namespaceValue); providerInstance.Namespace = namespaceInstance; } JToken registrationStateValue = valueValue["registrationState"]; if (registrationStateValue != null && registrationStateValue.Type != JTokenType.Null) { string registrationStateInstance = ((string)registrationStateValue); providerInstance.RegistrationState = registrationStateInstance; } JToken resourceTypesArray = valueValue["resourceTypes"]; if (resourceTypesArray != null && resourceTypesArray.Type != JTokenType.Null) { foreach (JToken resourceTypesValue in ((JArray)resourceTypesArray)) { ProviderResourceType providerResourceTypeInstance = new ProviderResourceType(); providerInstance.ResourceTypes.Add(providerResourceTypeInstance); JToken resourceTypeValue = resourceTypesValue["resourceType"]; if (resourceTypeValue != null && resourceTypeValue.Type != JTokenType.Null) { string resourceTypeInstance = ((string)resourceTypeValue); providerResourceTypeInstance.Name = resourceTypeInstance; } JToken locationsArray = resourceTypesValue["locations"]; if (locationsArray != null && locationsArray.Type != JTokenType.Null) { foreach (JToken locationsValue in ((JArray)locationsArray)) { providerResourceTypeInstance.Locations.Add(((string)locationsValue)); } } } } } } JToken odatanextLinkValue = responseDoc["@odata.nextLink"]; if (odatanextLinkValue != null && odatanextLinkValue.Type != JTokenType.Null) { string odatanextLinkInstance = ((string)odatanextLinkValue); result.NextLink = odatanextLinkInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return(result); } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } }
public override async Task <ActionResponse> ExecuteActionAsync(ActionRequest request) { var aadTenant = request.DataStore.GetValue("AADTenant"); string authBase; string clientId; string resource; string oauthType = (request.DataStore.GetLastValue("oauthType") ?? string.Empty).ToLowerInvariant(); switch (oauthType) { case "powerbi": authBase = string.Format(Constants.AzureAuthUri, aadTenant); clientId = Constants.MicrosoftClientIdPowerBI; resource = Constants.PowerBIService; break; case "mscrm": authBase = string.Format(Constants.AzureAuthUri, aadTenant); clientId = Constants.MsCrmClientId; resource = Constants.AzureManagementApi; break; case "keyvault": string azureToken = request.DataStore.GetJson("AzureToken", "access_token"); string subscriptionId = request.DataStore.GetJson("SelectedSubscription", "SubscriptionId"); string resourceGroup = request.DataStore.GetValue("SelectedResourceGroup"); // Make sure the Key Vault is registered SubscriptionCloudCredentials creds = new TokenCloudCredentials(subscriptionId, azureToken); using (ResourceManagementClient managementClient = new ResourceManagementClient(creds)) { ProviderListResult providersResult = managementClient.Providers.List(null); bool kvExists = false; foreach (var p in providersResult.Providers) { if (p.Namespace.EqualsIgnoreCase("Microsoft.KeyVault")) { kvExists = p.RegistrationState.EqualsIgnoreCase("Registered"); break; } } AzureOperationResponse operationResponse; if (!kvExists) { operationResponse = managementClient.Providers.Register("Microsoft.KeyVault"); if (operationResponse.StatusCode != System.Net.HttpStatusCode.OK && operationResponse.StatusCode != System.Net.HttpStatusCode.Accepted) { return(new ActionResponse(ActionStatus.Failure, JsonUtility.GetEmptyJObject(), "MsCrm_ErrorRegisterKv")); } Thread.Sleep(10000); // Wait for it to register } string oid; string tenantID; ExtractUserandTenant(azureToken, out oid, out tenantID); const string vaultApiVersion = "2015-06-01"; string tempVaultName = "bpst-" + RandomGenerator.GetRandomLowerCaseCharacters(12); GenericResource genRes = new GenericResource("westus") { Properties = "{\"sku\": { \"family\": \"A\", \"name\": \"Standard\" }, \"tenantId\": \"" + tenantID + "\", \"accessPolicies\": [], \"enabledForDeployment\": true }" }; operationResponse = managementClient.Resources.CreateOrUpdate(resourceGroup, new ResourceIdentity(tempVaultName, "Microsoft.KeyVault/vaults", vaultApiVersion), genRes); bool operationSucceeded = (operationResponse.StatusCode == System.Net.HttpStatusCode.OK) || (operationResponse.StatusCode == System.Net.HttpStatusCode.Accepted); Thread.Sleep(15000); // The created vault has an Url. DNS propagation will take a while if (operationSucceeded) { ResourceIdentity resIdent = new ResourceIdentity(tempVaultName, "Microsoft.KeyVault/vaults", vaultApiVersion); operationResponse = managementClient.Resources.Delete(resourceGroup, resIdent); operationSucceeded = (operationResponse.StatusCode == System.Net.HttpStatusCode.OK) || (operationResponse.StatusCode == System.Net.HttpStatusCode.Accepted); } if (!operationSucceeded) { return(new ActionResponse(ActionStatus.Failure, JsonUtility.GetEmptyJObject(), "MsCrm_ErrorRegisterKv")); } } clientId = Constants.MicrosoftClientIdCrm; resource = Constants.AzureKeyVaultApi; authBase = string.Format(Constants.AzureAuthUri, aadTenant); break; default: authBase = string.Format(Constants.AzureAuthUri, aadTenant); clientId = Constants.MicrosoftClientId; resource = Constants.AzureManagementApi; break; } StringBuilder builder = GetRawAzureAuthUri(request, authBase, clientId, resource); return(new ActionResponse(ActionStatus.Success, JsonUtility.GetJObjectFromStringValue(builder.ToString()))); }
public static ActionResponse RegisterKeyVault(ActionRequest request) { string azureToken = request.DataStore.GetJson("AzureToken", "access_token"); string subscriptionId = request.DataStore.GetJson("SelectedSubscription", "SubscriptionId"); string resourceGroup = request.DataStore.GetValue("SelectedResourceGroup"); // Make sure the Key Vault is registered SubscriptionCloudCredentials creds = new TokenCloudCredentials(subscriptionId, azureToken); using (ResourceManagementClient managementClient = new ResourceManagementClient(creds)) { ProviderListResult providersResult = managementClient.Providers.List(null); bool kvExists = false; foreach (var p in providersResult.Providers) { if (p.Namespace.EqualsIgnoreCase("Microsoft.KeyVault")) { kvExists = p.RegistrationState.EqualsIgnoreCase("Registered"); break; } } AzureOperationResponse operationResponse; if (!kvExists) { operationResponse = managementClient.Providers.Register("Microsoft.KeyVault"); if (operationResponse.StatusCode != System.Net.HttpStatusCode.OK && operationResponse.StatusCode != System.Net.HttpStatusCode.Accepted) { return(new ActionResponse(ActionStatus.Failure, JsonUtility.GetEmptyJObject(), "MsCrm_ErrorRegisterKv")); } Thread.Sleep(10000); // Wait for it to register } string oid; string tenantID; ExtractUserandTenant(azureToken, out oid, out tenantID); const string vaultApiVersion = "2015-06-01"; string tempVaultName = "bpst-" + RandomGenerator.GetRandomLowerCaseCharacters(12); GenericResource genRes = new GenericResource("westus") { Properties = "{\"sku\": { \"family\": \"A\", \"name\": \"Standard\" }, \"tenantId\": \"" + tenantID + "\", \"accessPolicies\": [], \"enabledForDeployment\": true }" }; operationResponse = managementClient.Resources.CreateOrUpdate(resourceGroup, new ResourceIdentity(tempVaultName, "Microsoft.KeyVault/vaults", vaultApiVersion), genRes); bool operationSucceeded = (operationResponse.StatusCode == System.Net.HttpStatusCode.OK) || (operationResponse.StatusCode == System.Net.HttpStatusCode.Accepted); Thread.Sleep(15000); // The created vault has an Url. DNS propagation will take a while if (operationSucceeded) { ResourceIdentity resIdent = new ResourceIdentity(tempVaultName, "Microsoft.KeyVault/vaults", vaultApiVersion); operationResponse = managementClient.Resources.Delete(resourceGroup, resIdent); operationSucceeded = (operationResponse.StatusCode == System.Net.HttpStatusCode.OK) || (operationResponse.StatusCode == System.Net.HttpStatusCode.Accepted); } if (!operationSucceeded) { return(new ActionResponse(ActionStatus.Failure, JsonUtility.GetEmptyJObject(), "MsCrm_ErrorRegisterKv")); } return(new ActionResponse(ActionStatus.Success)); } }
public void GetsResourceProviderTests() { // setup return values const string RegisteredProviderNamespace = "Providers.Test1"; const string UnregisteredProviderNamespace = "Providers.Test2"; const string ResourceTypeName = "TestResource1"; var unregisteredProvider = new Provider { Namespace = UnregisteredProviderNamespace, RegistrationState = "Unregistered", ResourceTypes = new[] { new ProviderResourceType { Locations = new[] { "West US", "East US", "South US" }, Name = "TestResource2" } } }; var result = new ProviderListResult { NextLink = null, Providers = new[] { new Provider { Namespace = RegisteredProviderNamespace, RegistrationState = ResourcesClient.RegisteredStateName, ResourceTypes = new[] { new ProviderResourceType { Locations = new[] { "West US", "East US" }, Name = ResourceTypeName, } } }, unregisteredProvider, } }; this.providerOperationsMock .Setup(f => f.ListAsync(It.IsAny <ProviderListParameters>(), It.IsAny <CancellationToken>())) .Returns(() => Task.FromResult(result)); // 1. List only registered providers this.commandRuntimeMock .Setup(m => m.WriteObject(It.IsAny <object>())) .Callback((object obj) => { Assert.IsType <PSResourceProvider[]>(obj); var providers = (PSResourceProvider[])obj; Assert.Equal(1, providers.Length); var provider = providers.Single(); Assert.Equal(RegisteredProviderNamespace, provider.ProviderNamespace); Assert.Equal(ResourcesClient.RegisteredStateName, provider.RegistrationState); Assert.Equal(1, provider.ResourceTypes.Length); var resourceType = provider.ResourceTypes.Single(); Assert.Equal(ResourceTypeName, resourceType.ResourceTypeName); Assert.Equal(2, resourceType.Locations.Length); }); this.cmdlet.ParameterSetOverride = GetAzureProviderCmdlet.ListAvailableParameterSet; this.cmdlet.ExecuteCmdlet(); this.VerifyListCallPatternAndReset(); // 2. List all providers this.cmdlet.ListAvailable = true; this.commandRuntimeMock .Setup(m => m.WriteObject(It.IsAny <object>())) .Callback((object obj) => { Assert.IsType <PSResourceProvider[]>(obj); var providers = (PSResourceProvider[])obj; Assert.Equal(2, providers.Length); }); this.cmdlet.ExecuteCmdlet(); this.VerifyListCallPatternAndReset(); // 3. List a single provider by name this.cmdlet.ProviderNamespace = UnregisteredProviderNamespace; this.providerOperationsMock .Setup(f => f.GetAsync(It.IsAny <string>(), It.IsAny <CancellationToken>())) .Returns(() => Task.FromResult(new ProviderGetResult { Provider = unregisteredProvider, RequestId = "requestId", StatusCode = HttpStatusCode.OK, })); this.commandRuntimeMock .Setup(m => m.WriteObject(It.IsAny <object>())) .Callback((object obj) => { Assert.IsType <PSResourceProvider[]>(obj); var providers = (PSResourceProvider[])obj; Assert.Equal(1, providers.Length); var provider = providers.Single(); Assert.Equal(UnregisteredProviderNamespace, provider.ProviderNamespace); }); this.cmdlet.ParameterSetOverride = GetAzureProviderCmdlet.IndividualProviderParameterSet; this.cmdlet.ExecuteCmdlet(); this.VerifyGetCallPatternAndReset(); // 4. List only registered providers with location this.cmdlet.Location = "South US"; this.cmdlet.ListAvailable = false; this.cmdlet.ProviderNamespace = null; this.commandRuntimeMock .Setup(m => m.WriteObject(It.IsAny <object>())) .Callback((object obj) => { Assert.IsType <PSResourceProvider[]>(obj); var providers = (PSResourceProvider[])obj; Assert.Equal(0, providers.Length); }); this.cmdlet.ParameterSetOverride = GetAzureProviderCmdlet.ListAvailableParameterSet; this.cmdlet.ExecuteCmdlet(); this.VerifyListCallPatternAndReset(); // 5. List all providers this.cmdlet.ListAvailable = true; this.cmdlet.Location = "South US"; this.cmdlet.ProviderNamespace = null; this.commandRuntimeMock .Setup(m => m.WriteObject(It.IsAny <object>())) .Callback((object obj) => { var providers = (PSResourceProvider[])obj; Assert.Equal(0, providers.Length); var provider = providers.Single(); Assert.Equal(UnregisteredProviderNamespace, provider.ProviderNamespace); Assert.Equal(1, provider.ResourceTypes.Length); var resourceType = provider.ResourceTypes.Single(); Assert.Equal(ResourceTypeName, resourceType.ResourceTypeName); }); this.cmdlet.ExecuteCmdlet(); this.VerifyListCallPatternAndReset(); }