/// <summary> /// Deletes the specified private endpoint connection associated with the /// storage sync service. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. The name is case insensitive. /// </param> /// <param name='storageSyncServiceName'> /// The name of the storage sync service name within the specified resource /// group. /// </param> /// <param name='privateEndpointConnectionName'> /// The name of the private endpoint connection associated with the Azure /// resource /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task <AzureOperationHeaderResponse <PrivateEndpointConnectionsDeleteHeaders> > DeleteWithHttpMessagesAsync(string resourceGroupName, string storageSyncServiceName, string privateEndpointConnectionName, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send request AzureOperationHeaderResponse <PrivateEndpointConnectionsDeleteHeaders> _response = await BeginDeleteWithHttpMessagesAsync(resourceGroupName, storageSyncServiceName, privateEndpointConnectionName, customHeaders, cancellationToken).ConfigureAwait(false); return(await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false)); }
/// <summary> /// x-ms-client-request-id = 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0 is required /// message header for all requests. Long running post request, service returns /// a 202 to the initial request, with 'Location' and 'Retry-After' headers, /// Polls return a 200 with a response body after success /// </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 Task <AzureOperationHeaderResponse <LROsCustomHeaderPost202Retry200Headers> > Post202Retry200WithHttpMessagesAsync(Product product = default(Product), Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send request AzureOperationHeaderResponse <LROsCustomHeaderPost202Retry200Headers> _response = await BeginPost202Retry200WithHttpMessagesAsync(product, customHeaders, cancellationToken).ConfigureAwait(false); return(await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false)); }
/// <summary> /// Accept subscription ownership. /// </summary> /// <param name='subscriptionId'> /// Subscription Id. /// </param> /// <param name='body'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task <AzureOperationHeaderResponse <SubscriptionAcceptOwnershipHeaders> > AcceptOwnershipWithHttpMessagesAsync(string subscriptionId, AcceptOwnershipRequest body, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send request AzureOperationHeaderResponse <SubscriptionAcceptOwnershipHeaders> _response = await BeginAcceptOwnershipWithHttpMessagesAsync(subscriptionId, body, customHeaders, cancellationToken).ConfigureAwait(false); return(await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false)); }
public void CannotModifyUsesTaskDependenciesOnAJobScheduleAfterItHasBeenCommitted() { const bool usesTaskDependencies = true; using BatchClient client = ClientUnitTestCommon.CreateDummyClient(); Protocol.RequestInterceptor interceptor = new Protocol.RequestInterceptor( baseRequest => { var request = (Protocol.BatchRequests.JobScheduleAddBatchRequest)baseRequest; request.ServiceRequestFunc = token => { var response = new AzureOperationHeaderResponse <Models.JobScheduleAddHeaders> { Response = new HttpResponseMessage(HttpStatusCode.Created) }; return(Task.FromResult(response)); }; }); Microsoft.Azure.Batch.CloudJobSchedule cloudJobSchedule = client.JobScheduleOperations.CreateJobSchedule(); Microsoft.Azure.Batch.JobSpecification jobSpec = new Microsoft.Azure.Batch.JobSpecification(poolInformation: null) { UsesTaskDependencies = usesTaskDependencies }; cloudJobSchedule.JobSpecification = jobSpec; cloudJobSchedule.Commit(new List <BatchClientBehavior> { interceptor }); // writing isn't allowed for a CloudJobSchedule.JobSpecification.UsesTaskDependencies that is in an invalid state. Assert.Throws <InvalidOperationException>(() => cloudJobSchedule.JobSpecification.UsesTaskDependencies = false); }
/// <summary> /// Deletes the specified Batch account. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group that contains the Batch account. /// </param> /// <param name='accountName'> /// The name of the Batch account. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task <AzureOperationHeaderResponse <RetryHeader> > DeleteWithHttpMessagesAsync(string resourceGroupName, string accountName, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send request AzureOperationHeaderResponse <RetryHeader> _response = await BeginDeleteWithHttpMessagesAsync(resourceGroupName, accountName, customHeaders, cancellationToken).ConfigureAwait(false); return(await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false)); }
/// <summary> /// Builds a NodeFileGetPropertiesFromComputeNodeResponse object /// </summary> public static AzureOperationHeaderResponse <ProxyModels.FileGetPropertiesFromComputeNodeHeaders> CreateNodeFileGetPropertiesByComputeNodeResponse() { var response = new AzureOperationHeaderResponse <ProxyModels.FileGetPropertiesFromComputeNodeHeaders>(); response.Response = new HttpResponseMessage(HttpStatusCode.OK); response.Headers = new ProxyModels.FileGetPropertiesFromComputeNodeHeaders(); return(response); }
public void RemoveComputeNodeRequestTest() { // Setup cmdlet to skip confirmation popup cmdlet.Force = true; commandRuntimeMock.Setup(f => f.ShouldProcess(It.IsAny <string>(), It.IsAny <string>())).Returns(true); BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys(); cmdlet.BatchContext = context; cmdlet.PoolId = "testPool"; cmdlet.Ids = new string[] { "computeNode1", "computeNode2" }; cmdlet.DeallocationOption = Microsoft.Azure.Batch.Common.ComputeNodeDeallocationOption.Terminate; cmdlet.ResizeTimeout = TimeSpan.FromMinutes(8); Microsoft.Azure.Batch.Common.ComputeNodeDeallocationOption?requestDeallocationOption = null; TimeSpan? requestResizeTimeout = null; IList <string> requestComputeNodeIds = null; // Don't go to the service on a Remove ComputeNode call RequestInterceptor interceptor = new RequestInterceptor((baseRequest) => { PoolRemoveNodesBatchRequest request = (PoolRemoveNodesBatchRequest)baseRequest; request.ServiceRequestFunc = (cancellationToken) => { // Grab the parameters from the outgoing request. requestDeallocationOption = BatchTestHelpers.MapEnum <Microsoft.Azure.Batch.Common.ComputeNodeDeallocationOption>(request.Parameters.NodeDeallocationOption); requestResizeTimeout = request.Parameters.ResizeTimeout; requestComputeNodeIds = request.Parameters.NodeList; var response = new AzureOperationHeaderResponse <PoolRemoveNodesHeaders>(); Task <AzureOperationHeaderResponse <PoolRemoveNodesHeaders> > task = Task.FromResult(response); return(task); }; }); cmdlet.AdditionalBehaviors = new List <BatchClientBehavior>() { interceptor }; cmdlet.ExecuteCmdlet(); // Verify that the parameters were properly set on the outgoing request Assert.Equal(cmdlet.DeallocationOption, requestDeallocationOption); Assert.Equal(cmdlet.ResizeTimeout, requestResizeTimeout); Assert.Equal(cmdlet.Ids.Length, requestComputeNodeIds.Count); foreach (string id in cmdlet.Ids) { Assert.True(requestComputeNodeIds.Contains(id)); } }
public async Task AutoPoolApplicationPackagesFlowThroughToPool() { var jobId = Guid.NewGuid().ToString(); var client = new BatchServiceClient(new Uri(Url), new BatchSharedKeyCredential(AccountName, AccountKey)); var poolInfo = new PoolInformation { AutoPoolSpecification = new AutoPoolSpecification(poolLifetimeOption: PoolLifetimeOption.Job, pool: new PoolSpecification { TargetDedicated = 0, ApplicationPackageReferences = new[] { new ApplicationPackageReference { ApplicationId = AppPackageName, Version = Version }, }, CloudServiceConfiguration = new CloudServiceConfiguration("4"), VmSize = "small", }) }; try { AzureOperationHeaderResponse <JobAddHeaders> addResponse = await client.Job.AddWithHttpMessagesAsync(new JobAddParameter(jobId, poolInfo : poolInfo)).ConfigureAwait(false); Assert.Equal(HttpStatusCode.Created, addResponse.Response.StatusCode); var autoPoolId = WaitForAutoPool(client, jobId); var poolResponse = await client.Pool.GetWithHttpMessagesAsync(autoPoolId).ConfigureAwait(false); Assert.Equal(HttpStatusCode.OK, poolResponse.Response.StatusCode); Assert.NotNull(poolResponse.Body); Assert.Equal(1, poolResponse.Body.ApplicationPackageReferences.Count); Assert.Equal(AppPackageName, poolResponse.Body.ApplicationPackageReferences[0].ApplicationId); Assert.Equal(Version, poolResponse.Body.ApplicationPackageReferences[0].Version); } finally { TestUtilities.DeleteJobIfExistsNoThrow(client, jobId, output); } }
public void RestartComputeNodeRequestTest() { BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys(); cmdlet.BatchContext = context; cmdlet.PoolId = "testPool"; cmdlet.Id = "computeNode1"; cmdlet.RebootOption = BatchCommon.ComputeNodeRebootOption.Terminate; ComputeNodeRebootOption?requestRebootOption = null; // Don't go to the service on a Reboot ComputeNode call RequestInterceptor interceptor = new RequestInterceptor((baseRequest) => { ComputeNodeRebootBatchRequest request = (ComputeNodeRebootBatchRequest)baseRequest; request.ServiceRequestFunc = (cancellationToken) => { // Grab the reboot option from the outgoing request. requestRebootOption = request.Parameters; var response = new AzureOperationHeaderResponse <ComputeNodeRebootHeaders>(); Task <AzureOperationHeaderResponse <ComputeNodeRebootHeaders> > task = Task.FromResult(response); return(task); }; }); cmdlet.AdditionalBehaviors = new List <BatchClientBehavior>() { interceptor }; cmdlet.ExecuteCmdlet(); // Verify that the reboot option was properly set on the outgoing request Assert.Equal(cmdlet.RebootOption, BatchTestHelpers.MapEnum <BatchCommon.ComputeNodeRebootOption>(requestRebootOption)); }
public void SetPoolOSVersionRequestTest() { BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys(); cmdlet.BatchContext = context; string targetOS = "targetOS"; string requestTargetOS = null; cmdlet.Id = "testPool"; cmdlet.TargetOSVersion = targetOS; // Don't go to the service on an Upgrade OS call RequestInterceptor interceptor = new RequestInterceptor((baseRequest) => { PoolUpgradeOSBatchRequest request = (PoolUpgradeOSBatchRequest)baseRequest; // Grab the target OS version off the outgoing request requestTargetOS = request.Parameters; request.ServiceRequestFunc = (cancellationToken) => { var response = new AzureOperationHeaderResponse <PoolUpgradeOSHeaders>(); Task <AzureOperationHeaderResponse <PoolUpgradeOSHeaders> > task = Task.FromResult(response); return(task); }; }); cmdlet.AdditionalBehaviors = new List <BatchClientBehavior>() { interceptor }; cmdlet.ExecuteCmdlet(); // Verify that the target OS was properly set on the outgoing request Assert.Equal(targetOS, requestTargetOS); }
public void DisableComputeNodeSchedulingRequestTest() { BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys(); cmdlet.BatchContext = context; BatchCommon.DisableComputeNodeSchedulingOption?disableOption = BatchCommon.DisableComputeNodeSchedulingOption.TaskCompletion; BatchCommon.DisableComputeNodeSchedulingOption?requestDisableOption = null; cmdlet.PoolId = "testPool"; cmdlet.Id = "computeNode1"; cmdlet.DisableSchedulingOption = disableOption; // Don't go to the service on an Disable Compute Node Scheduling call RequestInterceptor interceptor = new RequestInterceptor((baseRequest) => { ComputeNodeDisableSchedulingBatchRequest request = (ComputeNodeDisableSchedulingBatchRequest)baseRequest; requestDisableOption = BatchTestHelpers.MapEnum <BatchCommon.DisableComputeNodeSchedulingOption>(request.Parameters); request.ServiceRequestFunc = (cancellationToken) => { var response = new AzureOperationHeaderResponse <ComputeNodeDisableSchedulingHeaders>(); Task <AzureOperationHeaderResponse <ComputeNodeDisableSchedulingHeaders> > task = Task.FromResult(response); return(task); }; }); cmdlet.AdditionalBehaviors = new List <BatchClientBehavior>() { interceptor }; cmdlet.ExecuteCmdlet(); // Verify that the parameters were properly set on the outgoing request Assert.Equal(disableOption, requestDisableOption); }
/// <summary> /// Creates a RequestInterceptor that does not contact the Batch Service on a Get NodeFile or a Get NodeFile Properties call. /// The interceptor must handle both request types since it's possible for one OM node file method to perform both REST APIs. /// </summary> /// <param name="fileName">The name of the file to put in the response body.</param> public static RequestInterceptor CreateFakeGetFileAndPropertiesFromComputeNodeResponseInterceptor(string fileName) { RequestInterceptor interceptor = new RequestInterceptor((baseRequest) => { FileGetFromComputeNodeBatchRequest fileRequest = baseRequest as FileGetFromComputeNodeBatchRequest; if (fileRequest != null) { fileRequest.ServiceRequestFunc = (cancellationToken) => { var response = new AzureOperationResponse <Stream, ProxyModels.FileGetFromComputeNodeHeaders>(); response.Headers = new ProxyModels.FileGetFromComputeNodeHeaders(); response.Body = new MemoryStream(); Task <AzureOperationResponse <Stream, ProxyModels.FileGetFromComputeNodeHeaders> > task = Task.FromResult(response); return(task); }; } else { FileGetNodeFilePropertiesFromComputeNodeBatchRequest propRequest = (FileGetNodeFilePropertiesFromComputeNodeBatchRequest)baseRequest; propRequest.ServiceRequestFunc = (cancellationToken) => { var response = new AzureOperationHeaderResponse <ProxyModels.FileGetPropertiesFromComputeNodeHeaders>(); response.Headers = new ProxyModels.FileGetPropertiesFromComputeNodeHeaders(); Task <AzureOperationHeaderResponse <ProxyModels.FileGetPropertiesFromComputeNodeHeaders> > task = Task.FromResult(response); return(task); }; } }); return(interceptor); }
/// <summary> /// Accept subscription ownership. /// </summary> /// <param name='subscriptionId'> /// Subscription Id. /// </param> /// <param name='body'> /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseBodyException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task <AzureOperationHeaderResponse <SubscriptionAcceptOwnershipHeaders> > BeginAcceptOwnershipWithHttpMessagesAsync(string subscriptionId, AcceptOwnershipRequest body, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (subscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "subscriptionId"); } if (body == null) { throw new ValidationException(ValidationRules.CannotBeNull, "body"); } if (body != null) { body.Validate(); } string apiVersion = "2021-10-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("subscriptionId", subscriptionId); tracingParameters.Add("body", body); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginAcceptOwnership", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "providers/Microsoft.Subscription/subscriptions/{subscriptionId}/acceptOwnership").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(subscriptionId)); List <string> _queryParameters = new 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 var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("POST"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", 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 (body != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(body, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 202) { var ex = new ErrorResponseBodyException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponseBody _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject <ErrorResponseBody>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationHeaderResponse <SubscriptionAcceptOwnershipHeaders>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } try { _result.Headers = _httpResponse.GetHeadersAsJson().ToObject <SubscriptionAcceptOwnershipHeaders>(JsonSerializer.Create(Client.DeserializationSettings)); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the headers.", _httpResponse.GetHeadersAsJson().ToString(), ex); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return(_result); }
public void DisableComputeNodeSchedulingRequestTest() { BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys(); cmdlet.BatchContext = context; BatchCommon.DisableComputeNodeSchedulingOption? disableOption = BatchCommon.DisableComputeNodeSchedulingOption.TaskCompletion; BatchCommon.DisableComputeNodeSchedulingOption? requestDisableOption = null; cmdlet.PoolId = "testPool"; cmdlet.Id = "computeNode1"; cmdlet.DisableSchedulingOption = disableOption; // Don't go to the service on an Disable Compute Node Scheduling call RequestInterceptor interceptor = new RequestInterceptor((baseRequest) => { ComputeNodeDisableSchedulingBatchRequest request = (ComputeNodeDisableSchedulingBatchRequest)baseRequest; requestDisableOption = BatchTestHelpers.MapEnum<BatchCommon.DisableComputeNodeSchedulingOption>(request.Parameters); request.ServiceRequestFunc = (cancellationToken) => { var response = new AzureOperationHeaderResponse<ComputeNodeDisableSchedulingHeaders>(); Task<AzureOperationHeaderResponse<ComputeNodeDisableSchedulingHeaders>> task = Task.FromResult(response); return task; }; }); cmdlet.AdditionalBehaviors = new List<BatchClientBehavior>() { interceptor }; cmdlet.ExecuteCmdlet(); // Verify that the parameters were properly set on the outgoing request Assert.Equal(disableOption, requestDisableOption); }
/// <summary> /// Send foo-client-request-id = 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0 in the /// header of the request /// </summary> /// <param name='fooClientRequestId'> /// The fooRequestId /// </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="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task <AzureOperationHeaderResponse <HeaderCustomNamedRequestIdHeadersInner> > CustomNamedRequestIdWithHttpMessagesAsync(string fooClientRequestId, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (fooClientRequestId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "fooClientRequestId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("fooClientRequestId", fooClientRequestId); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "CustomNamedRequestId", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/customNamedRequestId").ToString(); List <string> _queryParameters = new List <string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("POST"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("foo-client-request-id", System.Guid.NewGuid().ToString()); } if (fooClientRequestId != null) { if (_httpRequest.Headers.Contains("foo-client-request-id")) { _httpRequest.Headers.Remove("foo-client-request-id"); } _httpRequest.Headers.TryAddWithoutValidation("foo-client-request-id", fooClientRequestId); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", 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 (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } 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, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationHeaderResponse <HeaderCustomNamedRequestIdHeadersInner>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("foo-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("foo-request-id").FirstOrDefault(); } try { _result.Headers = _httpResponse.GetHeadersAsJson().ToObject <HeaderCustomNamedRequestIdHeadersInner>(JsonSerializer.Create(Client.DeserializationSettings)); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the headers.", _httpResponse.GetHeadersAsJson().ToString(), ex); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return(_result); }
public void ExitConditionsAreSentToService() { BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys(); cmdlet.BatchContext = context; TaskAddParameter requestParameters = null; RequestInterceptor interceptor = new RequestInterceptor((baseRequest) => { TaskAddBatchRequest request = (TaskAddBatchRequest)baseRequest; request.ServiceRequestFunc = (cancellationToken) => { requestParameters = request.Parameters; var response = new AzureOperationHeaderResponse<TaskAddHeaders>(); Task<AzureOperationHeaderResponse<TaskAddHeaders>> task = Task.FromResult(response); return task; }; }); cmdlet.AdditionalBehaviors = new List<BatchClientBehavior> { interceptor }; var none = new PSExitOptions { omObject = new Azure.Batch.ExitOptions { JobAction = Azure.Batch.Common.JobAction.None } }; var terminate = new PSExitOptions { omObject = new Azure.Batch.ExitOptions { JobAction = Azure.Batch.Common.JobAction.Terminate } }; cmdlet.ExitConditions = new PSExitConditions { ExitCodes = new List<PSExitCodeMapping> { new PSExitCodeMapping(0, none) }, SchedulingError = terminate, ExitCodeRanges = new List<PSExitCodeRangeMapping> { new PSExitCodeRangeMapping(1, 5, terminate) }, Default = none, }; cmdlet.JobId = "job-Id"; cmdlet.Id = "task-id"; cmdlet.ExecuteCmdlet(); var exitConditions = requestParameters.ExitConditions; Assert.Equal(1, exitConditions.ExitCodeRanges.First().Start); Assert.Equal(5, exitConditions.ExitCodeRanges.First().End); Assert.Equal(ProxyModels.JobAction.Terminate, exitConditions.ExitCodeRanges.First().ExitOptions.JobAction); Assert.Equal(ProxyModels.JobAction.None, exitConditions.ExitCodes.First().ExitOptions.JobAction); Assert.Equal(ProxyModels.JobAction.Terminate, exitConditions.SchedulingError.JobAction); Assert.Equal(ProxyModels.JobAction.None, exitConditions.DefaultProperty.JobAction); }
public void ResetComputeNodeRequestTest() { BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys(); cmdlet.BatchContext = context; cmdlet.PoolId = "testPool"; cmdlet.Id = "computeNode1"; cmdlet.ReimageOption = BatchCommon.ComputeNodeReimageOption.Terminate; ComputeNodeReimageOption? requestReimageOption = null; // Don't go to the service on a Reimage ComputeNode call RequestInterceptor interceptor = new RequestInterceptor((baseRequest) => { ComputeNodeReimageBatchRequest request = (ComputeNodeReimageBatchRequest)baseRequest; request.ServiceRequestFunc = (cancellationToken) => { // Grab the reimage option from the outgoing request. requestReimageOption = request.Parameters; var response = new AzureOperationHeaderResponse<ComputeNodeReimageHeaders>(); Task<AzureOperationHeaderResponse<ComputeNodeReimageHeaders>> task = Task.FromResult(response); return task; }; }); cmdlet.AdditionalBehaviors = new List<BatchClientBehavior>() { interceptor }; cmdlet.ExecuteCmdlet(); // Verify that the reimage option was properly set on the outgoing request Assert.Equal(cmdlet.ReimageOption, BatchTestHelpers.MapEnum<BatchCommon.ComputeNodeReimageOption>(requestReimageOption)); }
private void ExitConditionsAreSentToService() { BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys(); cmdlet.BatchContext = context; TaskAddParameter requestParameters = null; RequestInterceptor interceptor = new RequestInterceptor((baseRequest) => { TaskAddBatchRequest request = (TaskAddBatchRequest)baseRequest; request.ServiceRequestFunc = (cancellationToken) => { requestParameters = request.Parameters; var response = new AzureOperationHeaderResponse <TaskAddHeaders>(); Task <AzureOperationHeaderResponse <TaskAddHeaders> > task = Task.FromResult(response); return(task); }; }); cmdlet.AdditionalBehaviors = new List <BatchClientBehavior> { interceptor }; var none = new PSExitOptions(new Azure.Batch.ExitOptions { JobAction = Azure.Batch.Common.JobAction.None }); var terminate = new PSExitOptions(new Azure.Batch.ExitOptions { JobAction = Azure.Batch.Common.JobAction.Terminate }); var satisfyDependency = new PSExitOptions(new Azure.Batch.ExitOptions { DependencyAction = Azure.Batch.Common.DependencyAction.Satisfy }); cmdlet.ExitConditions = new PSExitConditions { ExitCodes = new List <PSExitCodeMapping> { new PSExitCodeMapping(0, none) }, PreProcessingError = terminate, FileUploadError = none, ExitCodeRanges = new List <PSExitCodeRangeMapping> { new PSExitCodeRangeMapping(1, 5, satisfyDependency) }, Default = none, }; cmdlet.JobId = "job-Id"; cmdlet.Id = "task-id"; cmdlet.ExecuteCmdlet(); var exitConditions = requestParameters.ExitConditions; Assert.Equal(1, exitConditions.ExitCodeRanges.First().Start); Assert.Equal(5, exitConditions.ExitCodeRanges.First().End); Assert.Equal(ProxyModels.DependencyAction.Satisfy, exitConditions.ExitCodeRanges.First().ExitOptions.DependencyAction); Assert.Equal(ProxyModels.JobAction.None, exitConditions.ExitCodes.First().ExitOptions.JobAction); Assert.Equal(ProxyModels.JobAction.Terminate, exitConditions.PreProcessingError.JobAction); Assert.Equal(ProxyModels.JobAction.None, exitConditions.FileUploadError.JobAction); Assert.Equal(ProxyModels.JobAction.None, exitConditions.DefaultProperty.JobAction); }
/// <summary> /// Deletes the specified Batch account. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group that contains the Batch account. /// </param> /// <param name='accountName'> /// The name of the Batch account. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="HttpOperationException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task <AzureOperationHeaderResponse <RetryHeader> > BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string accountName, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._]+$")) { throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._]+$"); } } if (accountName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "accountName"); } if (accountName != null) { if (accountName.Length > 24) { throw new ValidationException(ValidationRules.MaxLength, "accountName", 24); } if (accountName.Length < 3) { throw new ValidationException(ValidationRules.MinLength, "accountName", 3); } if (!System.Text.RegularExpressions.Regex.IsMatch(accountName, "^[-\\w\\._]+$")) { throw new ValidationException(ValidationRules.Pattern, "accountName", "^[-\\w\\._]+$"); } } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("accountName", accountName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginDelete", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{accountName}", System.Uri.EscapeDataString(accountName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List <string> _queryParameters = new List <string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("DELETE"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", 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 (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 202 && (int)_statusCode != 204) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); object _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <object>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationHeaderResponse <RetryHeader>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } try { _result.Headers = _httpResponse.GetHeadersAsJson().ToObject <RetryHeader>(JsonSerializer.Create(Client.DeserializationSettings)); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the headers.", _httpResponse.GetHeadersAsJson().ToString(), ex); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return(_result); }
public void SetPoolOSVersionRequestTest() { BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys(); cmdlet.BatchContext = context; string targetOS = "targetOS"; string requestTargetOS = null; cmdlet.Id = "testPool"; cmdlet.TargetOSVersion = targetOS; // Don't go to the service on an Upgrade OS call RequestInterceptor interceptor = new RequestInterceptor((baseRequest) => { PoolUpgradeOSBatchRequest request = (PoolUpgradeOSBatchRequest)baseRequest; // Grab the target OS version off the outgoing request requestTargetOS = request.Parameters; request.ServiceRequestFunc = (cancellationToken) => { var response = new AzureOperationHeaderResponse<PoolUpgradeOSHeaders>(); Task<AzureOperationHeaderResponse<PoolUpgradeOSHeaders>> task = Task.FromResult(response); return task; }; }); cmdlet.AdditionalBehaviors = new List<BatchClientBehavior>() { interceptor }; cmdlet.ExecuteCmdlet(); // Verify that the target OS was properly set on the outgoing request Assert.Equal(targetOS, requestTargetOS); }
public void GetBatchNodeFileByTaskTest() { // Setup cmdlet to get a Task file by name BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys(); cmdlet.BatchContext = context; cmdlet.JobId = "job-1"; cmdlet.TaskId = "task"; cmdlet.Path = "stdout.txt"; cmdlet.Filter = null; // Build a NodeFile instead of querying the service on a Get NodeFile Properties call AzureOperationHeaderResponse <ProxyModels.FileGetPropertiesFromTaskHeaders> response = BatchTestHelpers.CreateNodeFileGetPropertiesByTaskResponse(); RequestInterceptor interceptor = BatchTestHelpers.CreateFakeServiceResponseInterceptor < ProxyModels.FileGetPropertiesFromTaskOptions, AzureOperationHeaderResponse <ProxyModels.FileGetPropertiesFromTaskHeaders> >(response); cmdlet.AdditionalBehaviors = new List <BatchClientBehavior>() { interceptor }; // Setup the cmdlet to write pipeline output to a list that can be examined later List <PSNodeFile> pipeline = new List <PSNodeFile>(); commandRuntimeMock.Setup(r => r.WriteObject(It.IsAny <PSNodeFile>())).Callback <object>(f => pipeline.Add((PSNodeFile)f)); cmdlet.ExecuteCmdlet(); // Verify that the cmdlet wrote the node file returned from the OM to the pipeline Assert.Single(pipeline); Assert.Equal(cmdlet.Path, pipeline[0].Path); }
public void RemoveComputeNodeRequestTest() { // Setup cmdlet to skip confirmation popup cmdlet.Force = true; commandRuntimeMock.Setup(f => f.ShouldProcess(It.IsAny<string>(), It.IsAny<string>())).Returns(true); BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys(); cmdlet.BatchContext = context; cmdlet.PoolId = "testPool"; cmdlet.Ids = new string[] { "computeNode1", "computeNode2" }; cmdlet.DeallocationOption = Microsoft.Azure.Batch.Common.ComputeNodeDeallocationOption.Terminate; cmdlet.ResizeTimeout = TimeSpan.FromMinutes(8); Microsoft.Azure.Batch.Common.ComputeNodeDeallocationOption? requestDeallocationOption = null; TimeSpan? requestResizeTimeout = null; IList<string> requestComputeNodeIds = null; // Don't go to the service on a Remove ComputeNode call RequestInterceptor interceptor = new RequestInterceptor((baseRequest) => { PoolRemoveNodesBatchRequest request = (PoolRemoveNodesBatchRequest)baseRequest; request.ServiceRequestFunc = (cancellationToken) => { // Grab the parameters from the outgoing request. requestDeallocationOption = BatchTestHelpers.MapEnum<Microsoft.Azure.Batch.Common.ComputeNodeDeallocationOption>(request.Parameters.NodeDeallocationOption); requestResizeTimeout = request.Parameters.ResizeTimeout; requestComputeNodeIds = request.Parameters.NodeList; var response = new AzureOperationHeaderResponse<PoolRemoveNodesHeaders>(); Task<AzureOperationHeaderResponse<PoolRemoveNodesHeaders>> task = Task.FromResult(response); return task; }; }); cmdlet.AdditionalBehaviors = new List<BatchClientBehavior>() { interceptor }; cmdlet.ExecuteCmdlet(); // Verify that the parameters were properly set on the outgoing request Assert.Equal(cmdlet.DeallocationOption, requestDeallocationOption); Assert.Equal(cmdlet.ResizeTimeout, requestResizeTimeout); Assert.Equal(cmdlet.Ids.Length, requestComputeNodeIds.Count); foreach (string id in cmdlet.Ids) { Assert.True(requestComputeNodeIds.Contains(id)); } }
public void NewBatchCertificateRequestBodyTest() { BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys(); cmdlet.BatchContext = context; X509Certificate2 cert = new X509Certificate2(BatchTestHelpers.TestCertificateFileName); string certDataBase64String = Convert.ToBase64String(cert.RawData); CertificateAddParameter requestParameters = null; // Don't go to the service on an Add Certificate call RequestInterceptor interceptor = new RequestInterceptor((baseRequest) => { CertificateAddBatchRequest request = (CertificateAddBatchRequest)baseRequest; request.ServiceRequestFunc = (cancellationToken) => { requestParameters = request.Parameters; var response = new AzureOperationHeaderResponse <CertificateAddHeaders>(); Task <AzureOperationHeaderResponse <CertificateAddHeaders> > task = Task.FromResult(response); return(task); }; }); cmdlet.AdditionalBehaviors = new List <BatchClientBehavior>() { interceptor }; // Verify that when just the raw data is specified, the request body matches expectations cmdlet.RawData = cert.RawData; cmdlet.ExecuteCmdlet(); Assert.Equal(CertificateFormat.Cer, requestParameters.CertificateFormat); Assert.Equal(BatchTestHelpers.TestCertificateAlgorithm, requestParameters.ThumbprintAlgorithm); Assert.Equal(cert.Thumbprint.ToLowerInvariant(), requestParameters.Thumbprint.ToLowerInvariant()); Assert.True(string.IsNullOrEmpty(requestParameters.Password)); Assert.Equal(certDataBase64String, requestParameters.Data); // Verify that when the raw data is specified with a password, the request body matches expectations cmdlet.RawData = cert.RawData; cmdlet.Password = BatchTestHelpers.TestCertificatePassword; cmdlet.ExecuteCmdlet(); Assert.Equal(CertificateFormat.Pfx, requestParameters.CertificateFormat); Assert.Equal(BatchTestHelpers.TestCertificateAlgorithm, requestParameters.ThumbprintAlgorithm); Assert.Equal(cert.Thumbprint.ToLowerInvariant(), requestParameters.Thumbprint.ToLowerInvariant()); Assert.Equal(BatchTestHelpers.TestCertificatePassword, requestParameters.Password); Assert.Equal(certDataBase64String, requestParameters.Data); // Verify that when just a file path is specified, the request body matches expectations cmdlet.RawData = null; cmdlet.Password = null; cmdlet.FilePath = BatchTestHelpers.TestCertificateFileName; cmdlet.ExecuteCmdlet(); Assert.Equal(CertificateFormat.Cer, requestParameters.CertificateFormat); Assert.Equal(BatchTestHelpers.TestCertificateAlgorithm, requestParameters.ThumbprintAlgorithm); Assert.Equal(cert.Thumbprint.ToLowerInvariant(), requestParameters.Thumbprint.ToLowerInvariant()); Assert.True(string.IsNullOrEmpty(requestParameters.Password)); Assert.Equal(certDataBase64String, requestParameters.Data); // Verify that when a file path is specified with a password, the request body matches expectations cmdlet.Password = BatchTestHelpers.TestCertificatePassword; cmdlet.ExecuteCmdlet(); Assert.Equal(CertificateFormat.Pfx, requestParameters.CertificateFormat); Assert.Equal(BatchTestHelpers.TestCertificateAlgorithm, requestParameters.ThumbprintAlgorithm); Assert.Equal(cert.Thumbprint.ToLowerInvariant(), requestParameters.Thumbprint.ToLowerInvariant()); Assert.Equal(BatchTestHelpers.TestCertificatePassword, requestParameters.Password); Assert.Equal(certDataBase64String, requestParameters.Data); }
/// <summary> /// x-ms-client-request-id = 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0 is required /// message header for all requests. Long running post request, service /// returns a 202 to the initial request, with an entity that contains /// ProvisioningState=’Creating’. Poll the endpoint indicated in the /// Azure-AsyncOperation header for operation status /// </summary> /// <param name='product'> /// Product to put /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task <AzureOperationHeaderResponse <LROsCustomHeaderPostAsyncRetrySucceededHeaders> > BeginPostAsyncRetrySucceededWithHttpMessagesAsync(Product product = default(Product), Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("product", product); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginPostAsyncRetrySucceeded", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "lro/customheader/postasync/retry/succeeded").ToString(); List <string> _queryParameters = new List <string>(); if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("POST"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", 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 (product != null) { _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); _httpRequest.Content.Headers.ContentType = 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) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 202) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = SafeJsonConvert.DeserializeObject <CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationHeaderResponse <LROsCustomHeaderPostAsyncRetrySucceededHeaders>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } try { _result.Headers = _httpResponse.GetHeadersAsJson().ToObject <LROsCustomHeaderPostAsyncRetrySucceededHeaders>(JsonSerializer.Create(this.Client.DeserializationSettings)); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the headers.", _httpResponse.GetHeadersAsJson().ToString(), ex); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return(_result); }
public void NewBatchCertificateRequestBodyTest() { BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys(); cmdlet.BatchContext = context; X509Certificate2 cert = new X509Certificate2(BatchTestHelpers.TestCertificateFileName); string certDataBase64String = Convert.ToBase64String(cert.RawData); CertificateAddParameter requestParameters = null; // Don't go to the service on an Add Certificate call RequestInterceptor interceptor = new RequestInterceptor((baseRequest) => { CertificateAddBatchRequest request = (CertificateAddBatchRequest)baseRequest; request.ServiceRequestFunc = (cancellationToken) => { requestParameters = request.Parameters; var response = new AzureOperationHeaderResponse<CertificateAddHeaders>(); Task<AzureOperationHeaderResponse<CertificateAddHeaders>> task = Task.FromResult(response); return task; }; }); cmdlet.AdditionalBehaviors = new List<BatchClientBehavior>() { interceptor }; // Verify that when just the raw data is specified, the request body matches expectations cmdlet.RawData = cert.RawData; cmdlet.ExecuteCmdlet(); Assert.Equal(CertificateFormat.Cer, requestParameters.CertificateFormat); Assert.Equal(BatchTestHelpers.TestCertificateAlgorithm, requestParameters.ThumbprintAlgorithm); Assert.Equal(cert.Thumbprint.ToLowerInvariant(), requestParameters.Thumbprint.ToLowerInvariant()); Assert.True(string.IsNullOrEmpty(requestParameters.Password)); Assert.Equal(certDataBase64String, requestParameters.Data); // Verify that when the raw data is specified with a password, the request body matches expectations cmdlet.RawData = cert.RawData; cmdlet.Password = BatchTestHelpers.TestCertificatePassword; cmdlet.ExecuteCmdlet(); Assert.Equal(CertificateFormat.Pfx, requestParameters.CertificateFormat); Assert.Equal(BatchTestHelpers.TestCertificateAlgorithm, requestParameters.ThumbprintAlgorithm); Assert.Equal(cert.Thumbprint.ToLowerInvariant(), requestParameters.Thumbprint.ToLowerInvariant()); Assert.Equal(BatchTestHelpers.TestCertificatePassword, requestParameters.Password); Assert.Equal(certDataBase64String, requestParameters.Data); // Verify that when just a file path is specified, the request body matches expectations cmdlet.RawData = null; cmdlet.Password = null; cmdlet.FilePath = BatchTestHelpers.TestCertificateFileName; cmdlet.ExecuteCmdlet(); Assert.Equal(CertificateFormat.Cer, requestParameters.CertificateFormat); Assert.Equal(BatchTestHelpers.TestCertificateAlgorithm, requestParameters.ThumbprintAlgorithm); Assert.Equal(cert.Thumbprint.ToLowerInvariant(), requestParameters.Thumbprint.ToLowerInvariant()); Assert.True(string.IsNullOrEmpty(requestParameters.Password)); Assert.Equal(certDataBase64String, requestParameters.Data); // Verify that when a file path is specified with a password, the request body matches expectations cmdlet.Password = BatchTestHelpers.TestCertificatePassword; cmdlet.ExecuteCmdlet(); Assert.Equal(CertificateFormat.Pfx, requestParameters.CertificateFormat); Assert.Equal(BatchTestHelpers.TestCertificateAlgorithm, requestParameters.ThumbprintAlgorithm); Assert.Equal(cert.Thumbprint.ToLowerInvariant(), requestParameters.Thumbprint.ToLowerInvariant()); Assert.Equal(BatchTestHelpers.TestCertificatePassword, requestParameters.Password); Assert.Equal(certDataBase64String, requestParameters.Data); }