public override async Task <ActionResponse> ExecuteActionAsync(ActionRequest request) { var azureToken = request.DataStore.GetJson("AzureToken")["access_token"].ToString(); CloudCredentials creds = new TokenCloudCredentials(azureToken); dynamic subscriptionWrapper = new ExpandoObject(); List <Subscription> validSubscriptions = new List <Subscription>(); using (SubscriptionClient client = new SubscriptionClient(creds)) { SubscriptionListResult subscriptionList = await client.Subscriptions.ListAsync(); foreach (Subscription s in subscriptionList.Subscriptions) { if (s.State.Equals("Disabled", System.StringComparison.OrdinalIgnoreCase) || s.State.Equals("Deleted", System.StringComparison.OrdinalIgnoreCase)) { continue; } validSubscriptions.Add(s); } subscriptionWrapper.value = validSubscriptions; } request.Logger.LogEvent("GetAzureSubscriptions-result", new Dictionary <string, string>() { { "Subscriptions", string.Join(",", validSubscriptions.Select(p => p.SubscriptionId)) } }); return(new ActionResponse(ActionStatus.Success, subscriptionWrapper)); }
/// <summary> /// Select the subscription id to use in the rest of the sample. /// </summary> /// <param name="client">The <see cref="Microsoft.Azure.Subscriptions.SubscriptionClient"/> to use to get all the subscriptions /// under the user's Azure account.</param> /// <returns>A <see cref="System.Threading.Tasks.Task"/> object that represents the asynchronous operation.</returns> /// <remarks>If the user has 1 subscription under their Azure account, it is chosen automatically. If the user has more than /// one, they are prompted to make a selection.</remarks> private static async Task <string> SelectSubscriptionAsync(SubscriptionClient client) { SubscriptionListResult subs = await client.Subscriptions.ListAsync(); if (subs.Subscriptions.Any()) { if (subs.Subscriptions.Count > 1) { // More than 1 subscription found under the Azure account, prompt the user for the subscription to use string[] subscriptionNames = subs.Subscriptions.Select(s => s.DisplayName).ToArray(); string selectedSubscription = PromptForSelectionFromCollection(subscriptionNames, "Enter the number of the Azure subscription to use: "); Subscription selectedSub = subs.Subscriptions.First(s => s.DisplayName.Equals(selectedSubscription)); return(selectedSub.SubscriptionId); } else { // Only one subscription found, use that one return(subs.Subscriptions.First().SubscriptionId); } } else { throw new InvalidOperationException("No subscriptions found in account. Please create at least one subscription within your Azure account."); } }
public static async Task IterateSubscriptions(this SubscriptionClient subscriptionClient, CancellationToken ct, Func <Subscription, Task> action) { SubscriptionListResult subscriptionListResult = await subscriptionClient.Subscriptions.ListAsync(ct); string subscriptionContinuationToken = subscriptionListResult.NextLink; foreach (var subscription in subscriptionListResult.Subscriptions) { await action(subscription); } while (!string.IsNullOrEmpty(subscriptionContinuationToken)) { subscriptionListResult = await subscriptionClient.Subscriptions.ListNextAsync(nextLink : subscriptionContinuationToken, cancellationToken : ct); subscriptionContinuationToken = subscriptionListResult.NextLink; foreach (var subscription in subscriptionListResult.Subscriptions) { await action(subscription); } } }
public SubscriptionClient GetSubscriptionClient() { var tenantMock = new Mock <ITenantOperations>(); tenantMock.Setup(t => t.ListAsync(It.IsAny <CancellationToken>())) .Returns( (CancellationToken token) => Task.FromResult(new TenantListResult() { StatusCode = HttpStatusCode.OK, RequestId = Guid.NewGuid().ToString(), TenantIds = _tenants.Select((k) => new TenantIdDescription() { Id = k, TenantId = k }).ToList() })); var subscriptionMock = new Mock <ISubscriptionOperations>(); subscriptionMock.Setup( s => s.GetAsync(It.IsAny <string>(), It.IsAny <CancellationToken>())).Returns( (string subId, CancellationToken token) => { GetSubscriptionResult result = new GetSubscriptionResult { RequestId = Guid.NewGuid().ToString(), StatusCode = HttpStatusCode.NotFound }; if (_subscriptionSet.Contains(subId)) { result.StatusCode = HttpStatusCode.OK; result.Subscription = new Subscription { DisplayName = GetSubscriptionNameFromId(subId), Id = subId, State = "Active", SubscriptionId = subId }; } return(Task.FromResult(result)); }); subscriptionMock.Setup( (s) => s.ListAsync(It.IsAny <CancellationToken>())).Returns( (CancellationToken token) => { SubscriptionListResult result = null; if (_subscriptions.Count > 0) { var subscriptionList = _subscriptions.Dequeue(); result = new SubscriptionListResult { StatusCode = HttpStatusCode.OK, RequestId = Guid.NewGuid().ToString(), NextLink = "LinkToNextPage", Subscriptions = new List <Subscription>( subscriptionList.Select( sub => new Subscription { DisplayName = GetSubscriptionNameFromId(sub), Id = sub, State = "Active", SubscriptionId = sub })) }; } return(Task.FromResult(result)); }); subscriptionMock.Setup( (s) => s.ListNextAsync("LinkToNextPage", It.IsAny <CancellationToken>())).Returns( (string nextLink, CancellationToken token) => { SubscriptionListResult result = null; if (_subscriptions.Count > 0) { var subscriptionList = _subscriptions.Dequeue(); result = new SubscriptionListResult { StatusCode = HttpStatusCode.OK, RequestId = Guid.NewGuid().ToString(), Subscriptions = new List <Subscription>( subscriptionList.Select( sub => new Subscription { DisplayName = nextLink, Id = sub, State = "Disabled", SubscriptionId = sub })) }; } return(Task.FromResult(result)); }); var client = new Mock <SubscriptionClient>(); client.SetupGet(c => c.Subscriptions).Returns(subscriptionMock.Object); client.SetupGet(c => c.Tenants).Returns(tenantMock.Object); return(client.Object); }
/// <summary> /// Gets a list of the subscriptionIds. /// </summary> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Subscription list operation response. /// </returns> public async Task <SubscriptionListResult> ListAsync(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>(); TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters); } // Construct URL string url = "/subscriptions?"; 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 SubscriptionListResult result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new SubscriptionListResult(); 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)) { Subscription subscriptionInstance = new Subscription(); result.Subscriptions.Add(subscriptionInstance); JToken idValue = valueValue["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); subscriptionInstance.Id = idInstance; } JToken subscriptionIdValue = valueValue["subscriptionId"]; if (subscriptionIdValue != null && subscriptionIdValue.Type != JTokenType.Null) { string subscriptionIdInstance = ((string)subscriptionIdValue); subscriptionInstance.SubscriptionId = subscriptionIdInstance; } JToken displayNameValue = valueValue["displayName"]; if (displayNameValue != null && displayNameValue.Type != JTokenType.Null) { string displayNameInstance = ((string)displayNameValue); subscriptionInstance.DisplayName = displayNameInstance; } JToken stateValue = valueValue["state"]; if (stateValue != null && stateValue.Type != JTokenType.Null) { string stateInstance = ((string)stateValue); subscriptionInstance.State = stateInstance; } } } } } 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 azureToken = request.DataStore.GetJson("AzureToken", "access_token"); // Show location selection on the page var showLocationsString = request.DataStore.GetValue("showLocations"); // For certain service, it only exists in few regions so add the allowed location list var allowedLocations = request.DataStore.GetValue("allowedLocations"); bool.TryParse(showLocationsString, out bool showLocations); string[] allowedLocationsList = null; if (showLocations && !string.IsNullOrWhiteSpace(allowedLocations)) { allowedLocationsList = allowedLocations.Split(new char[] { ',', ';' }, System.StringSplitOptions.RemoveEmptyEntries); } CloudCredentials creds = new TokenCloudCredentials(azureToken); dynamic subscriptionWrapper = new ExpandoObject(); List <Subscription> validSubscriptions = new List <Subscription>(); using (SubscriptionClient client = new SubscriptionClient(creds)) { SubscriptionListResult subscriptionList = await client.Subscriptions.ListAsync(); foreach (Subscription s in subscriptionList.Subscriptions) { if (s.State.EqualsIgnoreCase("Disabled") || s.State.EqualsIgnoreCase("Deleted")) { continue; } if (!showLocations) { validSubscriptions.Add(s); } else { var locationsList = (await client.Subscriptions.ListLocationsAsync(s.SubscriptionId, new CancellationToken())).Locations.ToList(); if (allowedLocationsList != null && allowedLocationsList.Length > 0) { locationsList = locationsList.Where(l => allowedLocationsList.Contains(l.Name, StringComparer.OrdinalIgnoreCase)).ToList(); } var subscription = new SubscriptionWithLocations() { SubscriptionId = s.SubscriptionId, DisplayName = s.DisplayName, State = s.State, SubscriptionPolicies = s.SubscriptionPolicies, Locations = locationsList }; validSubscriptions.Add(subscription); } } subscriptionWrapper.value = validSubscriptions; } request.Logger.LogEvent("GetAzureSubscriptions-result", new Dictionary <string, string>() { { "Subscriptions", string.Join(",", validSubscriptions.Select(p => p.SubscriptionId)) } }); return(new ActionResponse(ActionStatus.Success, subscriptionWrapper)); }
/// <summary> /// Lists the next set of subscriptions /// </summary> /// <param name='nextLink'> /// Required. URL to get the next set of results /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Result of subscription list operation /// </returns> public async Task <SubscriptionListResult> 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 = ""; url = url + Uri.EscapeDataString(nextLink); 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 SubscriptionListResult result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new SubscriptionListResult(); 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)) { SubscriptionDefinition subscriptionDefinitionInstance = new SubscriptionDefinition(); result.Subscriptions.Add(subscriptionDefinitionInstance); JToken idValue = valueValue["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); subscriptionDefinitionInstance.Id = idInstance; } JToken subscriptionIdValue = valueValue["subscriptionId"]; if (subscriptionIdValue != null && subscriptionIdValue.Type != JTokenType.Null) { string subscriptionIdInstance = ((string)subscriptionIdValue); subscriptionDefinitionInstance.SubscriptionId = subscriptionIdInstance; } JToken displayNameValue = valueValue["displayName"]; if (displayNameValue != null && displayNameValue.Type != JTokenType.Null) { string displayNameInstance = ((string)displayNameValue); subscriptionDefinitionInstance.DisplayName = displayNameInstance; } JToken externalReferenceIdValue = valueValue["externalReferenceId"]; if (externalReferenceIdValue != null && externalReferenceIdValue.Type != JTokenType.Null) { string externalReferenceIdInstance = ((string)externalReferenceIdValue); subscriptionDefinitionInstance.ExternalReferenceId = externalReferenceIdInstance; } JToken offerIdValue = valueValue["offerId"]; if (offerIdValue != null && offerIdValue.Type != JTokenType.Null) { string offerIdInstance = ((string)offerIdValue); subscriptionDefinitionInstance.OfferId = offerIdInstance; } JToken stateValue = valueValue["state"]; if (stateValue != null && stateValue.Type != JTokenType.Null) { SubscriptionState stateInstance = ((SubscriptionState)Enum.Parse(typeof(SubscriptionState), ((string)stateValue), true)); subscriptionDefinitionInstance.State = stateInstance; } } } JToken odatanextLinkValue = responseDoc["@odata.nextLink"]; if (odatanextLinkValue != null && odatanextLinkValue.Type != JTokenType.Null) { string odatanextLinkInstance = ((string)odatanextLinkValue); result.NextLink = odatanextLinkInstance; } } } result.StatusCode = statusCode; if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return(result); } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } }
/// <summary> /// Lists the subscriptions under the user account /// </summary> /// <param name='includeDetails'> /// Required. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Result of subscription list operation /// </returns> public async Task <SubscriptionListResult> ListAsync(bool includeDetails, 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("includeDetails", includeDetails); TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions"; List <string> queryParameters = new List <string>(); queryParameters.Add("api-version=" + Uri.EscapeDataString(this.Client.ApiVersion)); queryParameters.Add("includeDetails=" + Uri.EscapeDataString(includeDetails.ToString().ToLower())); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } 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 SubscriptionListResult result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new SubscriptionListResult(); 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)) { SubscriptionDefinition subscriptionDefinitionInstance = new SubscriptionDefinition(); result.Subscriptions.Add(subscriptionDefinitionInstance); JToken idValue = valueValue["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); subscriptionDefinitionInstance.Id = idInstance; } JToken subscriptionIdValue = valueValue["subscriptionId"]; if (subscriptionIdValue != null && subscriptionIdValue.Type != JTokenType.Null) { string subscriptionIdInstance = ((string)subscriptionIdValue); subscriptionDefinitionInstance.SubscriptionId = subscriptionIdInstance; } JToken displayNameValue = valueValue["displayName"]; if (displayNameValue != null && displayNameValue.Type != JTokenType.Null) { string displayNameInstance = ((string)displayNameValue); subscriptionDefinitionInstance.DisplayName = displayNameInstance; } JToken externalReferenceIdValue = valueValue["externalReferenceId"]; if (externalReferenceIdValue != null && externalReferenceIdValue.Type != JTokenType.Null) { string externalReferenceIdInstance = ((string)externalReferenceIdValue); subscriptionDefinitionInstance.ExternalReferenceId = externalReferenceIdInstance; } JToken offerIdValue = valueValue["offerId"]; if (offerIdValue != null && offerIdValue.Type != JTokenType.Null) { string offerIdInstance = ((string)offerIdValue); subscriptionDefinitionInstance.OfferId = offerIdInstance; } JToken stateValue = valueValue["state"]; if (stateValue != null && stateValue.Type != JTokenType.Null) { SubscriptionState stateInstance = ((SubscriptionState)Enum.Parse(typeof(SubscriptionState), ((string)stateValue), true)); subscriptionDefinitionInstance.State = stateInstance; } } } JToken odatanextLinkValue = responseDoc["@odata.nextLink"]; if (odatanextLinkValue != null && odatanextLinkValue.Type != JTokenType.Null) { string odatanextLinkInstance = ((string)odatanextLinkValue); result.NextLink = odatanextLinkInstance; } } } result.StatusCode = statusCode; if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return(result); } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } }