public GetAzureRmUsageTests()
        {
            insightsUsageMetricOperationsMock = new Mock <IUsageMetricsOperations>();
            insightsClientMock = new Mock <InsightsClient>();
            commandRuntimeMock = new Mock <ICommandRuntime>();
            cmdlet             = new GetAzureRmUsageCommand()
            {
                CommandRuntime = commandRuntimeMock.Object,
                InsightsClient = insightsClientMock.Object
            };

            response = Utilities.InitializeUsageMetricResponse();

            insightsUsageMetricOperationsMock
            .Setup(f => f.ListAsync(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>(), It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult <UsageMetricListResponse>(response))
            .Callback((string f, string s, string a, CancellationToken t) =>
            {
                resourceId = f;
                filter     = s;
                apiVersion = a;
            });

            insightsClientMock
            .SetupGet(f => f.UsageMetricOperations)
            .Returns(this.insightsUsageMetricOperationsMock.Object);
        }
Esempio n. 2
0
        public GetAzureRmUsageTests(Xunit.Abstractions.ITestOutputHelper output)
        {
            ServiceManagemenet.Common.Models.XunitTracingInterceptor.AddToContext(new ServiceManagemenet.Common.Models.XunitTracingInterceptor(output));
            insightsUsageMetricOperationsMock = new Mock <IUsageMetricsOperations>();
            insightsClientMock = new Mock <InsightsClient>();
            commandRuntimeMock = new Mock <ICommandRuntime>();
            cmdlet             = new GetAzureRmUsageCommand()
            {
                CommandRuntime = commandRuntimeMock.Object,
                InsightsClient = insightsClientMock.Object
            };

            response = Utilities.InitializeUsageMetricResponse();

            insightsUsageMetricOperationsMock
            .Setup(f => f.ListAsync(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>(), It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult <UsageMetricListResponse>(response))
            .Callback((string f, string s, string a, CancellationToken t) =>
            {
                resourceId = f;
                filter     = s;
                apiVersion = a;
            });

            insightsClientMock
            .SetupGet(f => f.UsageMetricOperations)
            .Returns(this.insightsUsageMetricOperationsMock.Object);
        }
Esempio n. 3
0
        /// <summary>
        /// Execute the cmdlet
        /// </summary>
        protected override void ProcessRecordInternal()
        {
            string queryFilter = this.ProcessParameters();
            string apiVersion  = this.ApiVersion ?? DefaultApiVersion;

            // Call the proper API methods to return a list of raw records.
            // If fullDetails is present full details of the records displayed, otherwise only a summary of the values is displayed
            UsageMetricListResponse response = this.InsightsClient.UsageMetricOperations
                                               .ListAsync(resourceUri: this.ResourceId, filterString: queryFilter, apiVersion: apiVersion, cancellationToken: CancellationToken.None)
                                               .Result;
            var records = response.UsageMetricCollection.Value
                          .Select(e => new PSUsageMetric(e))
                          .ToArray();

            WriteObject(sendToPipeline: records);
        }
        public void ListUsageTest()
        {
            string resourceUri  = "/subscriptions/123456789/resourceGroups/rg/providers/rp/rUri";
            string filterString = "name.value eq 'CPUTime' or name.value eq 'Requests'";

            UsageMetricCollection expectedUsageMetricCollection = GetUsageMetricCollection(resourceUri);
            HttpResponseMessage   response = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(expectedUsageMetricCollection.ToJson())
            };

            RecordedDelegatingHandler handler = new RecordedDelegatingHandler(response);
            var insightsClient = GetInsightsClient(handler);


            UsageMetricListResponse actualRespose = insightsClient.UsageMetricOperations.List(resourceUri: resourceUri, filterString: filterString, apiVersion: "2014-04-01");

            AreEqual(expectedUsageMetricCollection, actualRespose.UsageMetricCollection);
        }
Esempio n. 5
0
        /// <summary>
        /// The List operation lists the usage metrics for the resource.
        /// </summary>
        /// <param name='resourceUri'>
        /// Required.
        /// </param>
        /// <param name='metricNames'>
        /// Required.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// The List Usage Metric operation response.
        /// </returns>
        public async Task <UsageMetricListResponse> ListAsync(string resourceUri, IList <string> metricNames, CancellationToken cancellationToken)
        {
            // Validate
            if (resourceUri == null)
            {
                throw new ArgumentNullException("resourceUri");
            }
            if (metricNames == null)
            {
                throw new ArgumentNullException("metricNames");
            }

            // 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("resourceUri", resourceUri);
                tracingParameters.Add("metricNames", metricNames);
                Tracing.Enter(invocationId, this, "ListAsync", tracingParameters);
            }

            // Construct URL
            string url = "/" + resourceUri.Trim() + "/usages?";

            url = url + "api-version=2014-01";
            url = url + "&names=" + Uri.EscapeDataString(string.Join(",", metricNames));
            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("Accept", "application/json");
                httpRequest.Headers.Add("x-ms-version", "2014-01");

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

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

                    if (responseDoc != null && responseDoc.Type != JTokenType.Null)
                    {
                        UsageMetricCollection usageMetricCollectionInstance = new UsageMetricCollection();
                        result.UsageMetricCollection = usageMetricCollectionInstance;

                        JToken valueArray = responseDoc["value"];
                        if (valueArray != null && valueArray.Type != JTokenType.Null)
                        {
                            foreach (JToken valueValue in ((JArray)valueArray))
                            {
                                UsageMetric usageMetricInstance = new UsageMetric();
                                usageMetricCollectionInstance.Value.Add(usageMetricInstance);

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

                                JToken displayNameValue = valueValue["displayName"];
                                if (displayNameValue != null && displayNameValue.Type != JTokenType.Null)
                                {
                                    string displayNameInstance = ((string)displayNameValue);
                                    usageMetricInstance.DisplayName = displayNameInstance;
                                }

                                JToken currentValueValue = valueValue["currentValue"];
                                if (currentValueValue != null && currentValueValue.Type != JTokenType.Null)
                                {
                                    double currentValueInstance = ((double)currentValueValue);
                                    usageMetricInstance.CurrentValue = currentValueInstance;
                                }

                                JToken limitValue = valueValue["limit"];
                                if (limitValue != null && limitValue.Type != JTokenType.Null)
                                {
                                    double limitInstance = ((double)limitValue);
                                    usageMetricInstance.Limit = limitInstance;
                                }

                                JToken unitValue = valueValue["unit"];
                                if (unitValue != null && unitValue.Type != JTokenType.Null)
                                {
                                    string unitInstance = ((string)unitValue);
                                    usageMetricInstance.Unit = unitInstance;
                                }

                                JToken nextResetTimeValue = valueValue["nextResetTime"];
                                if (nextResetTimeValue != null && nextResetTimeValue.Type != JTokenType.Null)
                                {
                                    DateTime nextResetTimeInstance = ((DateTime)nextResetTimeValue);
                                    usageMetricInstance.NextResetTime = nextResetTimeInstance;
                                }

                                JToken quotaPeriodValue = valueValue["quotaPeriod"];
                                if (quotaPeriodValue != null && quotaPeriodValue.Type != JTokenType.Null)
                                {
                                    TimeSpan quotaPeriodInstance = TypeConversion.From8601TimeSpan(((string)quotaPeriodValue));
                                    usageMetricInstance.QuotaPeriod = quotaPeriodInstance;
                                }
                            }
                        }

                        JToken propertiesArray = responseDoc["properties"];
                        if (propertiesArray != null && propertiesArray.Type != JTokenType.Null)
                        {
                            foreach (JToken propertiesValue in ((JArray)propertiesArray))
                            {
                                UsageMetric usageMetricInstance2 = new UsageMetric();
                                usageMetricCollectionInstance.Properties.Add(usageMetricInstance2);

                                JToken nameValue2 = propertiesValue["name"];
                                if (nameValue2 != null && nameValue2.Type != JTokenType.Null)
                                {
                                    string nameInstance2 = ((string)nameValue2);
                                    usageMetricInstance2.Name = nameInstance2;
                                }

                                JToken displayNameValue2 = propertiesValue["displayName"];
                                if (displayNameValue2 != null && displayNameValue2.Type != JTokenType.Null)
                                {
                                    string displayNameInstance2 = ((string)displayNameValue2);
                                    usageMetricInstance2.DisplayName = displayNameInstance2;
                                }

                                JToken currentValueValue2 = propertiesValue["currentValue"];
                                if (currentValueValue2 != null && currentValueValue2.Type != JTokenType.Null)
                                {
                                    double currentValueInstance2 = ((double)currentValueValue2);
                                    usageMetricInstance2.CurrentValue = currentValueInstance2;
                                }

                                JToken limitValue2 = propertiesValue["limit"];
                                if (limitValue2 != null && limitValue2.Type != JTokenType.Null)
                                {
                                    double limitInstance2 = ((double)limitValue2);
                                    usageMetricInstance2.Limit = limitInstance2;
                                }

                                JToken unitValue2 = propertiesValue["unit"];
                                if (unitValue2 != null && unitValue2.Type != JTokenType.Null)
                                {
                                    string unitInstance2 = ((string)unitValue2);
                                    usageMetricInstance2.Unit = unitInstance2;
                                }

                                JToken nextResetTimeValue2 = propertiesValue["nextResetTime"];
                                if (nextResetTimeValue2 != null && nextResetTimeValue2.Type != JTokenType.Null)
                                {
                                    DateTime nextResetTimeInstance2 = ((DateTime)nextResetTimeValue2);
                                    usageMetricInstance2.NextResetTime = nextResetTimeInstance2;
                                }

                                JToken quotaPeriodValue2 = propertiesValue["quotaPeriod"];
                                if (quotaPeriodValue2 != null && quotaPeriodValue2.Type != JTokenType.Null)
                                {
                                    TimeSpan quotaPeriodInstance2 = TypeConversion.From8601TimeSpan(((string)quotaPeriodValue2));
                                    usageMetricInstance2.QuotaPeriod = quotaPeriodInstance2;
                                }
                            }
                        }
                    }

                    result.StatusCode = statusCode;
                    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();
                }
            }
        }
        /// <summary>
        /// The List operation lists the usage metrics for the resource.
        /// </summary>
        /// <param name='resourceUri'>
        /// Required. The resource identifier of the target resource to get
        /// usages for.
        /// </param>
        /// <param name='filterString'>
        /// Optional. An OData $filter expression that supports querying by the
        /// name of the usage. For example, "name.value eq 'Percentage CPU'".
        /// Name is optional, meaning the expression may be "".
        /// </param>
        /// <param name='apiVersion'>
        /// Required. The resource provider api version.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// The List Usage Metric operation response.
        /// </returns>
        public async Task <UsageMetricListResponse> ListAsync(string resourceUri, string filterString, string apiVersion, CancellationToken cancellationToken)
        {
            // Validate
            if (resourceUri == null)
            {
                throw new ArgumentNullException("resourceUri");
            }
            if (apiVersion == null)
            {
                throw new ArgumentNullException("apiVersion");
            }

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

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

            // Construct URL
            string url = "";

            url = url + "/";
            url = url + Uri.EscapeDataString(resourceUri);
            url = url + "/usages";
            List <string> queryParameters = new List <string>();

            queryParameters.Add("api-version=" + Uri.EscapeDataString(apiVersion));
            List <string> odataFilter = new List <string>();

            if (filterString != null)
            {
                odataFilter.Add(Uri.EscapeDataString(filterString));
            }
            if (odataFilter.Count > 0)
            {
                queryParameters.Add("$filter=" + string.Join(null, odataFilter));
            }
            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("Accept", "application/json");
                httpRequest.Headers.Add("x-ms-version", apiVersion);

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

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

                        if (responseDoc != null && responseDoc.Type != JTokenType.Null)
                        {
                            UsageMetricCollection usageMetricCollectionInstance = new UsageMetricCollection();
                            result.UsageMetricCollection = usageMetricCollectionInstance;

                            JToken valueArray = responseDoc["value"];
                            if (valueArray != null && valueArray.Type != JTokenType.Null)
                            {
                                foreach (JToken valueValue in ((JArray)valueArray))
                                {
                                    UsageMetric usageMetricInstance = new UsageMetric();
                                    usageMetricCollectionInstance.Value.Add(usageMetricInstance);

                                    JToken nameValue = valueValue["name"];
                                    if (nameValue != null && nameValue.Type != JTokenType.Null)
                                    {
                                        LocalizableString nameInstance = new LocalizableString();
                                        usageMetricInstance.Name = nameInstance;

                                        JToken valueValue2 = nameValue["value"];
                                        if (valueValue2 != null && valueValue2.Type != JTokenType.Null)
                                        {
                                            string valueInstance = ((string)valueValue2);
                                            nameInstance.Value = valueInstance;
                                        }

                                        JToken localizedValueValue = nameValue["localizedValue"];
                                        if (localizedValueValue != null && localizedValueValue.Type != JTokenType.Null)
                                        {
                                            string localizedValueInstance = ((string)localizedValueValue);
                                            nameInstance.LocalizedValue = localizedValueInstance;
                                        }
                                    }

                                    JToken currentValueValue = valueValue["currentValue"];
                                    if (currentValueValue != null && currentValueValue.Type != JTokenType.Null)
                                    {
                                        double currentValueInstance = ((double)currentValueValue);
                                        usageMetricInstance.CurrentValue = currentValueInstance;
                                    }

                                    JToken limitValue = valueValue["limit"];
                                    if (limitValue != null && limitValue.Type != JTokenType.Null)
                                    {
                                        double limitInstance = ((double)limitValue);
                                        usageMetricInstance.Limit = limitInstance;
                                    }

                                    JToken unitValue = valueValue["unit"];
                                    if (unitValue != null && unitValue.Type != JTokenType.Null)
                                    {
                                        string unitInstance = ((string)unitValue);
                                        usageMetricInstance.Unit = unitInstance;
                                    }

                                    JToken nextResetTimeValue = valueValue["nextResetTime"];
                                    if (nextResetTimeValue != null && nextResetTimeValue.Type != JTokenType.Null)
                                    {
                                        string nextResetTimeInstance = ((string)nextResetTimeValue);
                                        usageMetricInstance.NextResetTime = nextResetTimeInstance;
                                    }

                                    JToken quotaPeriodValue = valueValue["quotaPeriod"];
                                    if (quotaPeriodValue != null && quotaPeriodValue.Type != JTokenType.Null)
                                    {
                                        TimeSpan quotaPeriodInstance = XmlConvert.ToTimeSpan(((string)quotaPeriodValue));
                                        usageMetricInstance.QuotaPeriod = quotaPeriodInstance;
                                    }
                                }
                            }
                        }
                    }
                    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();
                }
            }
        }