コード例 #1
0
        /// <summary>
        /// The List Metric Value operation lists the metric value sets for the
        /// resource metrics.
        /// </summary>
        /// <param name='resourceId'>
        /// The id of the resource.
        /// </param>
        /// <param name='metricNames'>
        /// The names of the metrics.
        /// </param>
        /// <param name='metricNamespace'>
        /// The namespace of the metrics.
        /// </param>
        /// <param name='timeGrain'>
        /// The time grain of the metrics.
        /// </param>
        /// <param name='startTime'>
        /// The start time (in UTC) of the metrics.
        /// </param>
        /// <param name='endTime'>
        /// The end time (in UTC) of the metrics.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// The List Metric values operation response.
        /// </returns>
        public async Task <MetricValueListResponse> ListAsync(string resourceId, IList <string> metricNames, string metricNamespace, TimeSpan timeGrain, DateTime startTime, DateTime endTime, CancellationToken cancellationToken)
        {
            // Validate
            if (resourceId == null)
            {
                throw new ArgumentNullException("resourceId");
            }
            if (metricNames == null)
            {
                throw new ArgumentNullException("metricNames");
            }
            if (metricNames.Count <= 0)
            {
                throw new ArgumentException("metricNames cannot be empty.");
            }

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

            // Construct URL
            string url = new Uri(this.Client.BaseUri, "/").ToString() + this.Client.Credentials.SubscriptionId + "/services/monitoring/metricvalues/query?";

            url = url + "&resourceId=" + Uri.EscapeUriString(resourceId);
            if (metricNamespace != null)
            {
                url = url + "&namespace=" + Uri.EscapeUriString(metricNamespace);
            }
            url = url + "&names=" + Uri.EscapeUriString(string.Join(",", metricNames));
            url = url + "&timeGrain=" + Uri.EscapeUriString(TypeConversion.To8601String(timeGrain));
            url = url + "&startTime=" + Uri.EscapeUriString(string.Format(CultureInfo.InvariantCulture, "{0:O}", startTime.ToUniversalTime()));
            url = url + "&endTime=" + Uri.EscapeUriString(string.Format(CultureInfo.InvariantCulture, "{0:O}", endTime.ToUniversalTime()));

            // 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", "2013-10-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), CloudExceptionType.Json);
                        if (shouldTrace)
                        {
                            Tracing.Error(invocationId, ex);
                        }
                        throw ex;
                    }

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

                    result = new MetricValueListResponse();
                    JToken responseDoc = JToken.Parse(responseContent);

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

                        JArray valueArray = (JArray)responseDoc["Value"];
                        if (valueArray != null && valueArray.Type != JTokenType.Null)
                        {
                            foreach (JToken valueValue in valueArray)
                            {
                                MetricValueSet metricValueSetInstance = new MetricValueSet();
                                metricValueSetCollectionInstance.Value.Add(metricValueSetInstance);

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

                                JToken namespaceValue = valueValue["Namespace"];
                                if (namespaceValue != null && namespaceValue.Type != JTokenType.Null)
                                {
                                    string namespaceInstance = (string)namespaceValue;
                                    metricValueSetInstance.Namespace = namespaceInstance;
                                }

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

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

                                JToken primaryAggregationValue = valueValue["PrimaryAggregation"];
                                if (primaryAggregationValue != null && primaryAggregationValue.Type != JTokenType.Null)
                                {
                                    string primaryAggregationInstance = (string)primaryAggregationValue;
                                    metricValueSetInstance.PrimaryAggregation = primaryAggregationInstance;
                                }

                                JToken timeGrainValue = valueValue["TimeGrain"];
                                if (timeGrainValue != null && timeGrainValue.Type != JTokenType.Null)
                                {
                                    TimeSpan timeGrainInstance = TypeConversion.From8601TimeSpan((string)timeGrainValue);
                                    metricValueSetInstance.TimeGrain = timeGrainInstance;
                                }

                                JToken startTimeValue = valueValue["StartTime"];
                                if (startTimeValue != null && startTimeValue.Type != JTokenType.Null)
                                {
                                    DateTime startTimeInstance = (DateTime)startTimeValue;
                                    metricValueSetInstance.StartTime = startTimeInstance;
                                }

                                JToken endTimeValue = valueValue["EndTime"];
                                if (endTimeValue != null && endTimeValue.Type != JTokenType.Null)
                                {
                                    DateTime endTimeInstance = (DateTime)endTimeValue;
                                    metricValueSetInstance.EndTime = endTimeInstance;
                                }

                                JArray metricValuesArray = (JArray)valueValue["MetricValues"];
                                if (metricValuesArray != null && metricValuesArray.Type != JTokenType.Null)
                                {
                                    foreach (JToken metricValuesValue in metricValuesArray)
                                    {
                                        MetricValue metricValueInstance = new MetricValue();
                                        metricValueSetInstance.MetricValues.Add(metricValueInstance);

                                        JToken timestampValue = metricValuesValue["Timestamp"];
                                        if (timestampValue != null && timestampValue.Type != JTokenType.Null)
                                        {
                                            DateTime timestampInstance = (DateTime)timestampValue;
                                            metricValueInstance.Timestamp = timestampInstance;
                                        }

                                        JToken averageValue = metricValuesValue["Average"];
                                        if (averageValue != null && averageValue.Type != JTokenType.Null)
                                        {
                                            double averageInstance = (double)averageValue;
                                            metricValueInstance.Average = averageInstance;
                                        }

                                        JToken minimumValue = metricValuesValue["Minimum"];
                                        if (minimumValue != null && minimumValue.Type != JTokenType.Null)
                                        {
                                            double minimumInstance = (double)minimumValue;
                                            metricValueInstance.Minimum = minimumInstance;
                                        }

                                        JToken maximumValue = metricValuesValue["Maximum"];
                                        if (maximumValue != null && maximumValue.Type != JTokenType.Null)
                                        {
                                            double maximumInstance = (double)maximumValue;
                                            metricValueInstance.Maximum = maximumInstance;
                                        }

                                        JToken totalValue = metricValuesValue["Total"];
                                        if (totalValue != null && totalValue.Type != JTokenType.Null)
                                        {
                                            double totalInstance = (double)totalValue;
                                            metricValueInstance.Total = totalInstance;
                                        }

                                        JToken annotationValue = metricValuesValue["Annotation"];
                                        if (annotationValue != null && annotationValue.Type != JTokenType.Null)
                                        {
                                            string annotationInstance = (string)annotationValue;
                                            metricValueInstance.Annotation = annotationInstance;
                                        }

                                        JToken countValue = metricValuesValue["Count"];
                                        if (countValue != null && countValue.Type != JTokenType.Null)
                                        {
                                            int countInstance = (int)countValue;
                                            metricValueInstance.Count = countInstance;
                                        }
                                    }
                                }
                            }
                        }
                    }

                    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();
                }
            }
        }
コード例 #2
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();
                }
            }
        }
コード例 #3
0
        /// <summary>
        /// The List Metric Definitions operation lists the metric definitions
        /// for the resource.
        /// </summary>
        /// <param name='resourceId'>
        /// Required. The id of the resource.The resource id can be built using
        /// the resource id builder class under utilities
        /// </param>
        /// <param name='metricNames'>
        /// Optional. The names of the metrics.
        /// </param>
        /// <param name='metricNamespace'>
        /// Required. The namespace of the metrics.The value is either null or
        /// WindowsAzure.Availability.WindowsAzure.Availability returns the
        /// metric definitions for endpoint monitoring metrics
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// The List Metric Definitions operation response.
        /// </returns>
        public async System.Threading.Tasks.Task <Microsoft.WindowsAzure.Management.Monitoring.Metrics.Models.MetricDefinitionListResponse> ListAsync(string resourceId, IList <string> metricNames, string metricNamespace, CancellationToken cancellationToken)
        {
            // Validate
            if (resourceId == null)
            {
                throw new ArgumentNullException("resourceId");
            }

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

            // Construct URL
            string baseUrl = this.Client.BaseUri.AbsoluteUri;
            string url     = "/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/services/monitoring/metricdefinitions/query?";

            url = url + "&resourceId=" + Uri.EscapeUriString(resourceId.Trim());
            if (metricNamespace != null)
            {
                url = url + "&namespace=" + Uri.EscapeUriString(metricNamespace != null ? metricNamespace.Trim() : "");
            }
            if (metricNames != null && metricNames.Count > 0)
            {
                url = url + "&names=" + Uri.EscapeUriString(string.Join(",", metricNames));
            }
            // 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;

            // 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", "2013-10-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), CloudExceptionType.Json);
                        if (shouldTrace)
                        {
                            Tracing.Error(invocationId, ex);
                        }
                        throw ex;
                    }

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

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

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

                        JToken valueArray = responseDoc["Value"];
                        if (valueArray != null && valueArray.Type != JTokenType.Null)
                        {
                            foreach (JToken valueValue in ((JArray)valueArray))
                            {
                                MetricDefinition metricDefinitionInstance = new MetricDefinition();
                                metricDefinitionCollectionInstance.Value.Add(metricDefinitionInstance);

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

                                JToken namespaceValue = valueValue["Namespace"];
                                if (namespaceValue != null && namespaceValue.Type != JTokenType.Null)
                                {
                                    string namespaceInstance = ((string)namespaceValue);
                                    metricDefinitionInstance.Namespace = namespaceInstance;
                                }

                                JToken resourceIdSuffixValue = valueValue["ResourceIdSuffix"];
                                if (resourceIdSuffixValue != null && resourceIdSuffixValue.Type != JTokenType.Null)
                                {
                                    string resourceIdSuffixInstance = ((string)resourceIdSuffixValue);
                                    metricDefinitionInstance.ResourceIdSuffix = resourceIdSuffixInstance;
                                }

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

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

                                JToken primaryAggregationValue = valueValue["PrimaryAggregation"];
                                if (primaryAggregationValue != null && primaryAggregationValue.Type != JTokenType.Null)
                                {
                                    string primaryAggregationInstance = ((string)primaryAggregationValue);
                                    metricDefinitionInstance.PrimaryAggregation = primaryAggregationInstance;
                                }

                                JToken metricAvailabilitiesArray = valueValue["MetricAvailabilities"];
                                if (metricAvailabilitiesArray != null && metricAvailabilitiesArray.Type != JTokenType.Null)
                                {
                                    foreach (JToken metricAvailabilitiesValue in ((JArray)metricAvailabilitiesArray))
                                    {
                                        MetricAvailability metricAvailabilityInstance = new MetricAvailability();
                                        metricDefinitionInstance.MetricAvailabilities.Add(metricAvailabilityInstance);

                                        JToken timeGrainValue = metricAvailabilitiesValue["TimeGrain"];
                                        if (timeGrainValue != null && timeGrainValue.Type != JTokenType.Null)
                                        {
                                            TimeSpan timeGrainInstance = TypeConversion.From8601TimeSpan(((string)timeGrainValue));
                                            metricAvailabilityInstance.TimeGrain = timeGrainInstance;
                                        }

                                        JToken retentionValue = metricAvailabilitiesValue["Retention"];
                                        if (retentionValue != null && retentionValue.Type != JTokenType.Null)
                                        {
                                            TimeSpan retentionInstance = TypeConversion.From8601TimeSpan(((string)retentionValue));
                                            metricAvailabilityInstance.Retention = retentionInstance;
                                        }
                                    }
                                }

                                JToken minimumAlertableTimeWindowValue = valueValue["MinimumAlertableTimeWindow"];
                                if (minimumAlertableTimeWindowValue != null && minimumAlertableTimeWindowValue.Type != JTokenType.Null)
                                {
                                    TimeSpan minimumAlertableTimeWindowInstance = TypeConversion.From8601TimeSpan(((string)minimumAlertableTimeWindowValue));
                                    metricDefinitionInstance.MinimumAlertableTimeWindow = minimumAlertableTimeWindowInstance;
                                }

                                JToken isAlertableValue = valueValue["IsAlertable"];
                                if (isAlertableValue != null && isAlertableValue.Type != JTokenType.Null)
                                {
                                    bool isAlertableInstance = ((bool)isAlertableValue);
                                    metricDefinitionInstance.IsAlertable = isAlertableInstance;
                                }
                            }
                        }
                    }

                    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();
                }
            }
        }
コード例 #4
0
        /// <param name='resourceId'>
        /// Required. The resource ID.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// A standard service response including an HTTP status code and
        /// request ID.
        /// </returns>
        public async System.Threading.Tasks.Task <Microsoft.WindowsAzure.Management.Monitoring.Autoscale.Models.AutoscaleSettingGetResponse> GetAsync(string resourceId, CancellationToken cancellationToken)
        {
            // Validate
            if (resourceId == null)
            {
                throw new ArgumentNullException("resourceId");
            }

            // 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("resourceId", resourceId);
                Tracing.Enter(invocationId, this, "GetAsync", tracingParameters);
            }

            // Construct URL
            string url = "/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/services/monitoring/autoscalesettings?";

            url = url + "resourceId=" + Uri.EscapeDataString(resourceId.Trim());
            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", "2013-10-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
                    AutoscaleSettingGetResponse result = null;
                    // Deserialize Response
                    cancellationToken.ThrowIfCancellationRequested();
                    string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

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

                    if (responseDoc != null && responseDoc.Type != JTokenType.Null)
                    {
                        AutoscaleSetting settingInstance = new AutoscaleSetting();
                        result.Setting = settingInstance;

                        JToken profilesArray = responseDoc["Profiles"];
                        if (profilesArray != null && profilesArray.Type != JTokenType.Null)
                        {
                            foreach (JToken profilesValue in ((JArray)profilesArray))
                            {
                                AutoscaleProfile autoscaleProfileInstance = new AutoscaleProfile();
                                settingInstance.Profiles.Add(autoscaleProfileInstance);

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

                                JToken capacityValue = profilesValue["Capacity"];
                                if (capacityValue != null && capacityValue.Type != JTokenType.Null)
                                {
                                    ScaleCapacity capacityInstance = new ScaleCapacity();
                                    autoscaleProfileInstance.Capacity = capacityInstance;

                                    JToken minimumValue = capacityValue["Minimum"];
                                    if (minimumValue != null && minimumValue.Type != JTokenType.Null)
                                    {
                                        string minimumInstance = ((string)minimumValue);
                                        capacityInstance.Minimum = minimumInstance;
                                    }

                                    JToken maximumValue = capacityValue["Maximum"];
                                    if (maximumValue != null && maximumValue.Type != JTokenType.Null)
                                    {
                                        string maximumInstance = ((string)maximumValue);
                                        capacityInstance.Maximum = maximumInstance;
                                    }

                                    JToken defaultValue = capacityValue["Default"];
                                    if (defaultValue != null && defaultValue.Type != JTokenType.Null)
                                    {
                                        string defaultInstance = ((string)defaultValue);
                                        capacityInstance.Default = defaultInstance;
                                    }
                                }

                                JToken rulesArray = profilesValue["Rules"];
                                if (rulesArray != null && rulesArray.Type != JTokenType.Null)
                                {
                                    foreach (JToken rulesValue in ((JArray)rulesArray))
                                    {
                                        ScaleRule scaleRuleInstance = new ScaleRule();
                                        autoscaleProfileInstance.Rules.Add(scaleRuleInstance);

                                        JToken metricTriggerValue = rulesValue["MetricTrigger"];
                                        if (metricTriggerValue != null && metricTriggerValue.Type != JTokenType.Null)
                                        {
                                            MetricTrigger metricTriggerInstance = new MetricTrigger();
                                            scaleRuleInstance.MetricTrigger = metricTriggerInstance;

                                            JToken metricNameValue = metricTriggerValue["MetricName"];
                                            if (metricNameValue != null && metricNameValue.Type != JTokenType.Null)
                                            {
                                                string metricNameInstance = ((string)metricNameValue);
                                                metricTriggerInstance.MetricName = metricNameInstance;
                                            }

                                            JToken metricNamespaceValue = metricTriggerValue["MetricNamespace"];
                                            if (metricNamespaceValue != null && metricNamespaceValue.Type != JTokenType.Null)
                                            {
                                                string metricNamespaceInstance = ((string)metricNamespaceValue);
                                                metricTriggerInstance.MetricNamespace = metricNamespaceInstance;
                                            }

                                            JToken metricSourceValue = metricTriggerValue["MetricSource"];
                                            if (metricSourceValue != null && metricSourceValue.Type != JTokenType.Null)
                                            {
                                                string metricSourceInstance = ((string)metricSourceValue);
                                                metricTriggerInstance.MetricSource = metricSourceInstance;
                                            }

                                            JToken timeGrainValue = metricTriggerValue["TimeGrain"];
                                            if (timeGrainValue != null && timeGrainValue.Type != JTokenType.Null)
                                            {
                                                TimeSpan timeGrainInstance = TypeConversion.From8601TimeSpan(((string)timeGrainValue));
                                                metricTriggerInstance.TimeGrain = timeGrainInstance;
                                            }

                                            JToken statisticValue = metricTriggerValue["Statistic"];
                                            if (statisticValue != null && statisticValue.Type != JTokenType.Null)
                                            {
                                                MetricStatisticType statisticInstance = ((MetricStatisticType)Enum.Parse(typeof(MetricStatisticType), ((string)statisticValue), true));
                                                metricTriggerInstance.Statistic = statisticInstance;
                                            }

                                            JToken timeWindowValue = metricTriggerValue["TimeWindow"];
                                            if (timeWindowValue != null && timeWindowValue.Type != JTokenType.Null)
                                            {
                                                TimeSpan timeWindowInstance = TypeConversion.From8601TimeSpan(((string)timeWindowValue));
                                                metricTriggerInstance.TimeWindow = timeWindowInstance;
                                            }

                                            JToken timeAggregationValue = metricTriggerValue["TimeAggregation"];
                                            if (timeAggregationValue != null && timeAggregationValue.Type != JTokenType.Null)
                                            {
                                                TimeAggregationType timeAggregationInstance = ((TimeAggregationType)Enum.Parse(typeof(TimeAggregationType), ((string)timeAggregationValue), true));
                                                metricTriggerInstance.TimeAggregation = timeAggregationInstance;
                                            }

                                            JToken operatorValue = metricTriggerValue["Operator"];
                                            if (operatorValue != null && operatorValue.Type != JTokenType.Null)
                                            {
                                                ComparisonOperationType operatorInstance = ((ComparisonOperationType)Enum.Parse(typeof(ComparisonOperationType), ((string)operatorValue), true));
                                                metricTriggerInstance.Operator = operatorInstance;
                                            }

                                            JToken thresholdValue = metricTriggerValue["Threshold"];
                                            if (thresholdValue != null && thresholdValue.Type != JTokenType.Null)
                                            {
                                                double thresholdInstance = ((double)thresholdValue);
                                                metricTriggerInstance.Threshold = thresholdInstance;
                                            }
                                        }

                                        JToken scaleActionValue = rulesValue["ScaleAction"];
                                        if (scaleActionValue != null && scaleActionValue.Type != JTokenType.Null)
                                        {
                                            ScaleAction scaleActionInstance = new ScaleAction();
                                            scaleRuleInstance.ScaleAction = scaleActionInstance;

                                            JToken directionValue = scaleActionValue["Direction"];
                                            if (directionValue != null && directionValue.Type != JTokenType.Null)
                                            {
                                                ScaleDirection directionInstance = ((ScaleDirection)Enum.Parse(typeof(ScaleDirection), ((string)directionValue), true));
                                                scaleActionInstance.Direction = directionInstance;
                                            }

                                            JToken typeValue = scaleActionValue["Type"];
                                            if (typeValue != null && typeValue.Type != JTokenType.Null)
                                            {
                                                ScaleType typeInstance = ((ScaleType)Enum.Parse(typeof(ScaleType), ((string)typeValue), true));
                                                scaleActionInstance.Type = typeInstance;
                                            }

                                            JToken valueValue = scaleActionValue["Value"];
                                            if (valueValue != null && valueValue.Type != JTokenType.Null)
                                            {
                                                string valueInstance = ((string)valueValue);
                                                scaleActionInstance.Value = valueInstance;
                                            }

                                            JToken cooldownValue = scaleActionValue["Cooldown"];
                                            if (cooldownValue != null && cooldownValue.Type != JTokenType.Null)
                                            {
                                                TimeSpan cooldownInstance = TypeConversion.From8601TimeSpan(((string)cooldownValue));
                                                scaleActionInstance.Cooldown = cooldownInstance;
                                            }
                                        }
                                    }
                                }

                                JToken fixedDateValue = profilesValue["FixedDate"];
                                if (fixedDateValue != null && fixedDateValue.Type != JTokenType.Null)
                                {
                                    TimeWindow fixedDateInstance = new TimeWindow();
                                    autoscaleProfileInstance.FixedDate = fixedDateInstance;

                                    JToken timeZoneValue = fixedDateValue["TimeZone"];
                                    if (timeZoneValue != null && timeZoneValue.Type != JTokenType.Null)
                                    {
                                        string timeZoneInstance = ((string)timeZoneValue);
                                        fixedDateInstance.TimeZone = timeZoneInstance;
                                    }

                                    JToken startValue = fixedDateValue["Start"];
                                    if (startValue != null && startValue.Type != JTokenType.Null)
                                    {
                                        DateTime startInstance = ((DateTime)startValue);
                                        fixedDateInstance.Start = startInstance;
                                    }

                                    JToken endValue = fixedDateValue["End"];
                                    if (endValue != null && endValue.Type != JTokenType.Null)
                                    {
                                        DateTime endInstance = ((DateTime)endValue);
                                        fixedDateInstance.End = endInstance;
                                    }
                                }

                                JToken recurrenceValue = profilesValue["Recurrence"];
                                if (recurrenceValue != null && recurrenceValue.Type != JTokenType.Null)
                                {
                                    Recurrence recurrenceInstance = new Recurrence();
                                    autoscaleProfileInstance.Recurrence = recurrenceInstance;

                                    JToken frequencyValue = recurrenceValue["Frequency"];
                                    if (frequencyValue != null && frequencyValue.Type != JTokenType.Null)
                                    {
                                        RecurrenceFrequency frequencyInstance = ((RecurrenceFrequency)Enum.Parse(typeof(RecurrenceFrequency), ((string)frequencyValue), true));
                                        recurrenceInstance.Frequency = frequencyInstance;
                                    }

                                    JToken scheduleValue = recurrenceValue["Schedule"];
                                    if (scheduleValue != null && scheduleValue.Type != JTokenType.Null)
                                    {
                                        RecurrentSchedule scheduleInstance = new RecurrentSchedule();
                                        recurrenceInstance.Schedule = scheduleInstance;

                                        JToken timeZoneValue2 = scheduleValue["TimeZone"];
                                        if (timeZoneValue2 != null && timeZoneValue2.Type != JTokenType.Null)
                                        {
                                            string timeZoneInstance2 = ((string)timeZoneValue2);
                                            scheduleInstance.TimeZone = timeZoneInstance2;
                                        }

                                        JToken daysArray = scheduleValue["Days"];
                                        if (daysArray != null && daysArray.Type != JTokenType.Null)
                                        {
                                            foreach (JToken daysValue in ((JArray)daysArray))
                                            {
                                                scheduleInstance.Days.Add(((string)daysValue));
                                            }
                                        }

                                        JToken hoursArray = scheduleValue["Hours"];
                                        if (hoursArray != null && hoursArray.Type != JTokenType.Null)
                                        {
                                            foreach (JToken hoursValue in ((JArray)hoursArray))
                                            {
                                                scheduleInstance.Hours.Add(((int)hoursValue));
                                            }
                                        }

                                        JToken minutesArray = scheduleValue["Minutes"];
                                        if (minutesArray != null && minutesArray.Type != JTokenType.Null)
                                        {
                                            foreach (JToken minutesValue in ((JArray)minutesArray))
                                            {
                                                scheduleInstance.Minutes.Add(((int)minutesValue));
                                            }
                                        }
                                    }
                                }
                            }
                        }

                        JToken enabledValue = responseDoc["Enabled"];
                        if (enabledValue != null && enabledValue.Type != JTokenType.Null)
                        {
                            bool enabledInstance = ((bool)enabledValue);
                            settingInstance.Enabled = enabledInstance;
                        }
                    }

                    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();
                }
            }
        }
コード例 #5
0
        /// <summary>
        /// List the alert rules within a subscription.
        /// </summary>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// The List Rules operation response.
        /// </returns>
        public async System.Threading.Tasks.Task <Microsoft.WindowsAzure.Management.Monitoring.Alerts.Models.RuleListResponse> ListAsync(CancellationToken cancellationToken)
        {
            // Validate

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

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

            // Construct URL
            string url = new Uri(this.Client.BaseUri, "/").AbsoluteUri + this.Client.Credentials.SubscriptionId + "/services/monitoring/alertrules";

            // 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", "2013-10-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), CloudExceptionType.Json);
                        if (shouldTrace)
                        {
                            Tracing.Error(invocationId, ex);
                        }
                        throw ex;
                    }

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

                    result = new RuleListResponse();
                    JToken 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)
                            {
                                Rule ruleInstance = new Rule();
                                result.Value.Add(ruleInstance);

                                JToken idValue = valueValue["Id"];
                                if (idValue != null && idValue.Type != JTokenType.Null)
                                {
                                    string idInstance = (string)idValue;
                                    ruleInstance.Id = idInstance;
                                }

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

                                JToken descriptionValue = valueValue["Description"];
                                if (descriptionValue != null && descriptionValue.Type != JTokenType.Null)
                                {
                                    string descriptionInstance = (string)descriptionValue;
                                    ruleInstance.Description = descriptionInstance;
                                }

                                JToken isEnabledValue = valueValue["IsEnabled"];
                                if (isEnabledValue != null && isEnabledValue.Type != JTokenType.Null)
                                {
                                    bool isEnabledInstance = (bool)isEnabledValue;
                                    ruleInstance.IsEnabled = isEnabledInstance;
                                }

                                JToken conditionValue = valueValue["Condition"];
                                if (conditionValue != null && conditionValue.Type != JTokenType.Null)
                                {
                                    string typeName = (string)conditionValue["odata.type"];
                                    if (typeName == "Microsoft.WindowsAzure.Management.Monitoring.Alerts.Models.ThresholdRuleCondition")
                                    {
                                        ThresholdRuleCondition thresholdRuleConditionInstance = new ThresholdRuleCondition();

                                        JToken dataSourceValue = conditionValue["DataSource"];
                                        if (dataSourceValue != null && dataSourceValue.Type != JTokenType.Null)
                                        {
                                            string typeName2 = (string)dataSourceValue["odata.type"];
                                            if (typeName2 == "Microsoft.WindowsAzure.Management.Monitoring.Alerts.Models.RuleMetricDataSource")
                                            {
                                                RuleMetricDataSource ruleMetricDataSourceInstance = new RuleMetricDataSource();

                                                JToken resourceIdValue = dataSourceValue["ResourceId"];
                                                if (resourceIdValue != null && resourceIdValue.Type != JTokenType.Null)
                                                {
                                                    string resourceIdInstance = (string)resourceIdValue;
                                                    ruleMetricDataSourceInstance.ResourceId = resourceIdInstance;
                                                }

                                                JToken metricNamespaceValue = dataSourceValue["MetricNamespace"];
                                                if (metricNamespaceValue != null && metricNamespaceValue.Type != JTokenType.Null)
                                                {
                                                    string metricNamespaceInstance = (string)metricNamespaceValue;
                                                    ruleMetricDataSourceInstance.MetricNamespace = metricNamespaceInstance;
                                                }

                                                JToken metricNameValue = dataSourceValue["MetricName"];
                                                if (metricNameValue != null && metricNameValue.Type != JTokenType.Null)
                                                {
                                                    string metricNameInstance = (string)metricNameValue;
                                                    ruleMetricDataSourceInstance.MetricName = metricNameInstance;
                                                }
                                                thresholdRuleConditionInstance.DataSource = ruleMetricDataSourceInstance;
                                            }
                                        }

                                        JToken operatorValue = conditionValue["Operator"];
                                        if (operatorValue != null && operatorValue.Type != JTokenType.Null)
                                        {
                                            ConditionOperator operatorInstance = (ConditionOperator)Enum.Parse(typeof(ConditionOperator), (string)operatorValue, false);
                                            thresholdRuleConditionInstance.Operator = operatorInstance;
                                        }

                                        JToken thresholdValue = conditionValue["Threshold"];
                                        if (thresholdValue != null && thresholdValue.Type != JTokenType.Null)
                                        {
                                            double thresholdInstance = (double)thresholdValue;
                                            thresholdRuleConditionInstance.Threshold = thresholdInstance;
                                        }

                                        JToken windowSizeValue = conditionValue["WindowSize"];
                                        if (windowSizeValue != null && windowSizeValue.Type != JTokenType.Null)
                                        {
                                            TimeSpan windowSizeInstance = TypeConversion.From8601TimeSpan((string)windowSizeValue);
                                            thresholdRuleConditionInstance.WindowSize = windowSizeInstance;
                                        }
                                        ruleInstance.Condition = thresholdRuleConditionInstance;
                                    }
                                }

                                JToken actionsArray = valueValue["Actions"];
                                if (actionsArray != null && actionsArray.Type != JTokenType.Null)
                                {
                                    foreach (JToken actionsValue in (JArray)actionsArray)
                                    {
                                        string typeName3 = (string)actionsValue["odata.type"];
                                        if (typeName3 == "Microsoft.WindowsAzure.Management.Monitoring.Alerts.Models.RuleEmailAction")
                                        {
                                            RuleEmailAction ruleEmailActionInstance = new RuleEmailAction();

                                            JToken sendToServiceOwnersValue = actionsValue["SendToServiceOwners"];
                                            if (sendToServiceOwnersValue != null && sendToServiceOwnersValue.Type != JTokenType.Null)
                                            {
                                                bool sendToServiceOwnersInstance = (bool)sendToServiceOwnersValue;
                                                ruleEmailActionInstance.SendToServiceOwners = sendToServiceOwnersInstance;
                                            }

                                            JToken customEmailsArray = actionsValue["CustomEmails"];
                                            if (customEmailsArray != null && customEmailsArray.Type != JTokenType.Null)
                                            {
                                                foreach (JToken customEmailsValue in (JArray)customEmailsArray)
                                                {
                                                    ruleEmailActionInstance.CustomEmails.Add((string)customEmailsValue);
                                                }
                                            }
                                            ruleInstance.Actions.Add(ruleEmailActionInstance);
                                        }
                                    }
                                }

                                JToken lastUpdatedTimeValue = valueValue["LastUpdatedTime"];
                                if (lastUpdatedTimeValue != null && lastUpdatedTimeValue.Type != JTokenType.Null)
                                {
                                    DateTime lastUpdatedTimeInstance = (DateTime)lastUpdatedTimeValue;
                                    ruleInstance.LastUpdatedTime = lastUpdatedTimeInstance;
                                }
                            }
                        }
                    }

                    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();
                }
            }
        }
コード例 #6
0
        /// <summary>
        /// The List Metric operation lists the metric value sets for the
        /// resource metrics.
        /// </summary>
        /// <param name='resourceUri'>
        /// Required. The uri of the target resource to get metrics for.
        /// </param>
        /// <param name='filterString'>
        /// Required. An OData $filter expression that supports querying by the
        /// name of the metric definition.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// The List Metric values operation response.
        /// </returns>
        public async Task <MetricListResponse> GetMetricsInternalAsync(string resourceUri, string filterString, CancellationToken cancellationToken)
        {
            // Validate
            if (resourceUri == null)
            {
                throw new ArgumentNullException("resourceUri");
            }

            // 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("filterString", filterString);
                Tracing.Enter(invocationId, this, "GetMetricsAsync", tracingParameters);
            }

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

            url = url + "api-version=2014-04-01";
            if (filterString != null)
            {
                url = url + "&$filter=" + Uri.EscapeDataString(filterString != null ? filterString.Trim() : "");
            }
            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-04-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
                    MetricListResponse result = null;
                    // Deserialize Response
                    cancellationToken.ThrowIfCancellationRequested();
                    string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

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

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

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

                                JToken nameValue = valueValue["name"];
                                if (nameValue != null && nameValue.Type != JTokenType.Null)
                                {
                                    LocalizableString nameInstance = new LocalizableString();
                                    metricInstance.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 unitValue = valueValue["unit"];
                                if (unitValue != null && unitValue.Type != JTokenType.Null)
                                {
                                    Unit unitInstance = ((Unit)Enum.Parse(typeof(Unit), ((string)unitValue), true));
                                    metricInstance.Unit = unitInstance;
                                }

                                JToken timeGrainValue = valueValue["timeGrain"];
                                if (timeGrainValue != null && timeGrainValue.Type != JTokenType.Null)
                                {
                                    TimeSpan timeGrainInstance = TypeConversion.From8601TimeSpan(((string)timeGrainValue));
                                    metricInstance.TimeGrain = timeGrainInstance;
                                }

                                JToken startTimeValue = valueValue["startTime"];
                                if (startTimeValue != null && startTimeValue.Type != JTokenType.Null)
                                {
                                    DateTime startTimeInstance = ((DateTime)startTimeValue);
                                    metricInstance.StartTime = startTimeInstance;
                                }

                                JToken endTimeValue = valueValue["endTime"];
                                if (endTimeValue != null && endTimeValue.Type != JTokenType.Null)
                                {
                                    DateTime endTimeInstance = ((DateTime)endTimeValue);
                                    metricInstance.EndTime = endTimeInstance;
                                }

                                JToken metricValuesArray = valueValue["metricValues"];
                                if (metricValuesArray != null && metricValuesArray.Type != JTokenType.Null)
                                {
                                    foreach (JToken metricValuesValue in ((JArray)metricValuesArray))
                                    {
                                        MetricValue metricValueInstance = new MetricValue();
                                        metricInstance.MetricValues.Add(metricValueInstance);

                                        JToken timestampValue = metricValuesValue["timestamp"];
                                        if (timestampValue != null && timestampValue.Type != JTokenType.Null)
                                        {
                                            DateTime timestampInstance = ((DateTime)timestampValue);
                                            metricValueInstance.Timestamp = timestampInstance;
                                        }

                                        JToken averageValue = metricValuesValue["average"];
                                        if (averageValue != null && averageValue.Type != JTokenType.Null)
                                        {
                                            double averageInstance = ((double)averageValue);
                                            metricValueInstance.Average = averageInstance;
                                        }

                                        JToken minimumValue = metricValuesValue["minimum"];
                                        if (minimumValue != null && minimumValue.Type != JTokenType.Null)
                                        {
                                            double minimumInstance = ((double)minimumValue);
                                            metricValueInstance.Minimum = minimumInstance;
                                        }

                                        JToken maximumValue = metricValuesValue["maximum"];
                                        if (maximumValue != null && maximumValue.Type != JTokenType.Null)
                                        {
                                            double maximumInstance = ((double)maximumValue);
                                            metricValueInstance.Maximum = maximumInstance;
                                        }

                                        JToken totalValue = metricValuesValue["total"];
                                        if (totalValue != null && totalValue.Type != JTokenType.Null)
                                        {
                                            double totalInstance = ((double)totalValue);
                                            metricValueInstance.Total = totalInstance;
                                        }

                                        JToken countValue = metricValuesValue["count"];
                                        if (countValue != null && countValue.Type != JTokenType.Null)
                                        {
                                            long countInstance = ((long)countValue);
                                            metricValueInstance.Count = countInstance;
                                        }

                                        JToken lastValue = metricValuesValue["last"];
                                        if (lastValue != null && lastValue.Type != JTokenType.Null)
                                        {
                                            double lastInstance = ((double)lastValue);
                                            metricValueInstance.Last = lastInstance;
                                        }

                                        JToken propertiesSequenceElement = ((JToken)metricValuesValue["properties"]);
                                        if (propertiesSequenceElement != null && propertiesSequenceElement.Type != JTokenType.Null)
                                        {
                                            foreach (JProperty property in propertiesSequenceElement)
                                            {
                                                string propertiesKey   = ((string)property.Name);
                                                string propertiesValue = ((string)property.Value);
                                                metricValueInstance.Properties.Add(propertiesKey, propertiesValue);
                                            }
                                        }
                                    }
                                }

                                JToken resourceIdValue = valueValue["resourceId"];
                                if (resourceIdValue != null && resourceIdValue.Type != JTokenType.Null)
                                {
                                    string resourceIdInstance = ((string)resourceIdValue);
                                    metricInstance.ResourceId = resourceIdInstance;
                                }

                                JToken propertiesSequenceElement2 = ((JToken)valueValue["properties"]);
                                if (propertiesSequenceElement2 != null && propertiesSequenceElement2.Type != JTokenType.Null)
                                {
                                    foreach (JProperty property2 in propertiesSequenceElement2)
                                    {
                                        string propertiesKey2   = ((string)property2.Name);
                                        string propertiesValue2 = ((string)property2.Value);
                                        metricInstance.Properties.Add(propertiesKey2, propertiesValue2);
                                    }
                                }
                            }
                        }
                    }

                    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();
                }
            }
        }