public AddAzureRmAutoscaleSettingTests(Xunit.Abstractions.ITestOutputHelper output) { ServiceManagemenet.Common.Models.XunitTracingInterceptor.AddToContext(new ServiceManagemenet.Common.Models.XunitTracingInterceptor(output)); TestExecutionHelpers.SetUpSessionAndProfile(); insightsAutoscaleOperationsMock = new Mock <IAutoscaleSettingsOperations>(); insightsManagementClientMock = new Mock <MonitorManagementClient>(); commandRuntimeMock = new Mock <ICommandRuntime>(); cmdlet = new AddAzureRmAutoscaleSettingCommand() { CommandRuntime = commandRuntimeMock.Object, MonitorManagementClient = insightsManagementClientMock.Object }; response = new AzureOperationResponse <AutoscaleSettingResource>() { Body = new AutoscaleSettingResource() }; insightsAutoscaleOperationsMock.Setup(f => f.CreateOrUpdateWithHttpMessagesAsync(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <AutoscaleSettingResource>(), It.IsAny <Dictionary <string, List <string> > >(), It.IsAny <CancellationToken>())) .Returns(Task.FromResult <Microsoft.Rest.Azure.AzureOperationResponse <AutoscaleSettingResource> >(response)) .Callback((string resourceGrp, string settingNm, AutoscaleSettingResource createOrUpdateParams, Dictionary <string, List <string> > headers, CancellationToken t) => { resourceGroup = resourceGrp; settingName = settingNm; createOrUpdatePrms = createOrUpdateParams; }); insightsManagementClientMock.SetupGet(f => f.AutoscaleSettings).Returns(this.insightsAutoscaleOperationsMock.Object); // 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); }
public AddAzureRmAutoscaleSettingTests(Xunit.Abstractions.ITestOutputHelper output) { //ServiceManagemenet.Common.Models.XunitTracingInterceptor.AddToContext(new ServiceManagemenet.Common.Models.XunitTracingInterceptor(output)); insightsAutoscaleOperationsMock = new Mock<IAutoscaleSettingsOperations>(); insightsManagementClientMock = new Mock<InsightsManagementClient>(); commandRuntimeMock = new Mock<ICommandRuntime>(); cmdlet = new AddAzureRmAutoscaleSettingCommand() { CommandRuntime = commandRuntimeMock.Object, InsightsManagementClient = insightsManagementClientMock.Object }; response = new AzureOperationResponse<AutoscaleSettingResource>() { Body = new AutoscaleSettingResource() }; insightsAutoscaleOperationsMock.Setup(f => f.CreateOrUpdateWithHttpMessagesAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<AutoscaleSettingResource>(), It.IsAny<Dictionary<string, List<string>>>(), It.IsAny<CancellationToken>())) .Returns(Task.FromResult<Microsoft.Rest.Azure.AzureOperationResponse<AutoscaleSettingResource>>(response)) .Callback((string resourceGrp, string settingNm, AutoscaleSettingResource createOrUpdateParams, Dictionary<string, List<string>> headers, CancellationToken t) => { resourceGroup = resourceGrp; settingName = settingNm; createOrUpdatePrms = createOrUpdateParams; }); insightsManagementClientMock.SetupGet(f => f.AutoscaleSettings).Returns(this.insightsAutoscaleOperationsMock.Object); }
/// <summary> /// x-ms-client-request-id = 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0 is required /// message header for all requests. Long running put request, service /// returns a 201 to the initial request, with an entity that contains /// ProvisioningState=’Creating’. Polls return this value until the last /// poll returns a ‘200’ with ProvisioningState=’Succeeded’ /// </summary> /// <param name='product'> /// Product to put /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async System.Threading.Tasks.Task <Microsoft.Rest.Azure.AzureOperationResponse <Product> > Put201CreatingSucceeded200WithHttpMessagesAsync(Product product = default(Product), System.Collections.Generic.Dictionary <string, System.Collections.Generic.List <string> > customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { // Send Request Microsoft.Rest.Azure.AzureOperationResponse <Product> _response = await BeginPut201CreatingSucceeded200WithHttpMessagesAsync( product, customHeaders, cancellationToken); return(await this.Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken)); }
/// <summary> /// Creates a session for a node /// </summary> /// <param name='resourceGroupName'> /// The resource group name uniquely identifies the resource group within the /// user subscriptionId. /// </param> /// <param name='nodeName'> /// The node name (256 characters maximum). /// </param> /// <param name='session'> /// The sessionId from the user /// </param> /// <param name='userName'> /// encrypted User name to be used to connect to node /// </param> /// <param name='password'> /// encrypted Password associated with user name /// </param> /// <param name='retentionPeriod'> /// session retention period. Possible values include: 'Session', 'Persistent' /// </param> /// <param name='credentialDataFormat'> /// credential data format. Possible values include: 'RsaEncrypted' /// </param> /// <param name='encryptionCertificateThumbprint'> /// encryption certificate thumbprint /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async System.Threading.Tasks.Task <Microsoft.Rest.Azure.AzureOperationResponse <SessionResource> > CreateWithHttpMessagesAsync(string resourceGroupName, string nodeName, string session, string userName = default(string), string password = default(string), RetentionPeriod?retentionPeriod = default(RetentionPeriod?), CredentialDataFormat?credentialDataFormat = default(CredentialDataFormat?), string encryptionCertificateThumbprint = default(string), System.Collections.Generic.Dictionary <string, System.Collections.Generic.List <string> > customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { // Send Request Microsoft.Rest.Azure.AzureOperationResponse <SessionResource> _response = await BeginCreateWithHttpMessagesAsync( resourceGroupName, nodeName, session, userName, password, retentionPeriod, credentialDataFormat, encryptionCertificateThumbprint, customHeaders, cancellationToken); return(await this.Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken)); }
public GetAzureRmAutoscaleSettingTests(Xunit.Abstractions.ITestOutputHelper output) { ServiceManagement.Common.Models.XunitTracingInterceptor.AddToContext(new ServiceManagement.Common.Models.XunitTracingInterceptor(output)); TestExecutionHelpers.SetUpSessionAndProfile(); insightsAutoscaleOperationsMock = new Mock <IAutoscaleSettingsOperations>(); insightsManagementClientMock = new Mock <MonitorManagementClient>() { CallBase = true }; commandRuntimeMock = new Mock <ICommandRuntime>(); cmdlet = new GetAzureRmAutoscaleSettingCommand() { CommandRuntime = commandRuntimeMock.Object, MonitorManagementClient = insightsManagementClientMock.Object }; var responseObject = new AutoscaleSettingResource(id: "", location: "", profiles: null, autoscaleSettingResourceName: "", name: "") { Tags = null, }; responseSimple = new Microsoft.Rest.Azure.AzureOperationResponse <AutoscaleSettingResource>() { Body = responseObject }; responsePage = new AzureOperationResponse <IPage <AutoscaleSettingResource> >() { Body = JsonConvert.DeserializeObject <Microsoft.Azure.Management.Monitor.Models.Page <AutoscaleSettingResource> >(JsonConvert.SerializeObject(responseObject)) }; insightsAutoscaleOperationsMock.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 <AutoscaleSettingResource> >(responseSimple)) .Callback((string resourceGrp, string settingNm, Dictionary <string, List <string> > headers, CancellationToken t) => { resourceGroup = resourceGrp; settingName = settingNm; }); insightsAutoscaleOperationsMock.Setup(f => f.ListByResourceGroupWithHttpMessagesAsync(It.IsAny <string>(), It.IsAny <Dictionary <string, List <string> > >(), It.IsAny <CancellationToken>())) .Returns(Task.FromResult <Microsoft.Rest.Azure.AzureOperationResponse <IPage <AutoscaleSettingResource> > >(responsePage)) .Callback((string resourceGrp, Dictionary <string, List <string> > headers, CancellationToken t) => { resourceGroup = resourceGrp; }); insightsManagementClientMock.SetupGet(f => f.AutoscaleSettings).Returns(this.insightsAutoscaleOperationsMock.Object); }
public GetAzureRmAutoscaleSettingTests(Xunit.Abstractions.ITestOutputHelper output) { //ServiceManagemenet.Common.Models.XunitTracingInterceptor.AddToContext(new ServiceManagemenet.Common.Models.XunitTracingInterceptor(output)); insightsAutoscaleOperationsMock = new Mock<IAutoscaleSettingsOperations>(); insightsManagementClientMock = new Mock<InsightsManagementClient>(); commandRuntimeMock = new Mock<ICommandRuntime>(); cmdlet = new GetAzureRmAutoscaleSettingCommand() { CommandRuntime = commandRuntimeMock.Object, InsightsManagementClient = insightsManagementClientMock.Object }; var responseObject = new AutoscaleSettingResource(id: "", location: "", profiles: null, autoscaleSettingResourceName: "") { Name = "", Tags = null, }; responseSimple = new Microsoft.Rest.Azure.AzureOperationResponse<AutoscaleSettingResource>() { Body = responseObject }; responsePage = new AzureOperationResponse<IPage<AutoscaleSettingResource>>() { Body = JsonConvert.DeserializeObject<Microsoft.Azure.Management.Insights.Models.Page<AutoscaleSettingResource>>(JsonConvert.SerializeObject(responseObject)) }; insightsAutoscaleOperationsMock.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<AutoscaleSettingResource>>(responseSimple)) .Callback((string resourceGrp, string settingNm, Dictionary<string, List<string>> headers, CancellationToken t) => { resourceGroup = resourceGrp; settingName = settingNm; }); insightsAutoscaleOperationsMock.Setup(f => f.ListByResourceGroupWithHttpMessagesAsync(It.IsAny<string>(), It.IsAny<ODataQuery<AutoscaleSettingResource>>(), It.IsAny<Dictionary<string, List<string>>>(), It.IsAny<CancellationToken>())) .Returns(Task.FromResult<Microsoft.Rest.Azure.AzureOperationResponse<IPage<AutoscaleSettingResource>>>(responsePage)) .Callback((string resourceGrp, ODataQuery<AutoscaleSettingResource> qry, Dictionary<string, List<string>> headers, CancellationToken t) => { resourceGroup = resourceGrp; query = qry; }); insightsManagementClientMock.SetupGet(f => f.AutoscaleSettings).Returns(this.insightsAutoscaleOperationsMock.Object); }
/// <summary> /// Return 200 status code if successful /// </summary> /// <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> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task <Microsoft.Rest.Azure.AzureOperationResponse <bool> > Head200WithHttpMessagesAsync(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, "Head200", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "http/success/200").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("HEAD"); _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 && (int)_statusCode != 404) { 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 <bool>(); _result.Request = _httpRequest; _result.Response = _httpResponse; _result.Body = (_statusCode == System.Net.HttpStatusCode.OK); if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return(_result); }
/// <summary> /// Update products /// </summary> /// <remarks> /// Resets products. /// </remarks> /// <param name='subscriptionId'> /// Subscription ID. /// </param> /// <param name='resourceGroupName'> /// Resource Group ID. /// </param> /// <param name='productArrayOfDictionary'> /// Array of dictionary of products /// </param> /// <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> /// <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 <CatalogArray> > UpdateWithHttpMessagesAsync(string subscriptionId, string resourceGroupName, System.Collections.Generic.IList <System.Collections.Generic.IDictionary <string, Product> > productArrayOfDictionary = default(System.Collections.Generic.IList <System.Collections.Generic.IDictionary <string, Product> >), System.Collections.Generic.Dictionary <string, System.Collections.Generic.List <string> > customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (subscriptionId == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "subscriptionId"); } if (resourceGroupName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "resourceGroupName"); } string apiVersion = "2014-04-01-preview"; CatalogArrayOfDictionary bodyParameter = new CatalogArrayOfDictionary(); if (productArrayOfDictionary != null) { bodyParameter.ProductArrayOfDictionary = productArrayOfDictionary; } // 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("subscriptionId", subscriptionId); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("bodyParameter", bodyParameter); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "Update", tracingParameters); } // Construct URL var _baseUrl = this.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/Microsoft.Cache/Redis").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(subscriptionId)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); System.Collections.Generic.List <string> _queryParameters = new System.Collections.Generic.List <string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } 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("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (this.GenerateClientRequestId != null && this.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (this.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.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; if (bodyParameter != null) { _requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(bodyParameter, this.SerializationSettings); _httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (this.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.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.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 <CatalogArray>(); _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 <CatalogArray>(_responseContent, this.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); }
/// <summary> /// Gets the log profile. /// </summary> /// <param name='logProfileName'> /// The name of the log profile. /// </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 <LogProfileResource> > GetWithHttpMessagesAsync(string logProfileName, System.Collections.Generic.Dictionary <string, System.Collections.Generic.List <string> > customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (logProfileName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "logProfileName"); } 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("logProfileName", logProfileName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/microsoft.insights/logprofiles/{logProfileName}").ToString(); _url = _url.Replace("{logProfileName}", System.Uri.EscapeDataString(logProfileName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId)); System.Collections.Generic.List <string> _queryParameters = new System.Collections.Generic.List <string>(); 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 <LogProfileResource>(); _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 <LogProfileResource>(_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 SetDiagnosticSettingCommandTests(Xunit.Abstractions.ITestOutputHelper output) { ServiceManagement.Common.Models.XunitTracingInterceptor.AddToContext(new ServiceManagement.Common.Models.XunitTracingInterceptor(output)); this.insightsDiagnosticsOperationsMock = new Mock <IDiagnosticSettingsOperations>(); this.insightsManagementClientMock = new Mock <MonitorManagementClient>() { CallBase = true }; this.commandRuntimeMock = new Mock <ICommandRuntime>(); this.cmdlet = new SetAzureRmDiagnosticSettingCommand() { CommandRuntime = commandRuntimeMock.Object, MonitorManagementClient = insightsManagementClientMock.Object }; this.ExistingSetting = GetDefaultSetting(name: "service"); insightsDiagnosticsOperationsMock.Setup(f => f.GetWithHttpMessagesAsync( It.IsAny <string>(), It.IsAny <string>(), It.IsAny <Dictionary <string, List <string> > >(), It.IsAny <CancellationToken>())) .Returns(Task.FromResult <AzureOperationResponse <DiagnosticSettingsResource> >(new AzureOperationResponse <DiagnosticSettingsResource> { Body = this.ExistingSetting })); 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, ServiceBusRuleId = x.ServiceBusRuleId, LogAnalyticsDestinationType = x.LogAnalyticsDestinationType }; return(Task.FromResult(new AzureOperationResponse <DiagnosticSettingsResource> { Body = x })); }); multipleResponse = new Microsoft.Rest.Azure.AzureOperationResponse <DiagnosticSettingsResourceCollection>() { Body = new DiagnosticSettingsResourceCollection( value: new List <DiagnosticSettingsResource>() { this.ExistingSetting }) }; insightsDiagnosticsOperationsMock.Setup(f => f.ListWithHttpMessagesAsync(It.IsAny <string>(), It.IsAny <Dictionary <string, List <string> > >(), It.IsAny <CancellationToken>())) .Returns((string rsId, Dictionary <string, List <string> > head, CancellationToken token) => { // this.calledResourceId = resourceId; // this.diagnosticSettingName = "service"; this.calledSettings = multipleResponse.Body.Value[0]; return(Task.FromResult(multipleResponse)); }); 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); }
/// <summary> /// Create or update a linked service. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group to get. The name is case insensitive. /// </param> /// <param name='workspaceName'> /// Name of the Log Analytics Workspace that will contain the linkedServices /// resource /// </param> /// <param name='linkedServiceName'> /// Name of the linkedServices resource /// </param> /// <param name='parameters'> /// The parameters required to create or update a linked service. /// </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 <LinkedService> > CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string workspaceName, string linkedServiceName, LinkedService parameters, 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 (resourceGroupName != null) { if (resourceGroupName.Length > 90) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.MaxLength, "resourceGroupName", 90); } if (resourceGroupName.Length < 1) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.MinLength, "resourceGroupName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+$")) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._\\(\\)]+$"); } } if (workspaceName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "workspaceName"); } if (linkedServiceName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "linkedServiceName"); } if (parameters == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "parameters"); } if (parameters != null) { parameters.Validate(); } if (this.Client.SubscriptionId == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2015-11-01-preview"; // 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("resourceGroupName", resourceGroupName); tracingParameters.Add("workspaceName", workspaceName); tracingParameters.Add("linkedServiceName", linkedServiceName); tracingParameters.Add("parameters", parameters); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "CreateOrUpdate", 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.OperationalInsights/workspaces/{workspaceName}/linkedServices/{linkedServiceName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{workspaceName}", System.Uri.EscapeDataString(workspaceName)); _url = _url.Replace("{linkedServiceName}", System.Uri.EscapeDataString(linkedServiceName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId)); System.Collections.Generic.List <string> _queryParameters = new System.Collections.Generic.List <string>(); 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("PUT"); _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; if (parameters != null) { _requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, this.Client.SerializationSettings); _httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // 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 && (int)_statusCode != 201) { 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 <LinkedService>(); _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 <LinkedService>(_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); } } // Deserialize Response if ((int)_statusCode == 201) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <LinkedService>(_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); }
/// <summary> /// Gets information about the specified application. /// </summary> /// <param name='applicationId'> /// The id of the application. /// </param> /// <param name='applicationGetOptions'> /// 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 <ApplicationSummary, ApplicationGetHeaders> > GetWithHttpMessagesAsync(string applicationId, ApplicationGetOptions applicationGetOptions = default(ApplicationGetOptions), System.Collections.Generic.Dictionary <string, System.Collections.Generic.List <string> > customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (applicationId == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "applicationId"); } if (this.Client.ApiVersion == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } int?timeout = default(int?); if (applicationGetOptions != null) { timeout = applicationGetOptions.Timeout; } string clientRequestId = default(string); if (applicationGetOptions != null) { clientRequestId = applicationGetOptions.ClientRequestId; } bool?returnClientRequestId = default(bool?); if (applicationGetOptions != null) { returnClientRequestId = applicationGetOptions.ReturnClientRequestId; } System.DateTime?ocpDate = default(System.DateTime?); if (applicationGetOptions != null) { ocpDate = applicationGetOptions.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("applicationId", applicationId); 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, "Get", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "applications/{applicationId}").ToString(); _url = _url.Replace("{applicationId}", System.Uri.EscapeDataString(applicationId)); 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 (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 <ApplicationSummary, ApplicationGetHeaders>(); _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 <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 <ApplicationGetHeaders>(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); }
/// <summary> /// Creates a session for a node /// </summary> /// <param name='resourceGroupName'> /// The resource group name uniquely identifies the resource group within the /// user subscriptionId. /// </param> /// <param name='nodeName'> /// The node name (256 characters maximum). /// </param> /// <param name='session'> /// The sessionId from the user /// </param> /// <param name='userName'> /// encrypted User name to be used to connect to node /// </param> /// <param name='password'> /// encrypted Password associated with user name /// </param> /// <param name='retentionPeriod'> /// session retention period. Possible values include: 'Session', 'Persistent' /// </param> /// <param name='credentialDataFormat'> /// credential data format. Possible values include: 'RsaEncrypted' /// </param> /// <param name='encryptionCertificateThumbprint'> /// encryption certificate thumbprint /// </param> /// <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> /// <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 <SessionResource> > BeginCreateWithHttpMessagesAsync(string resourceGroupName, string nodeName, string session, string userName = default(string), string password = default(string), RetentionPeriod?retentionPeriod = default(RetentionPeriod?), CredentialDataFormat?credentialDataFormat = default(CredentialDataFormat?), string encryptionCertificateThumbprint = default(string), System.Collections.Generic.Dictionary <string, System.Collections.Generic.List <string> > customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (this.Client.SubscriptionId == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (this.Client.ApiVersion == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (resourceGroupName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (resourceGroupName.Length < 3) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.MinLength, "resourceGroupName", 3); } if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "[a-zA-Z0-9]+")) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.Pattern, "resourceGroupName", "[a-zA-Z0-9]+"); } } if (nodeName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "nodeName"); } if (nodeName != null) { if (nodeName.Length > 256) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.MaxLength, "nodeName", 256); } if (nodeName.Length < 1) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.MinLength, "nodeName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(nodeName, "^[a-zA-Z0-9][a-zA-Z0-9_.-]*$")) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.Pattern, "nodeName", "^[a-zA-Z0-9][a-zA-Z0-9_.-]*$"); } } if (session == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "session"); } SessionParameters sessionParameters = new SessionParameters(); if (userName != null || password != null || encryptionCertificateThumbprint != null) { sessionParameters.UserName = userName; sessionParameters.Password = password; sessionParameters.RetentionPeriod = retentionPeriod; sessionParameters.CredentialDataFormat = credentialDataFormat; sessionParameters.EncryptionCertificateThumbprint = encryptionCertificateThumbprint; } // 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("resourceGroupName", resourceGroupName); tracingParameters.Add("nodeName", nodeName); tracingParameters.Add("session", session); tracingParameters.Add("sessionParameters", sessionParameters); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "BeginCreate", 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.ServerManagement/nodes/{nodeName}/sessions/{session}").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{nodeName}", System.Uri.EscapeDataString(nodeName)); _url = _url.Replace("{session}", System.Uri.EscapeDataString(session)); 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 (_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("PUT"); _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; if (sessionParameters != null) { _requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(sessionParameters, this.Client.SerializationSettings); _httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // 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 && (int)_statusCode != 201 && (int)_statusCode != 202) { 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 <SessionResource>(); _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 <SessionResource>(_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); } } // Deserialize Response if ((int)_statusCode == 201) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <SessionResource>(_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); }