public GetAzureRmMetricTests(Xunit.Abstractions.ITestOutputHelper output)
        {
            ServiceManagemenet.Common.Models.XunitTracingInterceptor.AddToContext(new ServiceManagemenet.Common.Models.XunitTracingInterceptor(output));
            insightsMetricOperationsMock = new Mock <IMetricsOperations>();
            MonitorClientMock            = new Mock <MonitorClient>();
            commandRuntimeMock           = new Mock <ICommandRuntime>();
            cmdlet = new GetAzureRmMetricCommand()
            {
                CommandRuntime = commandRuntimeMock.Object,
                MonitorClient  = MonitorClientMock.Object
            };

            response = new Microsoft.Rest.Azure.AzureOperationResponse <IEnumerable <Metric> >()
            {
                Body = new List <Metric>()
            };

            insightsMetricOperationsMock.Setup(f => f.ListWithHttpMessagesAsync(It.IsAny <string>(), It.IsAny <ODataQuery <Metric> >(), It.IsAny <Dictionary <string, List <string> > >(), It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult <Microsoft.Rest.Azure.AzureOperationResponse <IEnumerable <Metric> > >(response))
            .Callback((string r, ODataQuery <Metric> s, Dictionary <string, List <string> > headers, CancellationToken t) =>
            {
                resourceId = r;
                filter     = s;
            });

            MonitorClientMock.SetupGet(f => f.Metrics).Returns(this.insightsMetricOperationsMock.Object);
        }
        /// <inheritdoc/>
        public async Task ChangeQuantityAsync(WebhookPayload payload)
        {
            if (payload == null)
            {
                throw new ArgumentNullException(nameof(payload));
            }

            if (payload.Status == OperationStatusEnum.Succeeded)
            {
                Microsoft.Rest.Azure.AzureOperationResponse response = await this.marketplaceClient.SubscriptionOperations.UpdateOperationStatusWithHttpMessagesAsync(
                    payload.SubscriptionId,
                    payload.OperationId,
                    null,
                    null,
                    null,
                    payload.Quantity,
                    UpdateOperationStatusEnum.Success).ConfigureAwait(false);

                // Change request is complete
                if (response.Response.IsSuccessStatusCode)
                {
                    await this.notificationHelper.NotifyChangeQuantityAsync(payload).ConfigureAwait(false);
                }
            }
            else if (payload.Status == OperationStatusEnum.Conflict || payload.Status == OperationStatusEnum.Failed)
            {
                await this.notificationHelper.ProcessOperationFailOrConflictAsync(payload).ConfigureAwait(false);
            }
        }
        public GetAzureRmMetricTests(Xunit.Abstractions.ITestOutputHelper output)
        {
            ServiceManagement.Common.Models.XunitTracingInterceptor.AddToContext(new ServiceManagement.Common.Models.XunitTracingInterceptor(output));
            insightsMetricOperationsMock = new Mock <IMetricsOperations>();
            MonitorClientMock            = new Mock <MonitorManagementClient>()
            {
                CallBase = true
            };
            commandRuntimeMock = new Mock <ICommandRuntime>();
            cmdlet             = new GetAzureRmMetricCommand()
            {
                CommandRuntime          = commandRuntimeMock.Object,
                MonitorManagementClient = MonitorClientMock.Object
            };

            response = new Microsoft.Rest.Azure.AzureOperationResponse <Response>();

            insightsMetricOperationsMock.Setup(f => f.ListWithHttpMessagesAsync(It.IsAny <string>(), It.IsAny <ODataQuery <MetadataValue> >(), It.IsAny <string>(), It.IsAny <TimeSpan?>(), It.IsAny <string>(), It.IsAny <string>(), It.IsAny <int?>(), It.IsAny <string>(), It.IsAny <ResultType?>(), It.IsAny <string>(), It.IsAny <Dictionary <string, List <string> > >(), It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult <Microsoft.Rest.Azure.AzureOperationResponse <Response> >(response))
            .Callback((string resourceUri, ODataQuery <MetadataValue> odataQuery, string timespan, TimeSpan? interval, string metricNames, string aggregation, int?top, string orderBy, ResultType? resultType, string metricNamespace, Dictionary <string, List <string> > headers, CancellationToken t) =>
            {
                resourceId          = resourceUri;
                filter              = odataQuery;
                timeSpan            = timespan;
                metricQueryInterval = interval;
                metricnames         = metricNames;
                aggregationType     = aggregation;
                topNumber           = top;
                orderby             = orderBy;
                resulttype          = resultType;
                metricnamespace     = metricNamespace;
            });

            MonitorClientMock.SetupGet(f => f.Metrics).Returns(this.insightsMetricOperationsMock.Object);
        }
        public GetAzureRmMetricDefinitionTests(Xunit.Abstractions.ITestOutputHelper output)
        {
            ServiceManagement.Common.Models.XunitTracingInterceptor.AddToContext(new ServiceManagement.Common.Models.XunitTracingInterceptor(output));
            insightsMetricDefinitionOperationsMock = new Mock <IMetricDefinitionsOperations>();
            MonitorClientMock = new Mock <MonitorManagementClient>()
            {
                CallBase = true
            };
            commandRuntimeMock = new Mock <ICommandRuntime>();
            cmdlet             = new GetAzureRmMetricDefinitionCommand()
            {
                CommandRuntime          = commandRuntimeMock.Object,
                MonitorManagementClient = MonitorClientMock.Object
            };

            response = new Microsoft.Rest.Azure.AzureOperationResponse <IEnumerable <MetricDefinition> >()
            {
                Body = Utilities.InitializeMetricDefinitionResponse()
            };

            insightsMetricDefinitionOperationsMock.Setup(f => f.ListWithHttpMessagesAsync(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <Dictionary <string, List <string> > >(), It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult <Microsoft.Rest.Azure.AzureOperationResponse <IEnumerable <MetricDefinition> > >(response))
            .Callback((string resource, string metricNamespace, Dictionary <string, List <string> > header, CancellationToken t) =>
            {
                resourceId      = resource;
                metricnamespace = metricNamespace;
            });

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

            response = new Microsoft.Rest.Azure.AzureOperationResponse<IEnumerable<UsageMetric>>()
            {
                Body = new List<UsageMetric>()
            };

            insightsUsageMetricOperationsMock
                .Setup(f => f.ListWithHttpMessagesAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<ODataQuery<UsageMetric>>(), It.IsAny<Dictionary<string, List<string>>>(), It.IsAny<CancellationToken>()))
                .Returns(Task.FromResult<Microsoft.Rest.Azure.AzureOperationResponse<IEnumerable<UsageMetric>>>(response))
                .Callback((string r, string api, ODataQuery<UsageMetric> q, Dictionary<string, List<string>> headers, CancellationToken t) =>
                {
                    resourceId = r;
                    filter = q;
                    apiVersion = api;
                });

            insightsClientMock
                .SetupGet(f => f.UsageMetrics)
                .Returns(this.insightsUsageMetricOperationsMock.Object);
        }
        public GetDiagnosticSettingCommandTests(Xunit.Abstractions.ITestOutputHelper output)
        {
            ServiceManagemenet.Common.Models.XunitTracingInterceptor.AddToContext(new ServiceManagemenet.Common.Models.XunitTracingInterceptor(output));
            insightsDiagnosticsOperationsMock = new Mock <IDiagnosticSettingsOperations>();
            insightsManagementClientMock      = new Mock <MonitorManagementClient>();
            commandRuntimeMock = new Mock <ICommandRuntime>();
            cmdlet             = new GetAzureRmDiagnosticSettingCommand()
            {
                CommandRuntime          = commandRuntimeMock.Object,
                MonitorManagementClient = insightsManagementClientMock.Object
            };

            response = new Microsoft.Rest.Azure.AzureOperationResponse <DiagnosticSettingsResource>()
            {
                Body = new DiagnosticSettingsResource
                {
                    EventHubName = "",
                    EventHubAuthorizationRuleId = "",
                    StorageAccountId            = "/subscriptions/123/resourcegroups/rg/providers/microsoft.storage/accounts/myaccount",
                    WorkspaceId = "",
                    Logs        = new List <LogSettings>
                    {
                        new LogSettings
                        {
                            RetentionPolicy = new RetentionPolicy()
                            {
                                Days    = 10,
                                Enabled = true
                            },
                            Category = "TestCategory1",
                            Enabled  = true
                        },
                        new LogSettings
                        {
                            RetentionPolicy = new RetentionPolicy()
                            {
                                Days    = 5,
                                Enabled = false
                            },
                            Category = "TestCategory2",
                            Enabled  = false
                        }
                    },
                    Metrics = new List <MetricSettings>
                    {
                        new MetricSettings
                        {
                            Category        = "MetricCat1",
                            RetentionPolicy = new RetentionPolicy()
                            {
                                Days    = 7,
                                Enabled = false
                            },
                            TimeGrain = TimeSpan.FromMinutes(1),
                            Enabled   = false
                        },
                        new MetricSettings
                        {
                            Category        = "MetricCat2",
                            RetentionPolicy = new RetentionPolicy()
                            {
                                Days    = 3,
                                Enabled = true
                            },
                            TimeGrain = TimeSpan.FromHours(1)
                        }
                    }
                }
            };

            insightsDiagnosticsOperationsMock.Setup(f => f.GetWithHttpMessagesAsync(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <Dictionary <string, List <string> > >(), It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult <Microsoft.Rest.Azure.AzureOperationResponse <DiagnosticSettingsResource> >(response))
            .Callback((string resourceId, string name, Dictionary <string, List <string> > headers, CancellationToken cancellationToken) =>
            {
                this.calledResourceId      = resourceId;
                this.diagnosticSettingName = name;
            });

            insightsManagementClientMock.SetupGet(f => f.DiagnosticSettings).Returns(this.insightsDiagnosticsOperationsMock.Object);
        }
        /// <summary>
        /// Get null duration value
        /// </summary>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="ErrorException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="Microsoft.Rest.SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public async System.Threading.Tasks.Task <Microsoft.Rest.Azure.AzureOperationResponse <System.TimeSpan?> > GetNullWithHttpMessagesAsync(System.Collections.Generic.Dictionary <string, System.Collections.Generic.List <string> > customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
        {
            // Tracing
            bool   _shouldTrace  = Microsoft.Rest.ServiceClientTracing.IsEnabled;
            string _invocationId = null;

            if (_shouldTrace)
            {
                _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
                System.Collections.Generic.Dictionary <string, object> tracingParameters = new System.Collections.Generic.Dictionary <string, object>();
                tracingParameters.Add("cancellationToken", cancellationToken);
                Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "GetNull", tracingParameters);
            }
            // Construct URL
            var _baseUrl = this.Client.BaseUri.AbsoluteUri;
            var _url     = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "duration/null").ToString();

            System.Collections.Generic.List <string> _queryParameters = new System.Collections.Generic.List <string>();
            if (_queryParameters.Count > 0)
            {
                _url += "?" + string.Join("&", _queryParameters);
            }
            // Create HTTP transport objects
            System.Net.Http.HttpRequestMessage  _httpRequest  = new System.Net.Http.HttpRequestMessage();
            System.Net.Http.HttpResponseMessage _httpResponse = null;
            _httpRequest.Method     = new System.Net.Http.HttpMethod("GET");
            _httpRequest.RequestUri = new System.Uri(_url);
            // Set Headers
            if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
            {
                _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
            }
            if (this.Client.AcceptLanguage != null)
            {
                if (_httpRequest.Headers.Contains("accept-language"))
                {
                    _httpRequest.Headers.Remove("accept-language");
                }
                _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
            }
            if (customHeaders != null)
            {
                foreach (var _header in customHeaders)
                {
                    if (_httpRequest.Headers.Contains(_header.Key))
                    {
                        _httpRequest.Headers.Remove(_header.Key);
                    }
                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
                }
            }

            // Serialize Request
            string _requestContent = null;

            // Set Credentials
            if (this.Client.Credentials != null)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            }
            // Send Request
            if (_shouldTrace)
            {
                Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);

            if (_shouldTrace)
            {
                Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
            }
            System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
            cancellationToken.ThrowIfCancellationRequested();
            string _responseContent = null;

            if ((int)_statusCode != 200)
            {
                var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                try
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                    Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <Error>(_responseContent, this.Client.DeserializationSettings);
                    if (_errorBody != null)
                    {
                        ex.Body = _errorBody;
                    }
                }
                catch (Newtonsoft.Json.JsonException)
                {
                    // Ignore the exception
                }
                ex.Request  = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
                ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
                if (_shouldTrace)
                {
                    Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
                }
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            // Create Result
            var _result = new Microsoft.Rest.Azure.AzureOperationResponse <System.TimeSpan?>();

            _result.Request  = _httpRequest;
            _result.Response = _httpResponse;
            if (_httpResponse.Headers.Contains("x-ms-request-id"))
            {
                _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
            }
            // Deserialize Response
            if ((int)_statusCode == 200)
            {
                _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                try
                {
                    _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <System.TimeSpan?>(_responseContent, this.Client.DeserializationSettings);
                }
                catch (Newtonsoft.Json.JsonException ex)
                {
                    _httpRequest.Dispose();
                    if (_httpResponse != null)
                    {
                        _httpResponse.Dispose();
                    }
                    throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex);
                }
            }
            if (_shouldTrace)
            {
                Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
            }
            return(_result);
        }
        public RemoveDiagnosticSettingCommandTests(Xunit.Abstractions.ITestOutputHelper output)
        {
            ServiceManagemenet.Common.Models.XunitTracingInterceptor.AddToContext(new ServiceManagemenet.Common.Models.XunitTracingInterceptor(output));
            this.insightsDiagnosticsOperationsMock = new Mock <IDiagnosticSettingsOperations>();
            this.insightsManagementClientMock      = new Mock <MonitorManagementClient>();
            this.commandRuntimeMock = new Mock <ICommandRuntime>();
            this.cmdlet             = new RemoveAzureRmDiagnosticSettingCommand()
            {
                CommandRuntime          = commandRuntimeMock.Object,
                MonitorManagementClient = insightsManagementClientMock.Object
            };

            var resource = new DiagnosticSettingsResource(name: "service")
            {
                EventHubName = "",
                EventHubAuthorizationRuleId = "",
                StorageAccountId            = "/subscriptions/123/resourcegroups/rg/providers/microsoft.storage/accounts/myaccount",
                WorkspaceId = "",
                Logs        = new List <LogSettings>
                {
                    new LogSettings
                    {
                        RetentionPolicy = new RetentionPolicy()
                        {
                            Days    = 10,
                            Enabled = true
                        },
                        Category = "TestCategory1",
                        Enabled  = true
                    },
                    new LogSettings
                    {
                        RetentionPolicy = new RetentionPolicy()
                        {
                            Days    = 5,
                            Enabled = false
                        },
                        Category = "TestCategory2",
                        Enabled  = false
                    }
                },
                Metrics = new List <MetricSettings>
                {
                    new MetricSettings
                    {
                        Category        = "MetricCat1",
                        RetentionPolicy = new RetentionPolicy()
                        {
                            Days    = 7,
                            Enabled = false
                        },
                        TimeGrain = TimeSpan.FromMinutes(1),
                        Enabled   = false
                    },
                    new MetricSettings
                    {
                        Category        = "MetricCat2",
                        RetentionPolicy = new RetentionPolicy()
                        {
                            Days    = 3,
                            Enabled = true
                        },
                        TimeGrain = TimeSpan.FromHours(1)
                    }
                }
            };

            response = new Microsoft.Rest.Azure.AzureOperationResponse <DiagnosticSettingsResource>()
            {
                RequestId = Guid.NewGuid().ToString(),
                Response  = new System.Net.Http.HttpResponseMessage
                {
                    StatusCode = System.Net.HttpStatusCode.OK
                },
                Body = resource
            };

            insightsDiagnosticsOperationsMock.Setup(f => f.DeleteWithHttpMessagesAsync(
                                                        It.IsAny <string>(),
                                                        It.IsAny <string>(),
                                                        It.IsAny <Dictionary <string, List <string> > >(),
                                                        It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult(new Rest.Azure.AzureOperationResponse
            {
                RequestId = "111-222"
            }))
            .Callback((string resourceId, string settingName, Dictionary <string, List <string> > headers, CancellationToken t) =>
            {
                resourceIdIn     = resourceId;
                this.settingName = settingName;
            });

            insightsDiagnosticsOperationsMock.Setup(f => f.CreateOrUpdateWithHttpMessagesAsync(
                                                        It.IsAny <string>(),
                                                        It.IsAny <DiagnosticSettingsResource>(),
                                                        It.IsAny <string>(),
                                                        It.IsAny <Dictionary <string, List <string> > >(),
                                                        It.IsAny <CancellationToken>()))
            .Returns((string a, DiagnosticSettingsResource x, string name, Dictionary <string, List <string> > b, CancellationToken c) =>
            {
                calledSettings = new DiagnosticSettingsResource(name: name)
                {
                    EventHubAuthorizationRuleId = x.EventHubAuthorizationRuleId,
                    EventHubName     = x.EventHubName,
                    Logs             = x.Logs,
                    Metrics          = x.Metrics,
                    StorageAccountId = x.StorageAccountId,
                    WorkspaceId      = x.WorkspaceId
                };
                return(Task.FromResult(new Rest.Azure.AzureOperationResponse <DiagnosticSettingsResource>
                {
                    RequestId = Guid.NewGuid().ToString(),
                    Body = x,
                    Response = new System.Net.Http.HttpResponseMessage
                    {
                        StatusCode = System.Net.HttpStatusCode.OK
                    }
                }));
            });

            insightsDiagnosticsOperationsMock.Setup(f => f.GetWithHttpMessagesAsync(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <Dictionary <string, List <string> > >(), It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult <Microsoft.Rest.Azure.AzureOperationResponse <DiagnosticSettingsResource> >(response))
            .Callback((string resourceId, string name, Dictionary <string, List <string> > headers, CancellationToken cancellationToken) =>
            {
                resourceIdIn     = resourceId;
                this.settingName = name;
            });

            multipleResponse = new Microsoft.Rest.Azure.AzureOperationResponse <DiagnosticSettingsResourceCollection>()
            {
                Body = new DiagnosticSettingsResourceCollection(
                    value: new List <DiagnosticSettingsResource>()
                {
                    resource
                })
            };

            insightsDiagnosticsOperationsMock.Setup(f => f.ListWithHttpMessagesAsync(It.IsAny <string>(), It.IsAny <Dictionary <string, List <string> > >(), It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult(multipleResponse))
            .Callback((string resourceId, Dictionary <string, List <string> > headers, CancellationToken cancellationToken) =>
            {
                resourceIdIn     = resourceId;
                this.settingName = "service";
            });

            insightsManagementClientMock.SetupGet(f => f.DiagnosticSettings).Returns(this.insightsDiagnosticsOperationsMock.Object);

            cmdlet.ResourceId = ResourceId;

            // Setup Confirmation
            commandRuntimeMock.Setup(f => f.ShouldProcess(It.IsAny <string>())).Returns(true);
            commandRuntimeMock.Setup(f => f.ShouldProcess(It.IsAny <string>(), It.IsAny <string>())).Returns(true);
            commandRuntimeMock.Setup(f => f.ShouldProcess(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>())).Returns(true);
            commandRuntimeMock.Setup(f => f.ShouldContinue(It.IsAny <string>(), It.IsAny <string>())).Returns(true);
        }
Beispiel #9
0
        /// <summary>
        /// List the alert rules within a resource group.
        /// </summary>
        /// <param name='resourceGroupName'>
        /// The name of the resource group.
        /// </param>
        /// <param name='odataQuery'>
        /// OData parameters to apply to the operation.
        /// </param>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="Microsoft.Rest.Azure.CloudException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="Microsoft.Rest.SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="Microsoft.Rest.ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public async System.Threading.Tasks.Task <Microsoft.Rest.Azure.AzureOperationResponse <System.Collections.Generic.IEnumerable <AlertRuleResource> > > ListByResourceGroupWithHttpMessagesAsync(string resourceGroupName, Microsoft.Rest.Azure.OData.ODataQuery <AlertRuleResource> odataQuery = default(Microsoft.Rest.Azure.OData.ODataQuery <AlertRuleResource>), System.Collections.Generic.Dictionary <string, System.Collections.Generic.List <string> > customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
        {
            if (resourceGroupName == null)
            {
                throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "resourceGroupName");
            }
            if (this.Client.SubscriptionId == null)
            {
                throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
            }
            string apiVersion = "2016-03-01";
            // Tracing
            bool   _shouldTrace  = Microsoft.Rest.ServiceClientTracing.IsEnabled;
            string _invocationId = null;

            if (_shouldTrace)
            {
                _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
                System.Collections.Generic.Dictionary <string, object> tracingParameters = new System.Collections.Generic.Dictionary <string, object>();
                tracingParameters.Add("odataQuery", odataQuery);
                tracingParameters.Add("resourceGroupName", resourceGroupName);
                tracingParameters.Add("apiVersion", apiVersion);
                tracingParameters.Add("cancellationToken", cancellationToken);
                Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "ListByResourceGroup", tracingParameters);
            }
            // Construct URL
            var _baseUrl = this.Client.BaseUri.AbsoluteUri;
            var _url     = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/microsoft.insights/alertrules").ToString();

            _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
            _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId));
            System.Collections.Generic.List <string> _queryParameters = new System.Collections.Generic.List <string>();
            if (odataQuery != null)
            {
                var _odataFilter = odataQuery.ToString();
                if (!string.IsNullOrEmpty(_odataFilter))
                {
                    _queryParameters.Add(_odataFilter);
                }
            }
            if (apiVersion != null)
            {
                _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
            }
            if (_queryParameters.Count > 0)
            {
                _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
            }
            // Create HTTP transport objects
            System.Net.Http.HttpRequestMessage  _httpRequest  = new System.Net.Http.HttpRequestMessage();
            System.Net.Http.HttpResponseMessage _httpResponse = null;
            _httpRequest.Method     = new System.Net.Http.HttpMethod("GET");
            _httpRequest.RequestUri = new System.Uri(_url);
            // Set Headers
            if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
            {
                _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
            }
            if (this.Client.AcceptLanguage != null)
            {
                if (_httpRequest.Headers.Contains("accept-language"))
                {
                    _httpRequest.Headers.Remove("accept-language");
                }
                _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
            }
            if (customHeaders != null)
            {
                foreach (var _header in customHeaders)
                {
                    if (_httpRequest.Headers.Contains(_header.Key))
                    {
                        _httpRequest.Headers.Remove(_header.Key);
                    }
                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
                }
            }

            // Serialize Request
            string _requestContent = null;

            // Set Credentials
            if (this.Client.Credentials != null)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            }
            // Send Request
            if (_shouldTrace)
            {
                Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);

            if (_shouldTrace)
            {
                Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
            }
            System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
            cancellationToken.ThrowIfCancellationRequested();
            string _responseContent = null;

            if ((int)_statusCode != 200)
            {
                var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                try
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                    CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <CloudError>(_responseContent, this.Client.DeserializationSettings);
                    if (_errorBody != null)
                    {
                        ex      = new Microsoft.Rest.Azure.CloudException(_errorBody.Message);
                        ex.Body = _errorBody;
                    }
                }
                catch (Newtonsoft.Json.JsonException)
                {
                    // Ignore the exception
                }
                ex.Request  = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
                ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
                if (_httpResponse.Headers.Contains("x-ms-request-id"))
                {
                    ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
                }
                if (_shouldTrace)
                {
                    Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
                }
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            // Create Result
            var _result = new Microsoft.Rest.Azure.AzureOperationResponse <System.Collections.Generic.IEnumerable <AlertRuleResource> >();

            _result.Request  = _httpRequest;
            _result.Response = _httpResponse;
            if (_httpResponse.Headers.Contains("x-ms-request-id"))
            {
                _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
            }
            // Deserialize Response
            if ((int)_statusCode == 200)
            {
                _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                try
                {
                    _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <Page1 <AlertRuleResource> >(_responseContent, this.Client.DeserializationSettings);
                }
                catch (Newtonsoft.Json.JsonException ex)
                {
                    _httpRequest.Dispose();
                    if (_httpResponse != null)
                    {
                        _httpResponse.Dispose();
                    }
                    throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex);
                }
            }
            if (_shouldTrace)
            {
                Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
            }
            return(_result);
        }
        public GetDiagnosticSettingCommandTests(Xunit.Abstractions.ITestOutputHelper output)
        {
            ServiceManagemenet.Common.Models.XunitTracingInterceptor.AddToContext(new ServiceManagemenet.Common.Models.XunitTracingInterceptor(output));
            insightsDiagnosticsOperationsMock = new Mock<IServiceDiagnosticSettingsOperations>();
            insightsManagementClientMock = new Mock<InsightsManagementClient>();
            commandRuntimeMock = new Mock<ICommandRuntime>();
            cmdlet = new GetAzureRmDiagnosticSettingCommand()
            {
                CommandRuntime = commandRuntimeMock.Object,
                InsightsManagementClient = insightsManagementClientMock.Object
            };

            response = new Microsoft.Rest.Azure.AzureOperationResponse<ServiceDiagnosticSettingsResource>()
            {
                Body = new ServiceDiagnosticSettingsResource
                {
                    Location = "some",
                    ServiceBusRuleId = "",
                    StorageAccountId = "/subscriptions/123/resourcegroups/rg/providers/microsoft.storage/accounts/myaccount",
                    WorkspaceId = "",
                    Logs = new List<LogSettings>
                    {
                        new LogSettings
                        {
                            RetentionPolicy = new RetentionPolicy()
                            {
                                Days = 10,
                                Enabled = true
                            },
                            Category = "TestCategory1",
                            Enabled = true
                        },
                        new LogSettings
                        {
                            RetentionPolicy = new RetentionPolicy()
                            {
                                Days = 5,
                                Enabled = false
                            },
                            Category = "TestCategory2",
                            Enabled = false
                        }
                    },
                    Metrics = new List<MetricSettings>
                    {
                        new MetricSettings
                        {
                            RetentionPolicy = new RetentionPolicy()
                            {
                                Days = 7,
                                Enabled = false
                            },
                            TimeGrain = TimeSpan.FromMinutes(1),
                            Enabled = false
                        },
                        new MetricSettings
                        {
                            RetentionPolicy = new RetentionPolicy()
                            {
                                Days = 3,
                                Enabled = true
                            },
                            TimeGrain = TimeSpan.FromHours(1)
                        }
                    }
                }
            };

            insightsDiagnosticsOperationsMock.Setup(f => f.GetWithHttpMessagesAsync(It.IsAny<string>(), It.IsAny<Dictionary<string, List<string>>>(), It.IsAny<CancellationToken>()))
                .Returns(Task.FromResult<Microsoft.Rest.Azure.AzureOperationResponse<ServiceDiagnosticSettingsResource>>(response))
                .Callback((string resourceId, Dictionary<string, List<string>> headers, CancellationToken cancellationToken) =>
                {
                    this.calledResourceId = resourceId;
                });

            insightsManagementClientMock.SetupGet(f => f.ServiceDiagnosticSettings).Returns(this.insightsDiagnosticsOperationsMock.Object);
        }
Beispiel #11
0
        /// <summary>
        /// Lists all of the applications available in the specified account.
        /// </summary>
        /// <param name='applicationListOptions'>
        /// Additional parameters for the operation
        /// </param>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="BatchErrorException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="Microsoft.Rest.SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="Microsoft.Rest.ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public async System.Threading.Tasks.Task <Microsoft.Rest.Azure.AzureOperationResponse <Microsoft.Rest.Azure.IPage <ApplicationSummary>, ApplicationListHeaders> > ListWithHttpMessagesAsync(ApplicationListOptions applicationListOptions = default(ApplicationListOptions), System.Collections.Generic.Dictionary <string, System.Collections.Generic.List <string> > customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
        {
            if (this.Client.ApiVersion == null)
            {
                throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.ApiVersion");
            }
            int?maxResults = default(int?);

            if (applicationListOptions != null)
            {
                maxResults = applicationListOptions.MaxResults;
            }
            int?timeout = default(int?);

            if (applicationListOptions != null)
            {
                timeout = applicationListOptions.Timeout;
            }
            string clientRequestId = default(string);

            if (applicationListOptions != null)
            {
                clientRequestId = applicationListOptions.ClientRequestId;
            }
            bool?returnClientRequestId = default(bool?);

            if (applicationListOptions != null)
            {
                returnClientRequestId = applicationListOptions.ReturnClientRequestId;
            }
            System.DateTime?ocpDate = default(System.DateTime?);
            if (applicationListOptions != null)
            {
                ocpDate = applicationListOptions.OcpDate;
            }
            // Tracing
            bool   _shouldTrace  = Microsoft.Rest.ServiceClientTracing.IsEnabled;
            string _invocationId = null;

            if (_shouldTrace)
            {
                _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
                System.Collections.Generic.Dictionary <string, object> tracingParameters = new System.Collections.Generic.Dictionary <string, object>();
                tracingParameters.Add("maxResults", maxResults);
                tracingParameters.Add("timeout", timeout);
                tracingParameters.Add("clientRequestId", clientRequestId);
                tracingParameters.Add("returnClientRequestId", returnClientRequestId);
                tracingParameters.Add("ocpDate", ocpDate);
                tracingParameters.Add("cancellationToken", cancellationToken);
                Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
            }
            // Construct URL
            var _baseUrl = this.Client.BaseUri.AbsoluteUri;
            var _url     = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "applications").ToString();

            System.Collections.Generic.List <string> _queryParameters = new System.Collections.Generic.List <string>();
            if (this.Client.ApiVersion != null)
            {
                _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(this.Client.ApiVersion)));
            }
            if (maxResults != null)
            {
                _queryParameters.Add(string.Format("maxresults={0}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(maxResults, this.Client.SerializationSettings).Trim('"'))));
            }
            if (timeout != null)
            {
                _queryParameters.Add(string.Format("timeout={0}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(timeout, this.Client.SerializationSettings).Trim('"'))));
            }
            if (_queryParameters.Count > 0)
            {
                _url += "?" + string.Join("&", _queryParameters);
            }
            // Create HTTP transport objects
            System.Net.Http.HttpRequestMessage  _httpRequest  = new System.Net.Http.HttpRequestMessage();
            System.Net.Http.HttpResponseMessage _httpResponse = null;
            _httpRequest.Method     = new System.Net.Http.HttpMethod("GET");
            _httpRequest.RequestUri = new System.Uri(_url);
            // Set Headers
            if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
            {
                _httpRequest.Headers.TryAddWithoutValidation("client-request-id", System.Guid.NewGuid().ToString());
            }
            if (this.Client.AcceptLanguage != null)
            {
                if (_httpRequest.Headers.Contains("accept-language"))
                {
                    _httpRequest.Headers.Remove("accept-language");
                }
                _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
            }
            if (clientRequestId != null)
            {
                if (_httpRequest.Headers.Contains("client-request-id"))
                {
                    _httpRequest.Headers.Remove("client-request-id");
                }
                _httpRequest.Headers.TryAddWithoutValidation("client-request-id", clientRequestId);
            }
            if (returnClientRequestId != null)
            {
                if (_httpRequest.Headers.Contains("return-client-request-id"))
                {
                    _httpRequest.Headers.Remove("return-client-request-id");
                }
                _httpRequest.Headers.TryAddWithoutValidation("return-client-request-id", Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(returnClientRequestId, this.Client.SerializationSettings).Trim('"'));
            }
            if (ocpDate != null)
            {
                if (_httpRequest.Headers.Contains("ocp-date"))
                {
                    _httpRequest.Headers.Remove("ocp-date");
                }
                _httpRequest.Headers.TryAddWithoutValidation("ocp-date", Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(ocpDate, new Microsoft.Rest.Serialization.DateTimeRfc1123JsonConverter()).Trim('"'));
            }
            if (customHeaders != null)
            {
                foreach (var _header in customHeaders)
                {
                    if (_httpRequest.Headers.Contains(_header.Key))
                    {
                        _httpRequest.Headers.Remove(_header.Key);
                    }
                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
                }
            }

            // Serialize Request
            string _requestContent = null;

            // Set Credentials
            if (this.Client.Credentials != null)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            }
            // Send Request
            if (_shouldTrace)
            {
                Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);

            if (_shouldTrace)
            {
                Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
            }
            System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
            cancellationToken.ThrowIfCancellationRequested();
            string _responseContent = null;

            if ((int)_statusCode != 200)
            {
                var ex = new BatchErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                try
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                    BatchError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <BatchError>(_responseContent, this.Client.DeserializationSettings);
                    if (_errorBody != null)
                    {
                        ex.Body = _errorBody;
                    }
                }
                catch (Newtonsoft.Json.JsonException)
                {
                    // Ignore the exception
                }
                ex.Request  = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
                ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
                if (_shouldTrace)
                {
                    Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
                }
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            // Create Result
            var _result = new Microsoft.Rest.Azure.AzureOperationResponse <Microsoft.Rest.Azure.IPage <ApplicationSummary>, ApplicationListHeaders>();

            _result.Request  = _httpRequest;
            _result.Response = _httpResponse;
            if (_httpResponse.Headers.Contains("request-id"))
            {
                _result.RequestId = _httpResponse.Headers.GetValues("request-id").FirstOrDefault();
            }
            // Deserialize Response
            if ((int)_statusCode == 200)
            {
                _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                try
                {
                    _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <Page <ApplicationSummary> >(_responseContent, this.Client.DeserializationSettings);
                }
                catch (Newtonsoft.Json.JsonException ex)
                {
                    _httpRequest.Dispose();
                    if (_httpResponse != null)
                    {
                        _httpResponse.Dispose();
                    }
                    throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex);
                }
            }
            try
            {
                _result.Headers = _httpResponse.GetHeadersAsJson().ToObject <ApplicationListHeaders>(Newtonsoft.Json.JsonSerializer.Create(this.Client.DeserializationSettings));
            }
            catch (Newtonsoft.Json.JsonException ex)
            {
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw new Microsoft.Rest.SerializationException("Unable to deserialize the headers.", _httpResponse.GetHeadersAsJson().ToString(), ex);
            }
            if (_shouldTrace)
            {
                Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
            }
            return(_result);
        }