public void Test_SubscriptionOperations_E2E()
        {
            BasicDelegatingHandler handler = new BasicDelegatingHandler();

            using (var undoContext = UndoContext.Current)
            {
                undoContext.Start();

                string resourceGroupName = TestUtilities.GenerateName("StreamAnalytics");
                string serviceLocation   = TestHelper.GetDefaultLocation();

                var resourceClient = TestHelper.GetResourceClient(handler);
                var client         = TestHelper.GetStreamAnalyticsManagementClient(handler);

                try
                {
                    ResourceGroup resourceGroup = new ResourceGroup()
                    {
                        Location = serviceLocation
                    };
                    resourceClient.ResourceGroups.CreateOrUpdate(resourceGroupName, resourceGroup);

                    SubscriptionQuotasGetResponse subscriptionQuotasGetResponse = client.Subscriptions.GetQuotas(serviceLocation);
                    Assert.Equal(HttpStatusCode.OK, subscriptionQuotasGetResponse.StatusCode);
                    Assert.Equal(1, subscriptionQuotasGetResponse.Value.FirstOrDefault().Properties.CurrentCount);
                    Assert.Equal(50, subscriptionQuotasGetResponse.Value.FirstOrDefault().Properties.MaxCount);
                }
                finally
                {
                    resourceClient.ResourceGroups.Delete(resourceGroupName);
                }
            }
        }
Esempio n. 2
0
        /// <summary>
        /// Gets the quotas of the subscription in the Batch Service.
        /// </summary>
        /// <param name="location">The location to use when getting the Batch subscription quotas.</param>
        /// <returns>A PSBatchSubscriptionQuotas object containing the subscription quotas.</returns>
        public virtual PSBatchSubscriptionQuotas GetSubscriptionQuotas(string location)
        {
            if (string.IsNullOrEmpty(location))
            {
                throw new ArgumentNullException("location");
            }

            WriteVerbose(string.Format(Resources.GettingSubscriptionQuotas, location));

            SubscriptionQuotasGetResponse response = this.BatchManagementClient.Subscriptions.GetSubscriptionQuotas(location);

            return(new PSBatchSubscriptionQuotas(location, response));
        }
        public PSBatchSubscriptionQuotas(string location, SubscriptionQuotasGetResponse subscriptionQuotasResponse)
        {
            if (string.IsNullOrEmpty(location))
            {
                throw new ArgumentNullException("location");
            }

            if (subscriptionQuotasResponse == null)
            {
                throw new ArgumentNullException("subscriptionQuotasResponse");
            }

            this.Location     = location;
            this.AccountQuota = subscriptionQuotasResponse.AccountQuota;
        }
        /// <summary>
        /// Get the stream analytics quotas of a subscription.
        /// </summary>
        /// <param name='location'>
        /// Required. The region that you want to check the quotas.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// The response of the get stream analytics quotas operation.
        /// </returns>
        public async Task <SubscriptionQuotasGetResponse> GetQuotasAsync(string location, CancellationToken cancellationToken)
        {
            // Validate
            if (location == null)
            {
                throw new ArgumentNullException("location");
            }

            // Tracing
            bool   shouldTrace  = CloudContext.Configuration.Tracing.IsEnabled;
            string invocationId = null;

            if (shouldTrace)
            {
                invocationId = Tracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("location", location);
                Tracing.Enter(invocationId, this, "GetQuotasAsync", tracingParameters);
            }

            // Construct URL
            string url = "/subscriptions/" + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId) + "/providers/Microsoft.StreamAnalytics/locations/" + Uri.EscapeDataString(location) + "/quotas?";

            url = url + "api-version=2014-12-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
                httpRequest.Headers.Add("x-ms-client-request-id", Guid.NewGuid().ToString());

                // Set Credentials
                cancellationToken.ThrowIfCancellationRequested();
                await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);

                // Send Request
                HttpResponseMessage httpResponse = null;
                try
                {
                    if (shouldTrace)
                    {
                        Tracing.SendRequest(invocationId, httpRequest);
                    }
                    cancellationToken.ThrowIfCancellationRequested();
                    httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);

                    if (shouldTrace)
                    {
                        Tracing.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)
                        {
                            Tracing.Error(invocationId, ex);
                        }
                        throw ex;
                    }

                    // Create Result
                    SubscriptionQuotasGetResponse result = null;
                    // Deserialize Response
                    cancellationToken.ThrowIfCancellationRequested();
                    string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                    result = new SubscriptionQuotasGetResponse();
                    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))
                            {
                                SubscriptionQuotas subscriptionQuotasInstance = new SubscriptionQuotas();
                                result.Value.Add(subscriptionQuotasInstance);

                                JToken nameValue = valueValue["name"];
                                if (nameValue != null && nameValue.Type != JTokenType.Null)
                                {
                                    string nameInstance = ((string)nameValue);
                                    subscriptionQuotasInstance.Name = nameInstance;
                                }

                                JToken propertiesValue = valueValue["properties"];
                                if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
                                {
                                    SubscriptionQuotasProperties propertiesInstance = new SubscriptionQuotasProperties();
                                    subscriptionQuotasInstance.Properties = propertiesInstance;

                                    JToken maxCountValue = propertiesValue["maxCount"];
                                    if (maxCountValue != null && maxCountValue.Type != JTokenType.Null)
                                    {
                                        int maxCountInstance = ((int)maxCountValue);
                                        propertiesInstance.MaxCount = maxCountInstance;
                                    }

                                    JToken currentCountValue = propertiesValue["currentCount"];
                                    if (currentCountValue != null && currentCountValue.Type != JTokenType.Null)
                                    {
                                        int currentCountInstance = ((int)currentCountValue);
                                        propertiesInstance.CurrentCount = currentCountInstance;
                                    }
                                }
                            }
                        }
                    }

                    result.StatusCode = statusCode;
                    if (httpResponse.Headers.Contains("Date"))
                    {
                        result.Date = DateTime.Parse(httpResponse.Headers.GetValues("Date").FirstOrDefault(), CultureInfo.InvariantCulture);
                    }
                    if (httpResponse.Headers.Contains("x-ms-request-id"))
                    {
                        result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
                    }

                    if (shouldTrace)
                    {
                        Tracing.Exit(invocationId, result);
                    }
                    return(result);
                }
                finally
                {
                    if (httpResponse != null)
                    {
                        httpResponse.Dispose();
                    }
                }
            }
            finally
            {
                if (httpRequest != null)
                {
                    httpRequest.Dispose();
                }
            }
        }
Esempio n. 5
0
        /// <summary>
        /// Performs various Batch account operations using the Batch Management library.
        /// </summary>
        /// <param name="creds">The <see cref="Microsoft.Azure.TokenCloudCredentials"/> containing information about the user's
        /// Azure account and subscription.</param>
        /// <param name="location">The location where the Batch account will be created.</param>
        /// <returns>A <see cref="System.Threading.Tasks.Task"/> object that represents the asynchronous operation.</returns>
        private static async Task PerformBatchAccountOperationsAsync(TokenCloudCredentials creds, string location)
        {
            using (BatchManagementClient batchManagementClient = new BatchManagementClient(creds))
            {
                // Get the account quota for the subscription
                SubscriptionQuotasGetResponse quotaResponse = await batchManagementClient.Subscriptions.GetSubscriptionQuotasAsync(location);

                Console.WriteLine("Your subscription can create {0} account(s) in the {1} region.", quotaResponse.AccountQuota, location);
                Console.WriteLine();

                // Create account
                string accountName = PromptUserForAccountName();
                Console.WriteLine("Creating account {0}...", accountName);
                await batchManagementClient.Accounts.CreateAsync(ResourceGroupName, accountName, new BatchAccountCreateParameters()
                {
                    Location = location
                });

                Console.WriteLine("Account {0} created", accountName);
                Console.WriteLine();

                // Get account
                Console.WriteLine("Getting account {0}...", accountName);
                BatchAccountGetResponse getResponse = await batchManagementClient.Accounts.GetAsync(ResourceGroupName, accountName);

                AccountResource account = getResponse.Resource;
                Console.WriteLine("Got account {0}:", account.Name);
                Console.WriteLine("  Account location: {0}", account.Location);
                Console.WriteLine("  Account resource type: {0}", account.Type);
                Console.WriteLine("  Account id: {0}", account.Id);
                Console.WriteLine();

                // Print account quotas
                Console.WriteLine("Quotas for account {0}:", account.Name);
                Console.WriteLine("  Core quota: {0}", account.Properties.CoreQuota);
                Console.WriteLine("  Pool quota: {0}", account.Properties.PoolQuota);
                Console.WriteLine("  Active job and job schedule quota: {0}", account.Properties.ActiveJobAndJobScheduleQuota);
                Console.WriteLine();

                // Get account keys
                Console.WriteLine("Getting account keys of account {0}...", account.Name);
                BatchAccountListKeyResponse accountKeys = await batchManagementClient.Accounts.ListKeysAsync(ResourceGroupName, account.Name);

                Console.WriteLine("  Primary key of account {0}:   {1}", account.Name, accountKeys.PrimaryKey);
                Console.WriteLine("  Secondary key of account {0}: {1}", account.Name, accountKeys.SecondaryKey);
                Console.WriteLine();

                // Regenerate primary account key
                Console.WriteLine("Regenerating the primary key of account {0}...", account.Name);
                BatchAccountRegenerateKeyResponse newKeys = await batchManagementClient.Accounts.RegenerateKeyAsync(
                    ResourceGroupName, account.Name,
                    new BatchAccountRegenerateKeyParameters()
                {
                    KeyName = AccountKeyType.Primary
                });

                Console.WriteLine("  New primary key of account {0}: {1}", account.Name, newKeys.PrimaryKey);
                Console.WriteLine("  Secondary key of account {0}:   {1}", account.Name, newKeys.SecondaryKey);
                Console.WriteLine();

                // Print subscription quota information
                BatchAccountListResponse listResponse = await batchManagementClient.Accounts.ListAsync(new AccountListParameters());

                IList <AccountResource> accounts = listResponse.Accounts;
                Console.WriteLine("Total number of Batch accounts under subscription id {0}:  {1}", creds.SubscriptionId, accounts.Count);

                // Determine how many additional accounts can be created in the target region
                int numAccountsInRegion = accounts.Count(o => o.Location == account.Location);
                Console.WriteLine("Accounts in {0}: {1}", account.Location, numAccountsInRegion);
                Console.WriteLine("You can create {0} more accounts in the {1} region.", quotaResponse.AccountQuota - numAccountsInRegion, account.Location);
                Console.WriteLine();

                // List accounts in the subscription
                Console.WriteLine("Listing all Batch accounts under subscription id {0}...", creds.SubscriptionId);
                foreach (AccountResource acct in accounts)
                {
                    Console.WriteLine("  {0} - {1} | Location: {2}", accounts.IndexOf(acct) + 1, acct.Name, acct.Location);
                }
                Console.WriteLine();

                // Delete account
                Console.Write("Hit ENTER to delete account {0}: ", account.Name);
                Console.ReadLine();
                Console.WriteLine("Deleting account {0}...", account.Name);
                await batchManagementClient.Accounts.DeleteAsync(ResourceGroupName, account.Name);

                Console.WriteLine("Account {0} deleted", account.Name);
                Console.WriteLine();
            }
        }
Esempio n. 6
0
        /// <summary>
        /// Performs various Batch account operations using the Batch Management library.
        /// </summary>
        /// <param name="context">The <see cref="Microsoft.Azure.Common.Authentication.Models.AzureContext"/> containing information
        /// about the user's Azure account and subscription.</param>
        /// <param name="accountName">The name of the Batch account to create.</param>
        /// <param name="location">The location where the Batch account will be created.</param>
        /// <returns>A <see cref="System.Threading.Tasks.Task"/> object that represents the asynchronous operation.</returns>
        private static async Task PerformBatchAccountOperationsAsync(AzureContext context, string accountName, string location)
        {
            using (IBatchManagementClient batchManagementClient =
                       AzureSession.ClientFactory.CreateClient <BatchManagementClient>(context, AzureEnvironment.Endpoint.ResourceManager))
            {
                // Get the account quota for the subscription
                SubscriptionQuotasGetResponse quotaResponse = await batchManagementClient.Subscriptions.GetSubscriptionQuotasAsync(location);

                Console.WriteLine("Your subscription can create {0} account(s) in the {1} region.", quotaResponse.AccountQuota, location);
                Console.WriteLine();

                // Create account
                Console.WriteLine("Creating account {0} ...", accountName);
                await batchManagementClient.Accounts.CreateAsync(ResourceGroupName, accountName, new BatchAccountCreateParameters()
                {
                    Location = location
                });

                Console.WriteLine("Account {0} created", accountName);
                Console.WriteLine();

                // Get account
                Console.WriteLine("Getting account {0} ...", accountName);
                BatchAccountGetResponse getResponse = await batchManagementClient.Accounts.GetAsync(ResourceGroupName, accountName);

                AccountResource account = getResponse.Resource;
                Console.WriteLine("Got account {0}:", accountName);
                Console.WriteLine(" Account location: {0}", account.Location);
                Console.WriteLine(" Account resource type: {0}", account.Type);
                Console.WriteLine(" Account id: {0}", account.Id);
                Console.WriteLine(" Core quota: {0}", account.Properties.CoreQuota);
                Console.WriteLine(" Pool quota: {0}", account.Properties.PoolQuota);
                Console.WriteLine(" Active job and job schedule quota: {0}", account.Properties.ActiveJobAndJobScheduleQuota);
                Console.WriteLine();

                // Get account keys
                Console.WriteLine("Getting account keys of account {0} ....", accountName);
                BatchAccountListKeyResponse accountKeys = await batchManagementClient.Accounts.ListKeysAsync(ResourceGroupName, accountName);

                Console.WriteLine("Primary key of account {0}:", accountName);
                Console.WriteLine(accountKeys.PrimaryKey);
                Console.WriteLine("Secondary key of account {0}:", accountName);
                Console.WriteLine(accountKeys.SecondaryKey);
                Console.WriteLine();

                // Regenerate account key
                Console.WriteLine("Regenerating the primary key of account {0} ....", accountName);
                BatchAccountRegenerateKeyResponse newKeys = await batchManagementClient.Accounts.RegenerateKeyAsync(ResourceGroupName, accountName,
                                                                                                                    new BatchAccountRegenerateKeyParameters()
                {
                    KeyName = AccountKeyType.Primary
                });

                Console.WriteLine("New primary key of account {0}:", accountName);
                Console.WriteLine(newKeys.PrimaryKey);
                Console.WriteLine("Secondary key of account {0}:", accountName);
                Console.WriteLine(newKeys.SecondaryKey);
                Console.WriteLine();

                // List accounts
                Console.WriteLine("Listing all Batch accounts under subscription id {0} ...", context.Subscription.Id);
                BatchAccountListResponse listResponse = await batchManagementClient.Accounts.ListAsync(new AccountListParameters());

                IList <AccountResource> accounts = listResponse.Accounts;
                Console.WriteLine("Total number of Batch accounts under subscription id {0}:  {1}", context.Subscription.Id, accounts.Count);
                for (int i = 0; i < accounts.Count; i++)
                {
                    Console.WriteLine(" {0} - {1}", i + 1, accounts[i].Name);
                }
                Console.WriteLine();

                // Delete account
                Console.WriteLine("Deleting account {0} ...", accountName);
                await batchManagementClient.Accounts.DeleteAsync(ResourceGroupName, accountName);

                Console.WriteLine("Account {0} deleted", accountName);
                Console.WriteLine();
            }
        }
        /// <summary>
        /// The Get Subscription Quotas operation returns the quotas of the
        /// subscription in the Batch service.
        /// </summary>
        /// <param name='locationName'>
        /// Required.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// Values returned by the Get Subscription Quotas operation.
        /// </returns>
        public async Task <SubscriptionQuotasGetResponse> GetSubscriptionQuotasAsync(string locationName, CancellationToken cancellationToken)
        {
            // Validate
            if (locationName == null)
            {
                throw new ArgumentNullException("locationName");
            }

            // Tracing
            bool   shouldTrace  = TracingAdapter.IsEnabled;
            string invocationId = null;

            if (shouldTrace)
            {
                invocationId = TracingAdapter.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("locationName", locationName);
                TracingAdapter.Enter(invocationId, this, "GetSubscriptionQuotasAsync", tracingParameters);
            }

            // Construct URL
            string url = "";

            url = url + "/subscriptions/";
            if (this.Client.Credentials.SubscriptionId != null)
            {
                url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
            }
            url = url + "/providers/";
            url = url + "Microsoft.Batch";
            url = url + "/locations/";
            url = url + Uri.EscapeDataString(locationName);
            url = url + "/quotas";
            List <string> queryParameters = new List <string>();

            queryParameters.Add("api-version=2015-09-01");
            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
                httpRequest.Headers.Add("x-ms-version", "2015-09-01");

                // 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
                    SubscriptionQuotasGetResponse result = null;
                    // Deserialize Response
                    if (statusCode == HttpStatusCode.OK)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                        result = new SubscriptionQuotasGetResponse();
                        JToken responseDoc = null;
                        if (string.IsNullOrEmpty(responseContent) == false)
                        {
                            responseDoc = JToken.Parse(responseContent);
                        }

                        if (responseDoc != null && responseDoc.Type != JTokenType.Null)
                        {
                            JToken accountQuotaValue = responseDoc["accountQuota"];
                            if (accountQuotaValue != null && accountQuotaValue.Type != JTokenType.Null)
                            {
                                int accountQuotaInstance = ((int)accountQuotaValue);
                                result.AccountQuota = accountQuotaInstance;
                            }
                        }
                    }
                    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();
                }
            }
        }