private async Task <TestJobCreateResponse> createTestJob()
        {
            RunbookDraft draft = await AutomationRunbookManager.GetRunbookDraft(runbookName, iseClient.automationManagementClient,
                                                                                iseClient.accountResourceGroups[iseClient.currAccount].Name, iseClient.currAccount.Name);

            if (draft.InEdit == false)
            {
                throw new Exception("This runbook has no draft to test because it is in a 'Published' state.");
            }

            HybridRunbookWorkerGroupsListResponse hybridGroupResponse = await iseClient.automationManagementClient.HybridRunbookWorkerGroups.ListAsync(
                iseClient.accountResourceGroups[iseClient.currAccount].Name, iseClient.currAccount.Name,
                new CancellationToken());

            TestJobCreateParameters jobCreationParams = new TestJobCreateParameters();

            jobCreationParams.RunbookName = runbookName;
            if (draft.Parameters.Count > 0 || hybridGroupResponse.HybridRunbookWorkerGroups.Count > 0)
            {
                /* User needs to specify some things */
                var existingParams = await GetLastTestJobParams();

                RunbookParamDialog paramDialog = new RunbookParamDialog(draft.Parameters, existingParams, hybridGroupResponse.HybridRunbookWorkerGroups);
                if (paramDialog.ShowDialog() == true)
                {
                    if (draft.Parameters.Count > 0)
                    {
                        jobCreationParams.Parameters = paramDialog.paramValues;
                    }
                    if (!String.IsNullOrEmpty(paramDialog.runOnSelection) && !paramDialog.runOnSelection.Equals("Azure"))
                    {
                        jobCreationParams.RunOn = paramDialog.runOnSelection;
                    }
                }
                else
                {
                    return(null);
                }
            }
            /* start the test job */
            CancellationTokenSource cts = new CancellationTokenSource();

            cts.CancelAfter(TIMEOUT_MS);
            TestJobCreateResponse jobResponse = await iseClient.automationManagementClient.TestJobs.CreateAsync(
                iseClient.accountResourceGroups[iseClient.currAccount].Name,
                iseClient.currAccount.Name, jobCreationParams, cts.Token);

            if (jobResponse == null || jobResponse.StatusCode != System.Net.HttpStatusCode.Created)
            {
                throw new Exception("The test job could not be created: received HTTP status code " + jobResponse.StatusCode);
            }
            return(jobResponse);
        }
Esempio n. 2
0
        private async Task <TestJobCreateResponse> createTestJob()
        {
            RunbookDraft draft = await AutomationRunbookManager.GetRunbookDraft(runbookName, iseClient.automationManagementClient,
                                                                                iseClient.accountResourceGroups[iseClient.currAccount].Name, iseClient.currAccount.Name);

            if (draft.InEdit == false)
            {
                throw new Exception("This runbook has no draft to test because it is in a 'Published' state.");
            }
            TestJobCreateParameters jobCreationParams = new TestJobCreateParameters();

            jobCreationParams.RunbookName = runbookName;
            if (draft.Parameters.Count > 0)
            {
                /* User needs to specify values for them */
                var existingParams = await GetTestJobParams();

                RunbookParamDialog paramDialog = new RunbookParamDialog(draft.Parameters, existingParams);
                if (paramDialog.ShowDialog() == true)
                {
                    jobCreationParams.Parameters = paramDialog.paramValues;
                }
                else
                {
                    return(null);
                }
            }
            /* start the test job */
            TestJobCreateResponse jobResponse = await iseClient.automationManagementClient.TestJobs.CreateAsync(
                iseClient.accountResourceGroups[iseClient.currAccount].Name,
                iseClient.currAccount.Name, jobCreationParams, new System.Threading.CancellationToken());

            if (jobResponse == null || jobResponse.StatusCode != System.Net.HttpStatusCode.Created)
            {
                throw new Exception("The test job could not be created: received HTTP status code " + jobResponse.StatusCode);
            }
            return(jobResponse);
        }
Esempio n. 3
0
        /// <summary>
        /// Create a test job of the runbook.  (see
        /// http://aka.ms/azureautomationsdk/testjoboperations for more
        /// information)
        /// </summary>
        /// <param name='resourceGroupName'>
        /// Required. The name of the resource group
        /// </param>
        /// <param name='automationAccount'>
        /// Required. The automation account name.
        /// </param>
        /// <param name='parameters'>
        /// Required. The parameters supplied to the create test job operation.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// The response model for the create test job operation.
        /// </returns>
        public async Task <TestJobCreateResponse> CreateAsync(string resourceGroupName, string automationAccount, TestJobCreateParameters parameters, CancellationToken cancellationToken)
        {
            // Validate
            if (resourceGroupName == null)
            {
                throw new ArgumentNullException("resourceGroupName");
            }
            if (automationAccount == null)
            {
                throw new ArgumentNullException("automationAccount");
            }
            if (parameters == null)
            {
                throw new ArgumentNullException("parameters");
            }
            if (parameters.RunbookName == null)
            {
                throw new ArgumentNullException("parameters.RunbookName");
            }

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

            if (shouldTrace)
            {
                invocationId = TracingAdapter.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("resourceGroupName", resourceGroupName);
                tracingParameters.Add("automationAccount", automationAccount);
                tracingParameters.Add("parameters", parameters);
                TracingAdapter.Enter(invocationId, this, "CreateAsync", tracingParameters);
            }

            // Construct URL
            string url = "";

            url = url + "/subscriptions/";
            if (this.Client.Credentials.SubscriptionId != null)
            {
                url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
            }
            url = url + "/resourceGroups/";
            url = url + Uri.EscapeDataString(resourceGroupName);
            url = url + "/providers/";
            if (this.Client.ResourceNamespace != null)
            {
                url = url + Uri.EscapeDataString(this.Client.ResourceNamespace);
            }
            url = url + "/automationAccounts/";
            url = url + Uri.EscapeDataString(automationAccount);
            url = url + "/runbooks/";
            url = url + Uri.EscapeDataString(parameters.RunbookName);
            url = url + "/draft/testJob";
            List <string> queryParameters = new List <string>();

            queryParameters.Add("api-version=2017-05-15-preview");
            if (queryParameters.Count > 0)
            {
                url = url + "?" + string.Join("&", queryParameters);
            }
            string baseUrl = this.Client.BaseUri.AbsoluteUri;

            // Trim '/' character from the end of baseUrl and beginning of url.
            if (baseUrl[baseUrl.Length - 1] == '/')
            {
                baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
            }
            if (url[0] == '/')
            {
                url = url.Substring(1);
            }
            url = baseUrl + "/" + url;
            url = url.Replace(" ", "%20");

            // Create HTTP transport objects
            HttpRequestMessage httpRequest = null;

            try
            {
                httpRequest            = new HttpRequestMessage();
                httpRequest.Method     = HttpMethod.Put;
                httpRequest.RequestUri = new Uri(url);

                // Set Headers
                httpRequest.Headers.Add("Accept", "application/json");
                httpRequest.Headers.Add("x-ms-version", "2014-06-01");

                // Set Credentials
                cancellationToken.ThrowIfCancellationRequested();
                await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);

                // Serialize Request
                string requestContent = null;
                JToken requestDoc     = null;

                JObject testJobCreateParametersValue = new JObject();
                requestDoc = testJobCreateParametersValue;

                if (parameters.Parameters != null)
                {
                    if (parameters.Parameters is ILazyCollection == false || ((ILazyCollection)parameters.Parameters).IsInitialized)
                    {
                        JObject parametersDictionary = new JObject();
                        foreach (KeyValuePair <string, string> pair in parameters.Parameters)
                        {
                            string parametersKey   = pair.Key;
                            string parametersValue = pair.Value;
                            parametersDictionary[parametersKey] = parametersValue;
                        }
                        testJobCreateParametersValue["parameters"] = parametersDictionary;
                    }
                }

                if (parameters.RunOn != null)
                {
                    testJobCreateParametersValue["runOn"] = parameters.RunOn;
                }

                requestContent      = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented);
                httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
                httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");

                // Send Request
                HttpResponseMessage httpResponse = null;
                try
                {
                    if (shouldTrace)
                    {
                        TracingAdapter.SendRequest(invocationId, httpRequest);
                    }
                    cancellationToken.ThrowIfCancellationRequested();
                    httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);

                    if (shouldTrace)
                    {
                        TracingAdapter.ReceiveResponse(invocationId, httpResponse);
                    }
                    HttpStatusCode statusCode = httpResponse.StatusCode;
                    if (statusCode != HttpStatusCode.Created)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
                        if (shouldTrace)
                        {
                            TracingAdapter.Error(invocationId, ex);
                        }
                        throw ex;
                    }

                    // Create Result
                    TestJobCreateResponse result = null;
                    // Deserialize Response
                    if (statusCode == HttpStatusCode.Created)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

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

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

                            JToken creationTimeValue = responseDoc["creationTime"];
                            if (creationTimeValue != null && creationTimeValue.Type != JTokenType.Null)
                            {
                                DateTimeOffset creationTimeInstance = ((DateTimeOffset)creationTimeValue);
                                testJobInstance.CreationTime = creationTimeInstance;
                            }

                            JToken statusValue = responseDoc["status"];
                            if (statusValue != null && statusValue.Type != JTokenType.Null)
                            {
                                string statusInstance = ((string)statusValue);
                                testJobInstance.Status = statusInstance;
                            }

                            JToken statusDetailsValue = responseDoc["statusDetails"];
                            if (statusDetailsValue != null && statusDetailsValue.Type != JTokenType.Null)
                            {
                                string statusDetailsInstance = ((string)statusDetailsValue);
                                testJobInstance.StatusDetails = statusDetailsInstance;
                            }

                            JToken runOnValue = responseDoc["runOn"];
                            if (runOnValue != null && runOnValue.Type != JTokenType.Null)
                            {
                                string runOnInstance = ((string)runOnValue);
                                testJobInstance.RunOn = runOnInstance;
                            }

                            JToken startTimeValue = responseDoc["startTime"];
                            if (startTimeValue != null && startTimeValue.Type != JTokenType.Null)
                            {
                                DateTimeOffset startTimeInstance = ((DateTimeOffset)startTimeValue);
                                testJobInstance.StartTime = startTimeInstance;
                            }

                            JToken endTimeValue = responseDoc["endTime"];
                            if (endTimeValue != null && endTimeValue.Type != JTokenType.Null)
                            {
                                DateTimeOffset endTimeInstance = ((DateTimeOffset)endTimeValue);
                                testJobInstance.EndTime = endTimeInstance;
                            }

                            JToken exceptionValue = responseDoc["exception"];
                            if (exceptionValue != null && exceptionValue.Type != JTokenType.Null)
                            {
                                string exceptionInstance = ((string)exceptionValue);
                                testJobInstance.Exception = exceptionInstance;
                            }

                            JToken lastModifiedTimeValue = responseDoc["lastModifiedTime"];
                            if (lastModifiedTimeValue != null && lastModifiedTimeValue.Type != JTokenType.Null)
                            {
                                DateTimeOffset lastModifiedTimeInstance = ((DateTimeOffset)lastModifiedTimeValue);
                                testJobInstance.LastModifiedTime = lastModifiedTimeInstance;
                            }

                            JToken lastStatusModifiedTimeValue = responseDoc["lastStatusModifiedTime"];
                            if (lastStatusModifiedTimeValue != null && lastStatusModifiedTimeValue.Type != JTokenType.Null)
                            {
                                DateTimeOffset lastStatusModifiedTimeInstance = ((DateTimeOffset)lastStatusModifiedTimeValue);
                                testJobInstance.LastStatusModifiedTime = lastStatusModifiedTimeInstance;
                            }

                            JToken parametersSequenceElement = ((JToken)responseDoc["parameters"]);
                            if (parametersSequenceElement != null && parametersSequenceElement.Type != JTokenType.Null)
                            {
                                foreach (JProperty property in parametersSequenceElement)
                                {
                                    string parametersKey2   = ((string)property.Name);
                                    string parametersValue2 = ((string)property.Value);
                                    testJobInstance.Parameters.Add(parametersKey2, parametersValue2);
                                }
                            }
                        }
                    }
                    result.StatusCode = statusCode;
                    if (httpResponse.Headers.Contains("x-ms-request-id"))
                    {
                        result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
                    }

                    if (shouldTrace)
                    {
                        TracingAdapter.Exit(invocationId, result);
                    }
                    return(result);
                }
                finally
                {
                    if (httpResponse != null)
                    {
                        httpResponse.Dispose();
                    }
                }
            }
            finally
            {
                if (httpRequest != null)
                {
                    httpRequest.Dispose();
                }
            }
        }
 /// <summary>
 /// Create a test job of the runbook.  (see
 /// http://aka.ms/azureautomationsdk/testjoboperations for more
 /// information)
 /// </summary>
 /// <param name='operations'>
 /// Reference to the
 /// Microsoft.Azure.Management.Automation.ITestJobOperations.
 /// </param>
 /// <param name='resourceGroupName'>
 /// Required. The name of the resource group
 /// </param>
 /// <param name='automationAccount'>
 /// Required. The automation account name.
 /// </param>
 /// <param name='parameters'>
 /// Required. The parameters supplied to the create test job operation.
 /// </param>
 /// <returns>
 /// The response model for the create test job operation.
 /// </returns>
 public static Task <TestJobCreateResponse> CreateAsync(this ITestJobOperations operations, string resourceGroupName, string automationAccount, TestJobCreateParameters parameters)
 {
     return(operations.CreateAsync(resourceGroupName, automationAccount, parameters, CancellationToken.None));
 }
 /// <summary>
 /// Create a test job of the runbook.  (see
 /// http://aka.ms/azureautomationsdk/testjoboperations for more
 /// information)
 /// </summary>
 /// <param name='operations'>
 /// Reference to the
 /// Microsoft.Azure.Management.Automation.ITestJobOperations.
 /// </param>
 /// <param name='resourceGroupName'>
 /// Required. The name of the resource group
 /// </param>
 /// <param name='automationAccount'>
 /// Required. The automation account name.
 /// </param>
 /// <param name='parameters'>
 /// Required. The parameters supplied to the create test job operation.
 /// </param>
 /// <returns>
 /// The response model for the create test job operation.
 /// </returns>
 public static TestJobCreateResponse Create(this ITestJobOperations operations, string resourceGroupName, string automationAccount, TestJobCreateParameters parameters)
 {
     return(Task.Factory.StartNew((object s) =>
     {
         return ((ITestJobOperations)s).CreateAsync(resourceGroupName, automationAccount, parameters);
     }
                                  , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult());
 }
        /// <summary>
        /// Create a test job of the runbook.
        /// <see href="http://aka.ms/azureautomationsdk/testjoboperations" />
        /// </summary>
        /// <param name='resourceGroupName'>
        /// Name of an Azure Resource group.
        /// </param>
        /// <param name='automationAccountName'>
        /// The name of the automation account.
        /// </param>
        /// <param name='runbookName'>
        /// The parameters supplied to the create test job operation.
        /// </param>
        /// <param name='parameters'>
        /// The parameters supplied to the create test job operation.
        /// </param>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="ErrorResponseException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="SerializationException">
        /// Thrown when unable to deserialize the response
        /// </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 <AzureOperationResponse <TestJob> > CreateWithHttpMessagesAsync(string resourceGroupName, string automationAccountName, string runbookName, TestJobCreateParameters parameters, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (Client.SubscriptionId == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
            }
            if (resourceGroupName == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
            }
            if (resourceGroupName != null)
            {
                if (resourceGroupName.Length > 90)
                {
                    throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90);
                }
                if (resourceGroupName.Length < 1)
                {
                    throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1);
                }
                if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._]+$"))
                {
                    throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._]+$");
                }
            }
            if (automationAccountName == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "automationAccountName");
            }
            if (runbookName == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "runbookName");
            }
            if (parameters == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "parameters");
            }
            string apiVersion = "2018-06-30";
            // 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("automationAccountName", automationAccountName);
                tracingParameters.Add("runbookName", runbookName);
                tracingParameters.Add("parameters", parameters);
                tracingParameters.Add("apiVersion", apiVersion);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "Create", 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.Automation/automationAccounts/{automationAccountName}/runbooks/{runbookName}/draft/testJob").ToString();

            _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
            _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
            _url = _url.Replace("{automationAccountName}", System.Uri.EscapeDataString(automationAccountName));
            _url = _url.Replace("{runbookName}", System.Uri.EscapeDataString(runbookName));
            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("PUT");
            _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 (parameters != null)
            {
                _requestContent      = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, 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);
            }
            System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
            cancellationToken.ThrowIfCancellationRequested();
            string _responseContent = null;

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

                    ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject <ErrorResponse>(_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 AzureOperationResponse <TestJob>();

            _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 == 201)
            {
                _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                try
                {
                    _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject <TestJob>(_responseContent, Client.DeserializationSettings);
                }
                catch (JsonException ex)
                {
                    _httpRequest.Dispose();
                    if (_httpResponse != null)
                    {
                        _httpResponse.Dispose();
                    }
                    throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
                }
            }
            if (_shouldTrace)
            {
                ServiceClientTracing.Exit(_invocationId, _result);
            }
            return(_result);
        }
 /// <summary>
 /// Create a test job of the runbook.
 /// <see href="http://aka.ms/azureautomationsdk/testjoboperations" />
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='resourceGroupName'>
 /// Name of an Azure Resource group.
 /// </param>
 /// <param name='automationAccountName'>
 /// The name of the automation account.
 /// </param>
 /// <param name='runbookName'>
 /// The parameters supplied to the create test job operation.
 /// </param>
 /// <param name='parameters'>
 /// The parameters supplied to the create test job operation.
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async Task <TestJob> CreateAsync(this ITestJobOperations operations, string resourceGroupName, string automationAccountName, string runbookName, TestJobCreateParameters parameters, CancellationToken cancellationToken = default(CancellationToken))
 {
     using (var _result = await operations.CreateWithHttpMessagesAsync(resourceGroupName, automationAccountName, runbookName, parameters, null, cancellationToken).ConfigureAwait(false))
     {
         return(_result.Body);
     }
 }
 /// <summary>
 /// Create a test job of the runbook.
 /// <see href="http://aka.ms/azureautomationsdk/testjoboperations" />
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='resourceGroupName'>
 /// Name of an Azure Resource group.
 /// </param>
 /// <param name='automationAccountName'>
 /// The name of the automation account.
 /// </param>
 /// <param name='runbookName'>
 /// The parameters supplied to the create test job operation.
 /// </param>
 /// <param name='parameters'>
 /// The parameters supplied to the create test job operation.
 /// </param>
 public static TestJob Create(this ITestJobOperations operations, string resourceGroupName, string automationAccountName, string runbookName, TestJobCreateParameters parameters)
 {
     return(operations.CreateAsync(resourceGroupName, automationAccountName, runbookName, parameters).GetAwaiter().GetResult());
 }