/// <summary>
 /// Invoke a command on the website's VM.
 /// </summary>
 /// <param name='operations'>
 /// Reference to the
 /// Microsoft.WindowsAzure.WebSitesExtensions.ICommandsOperations.
 /// </param>
 /// <param name='parameters'>
 /// Required. The invoke command parameters.
 /// </param>
 /// <returns>
 /// The invoke command operation response.
 /// </returns>
 public static InvokeCommandResponse Invoke(this ICommandsOperations operations, InvokeCommandParameters parameters)
 {
     return(Task.Factory.StartNew((object s) =>
     {
         return ((ICommandsOperations)s).InvokeAsync(parameters);
     }
                                  , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult());
 }
 /// <summary>
 /// Invoke a command on the website's VM.
 /// </summary>
 /// <param name='operations'>
 /// Reference to the
 /// Microsoft.WindowsAzure.WebSitesExtensions.ICommandsOperations.
 /// </param>
 /// <param name='parameters'>
 /// Required. The invoke command parameters.
 /// </param>
 /// <returns>
 /// The invoke command operation response.
 /// </returns>
 public static Task <InvokeCommandResponse> InvokeAsync(this ICommandsOperations operations, InvokeCommandParameters parameters)
 {
     return(operations.InvokeAsync(parameters, CancellationToken.None));
 }
        /// <summary>
        /// Invoke a command on the website's VM.
        /// </summary>
        /// <param name='parameters'>
        /// Required. The invoke command parameters.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// The invoke command operation response.
        /// </returns>
        public async Task <InvokeCommandResponse> InvokeAsync(InvokeCommandParameters parameters, CancellationToken cancellationToken)
        {
            // Validate
            if (parameters == null)
            {
                throw new ArgumentNullException("parameters");
            }

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

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

            // Construct URL
            string url = "";

            url = url + "/api/command";
            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.Post;
                httpRequest.RequestUri = new Uri(url);

                // Set Headers

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

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

                JObject invokeCommandParametersValue = new JObject();
                requestDoc = invokeCommandParametersValue;

                if (parameters.Command != null)
                {
                    invokeCommandParametersValue["command"] = parameters.Command;
                }

                if (parameters.Directory != null)
                {
                    invokeCommandParametersValue["dir"] = parameters.Directory;
                }

                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.OK)
                    {
                        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
                    InvokeCommandResponse result = null;
                    // Deserialize Response
                    if (statusCode == HttpStatusCode.OK)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

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

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

                            JToken outputValue = responseDoc["Output"];
                            if (outputValue != null && outputValue.Type != JTokenType.Null)
                            {
                                string outputInstance = ((string)outputValue);
                                commandResultInstance.Output = outputInstance;
                            }

                            JToken errorValue = responseDoc["Error"];
                            if (errorValue != null && errorValue.Type != JTokenType.Null)
                            {
                                string errorInstance = ((string)errorValue);
                                commandResultInstance.Error = errorInstance;
                            }

                            JToken exitCodeValue = responseDoc["ExitCode"];
                            if (exitCodeValue != null && exitCodeValue.Type != JTokenType.Null)
                            {
                                int exitCodeInstance = ((int)exitCodeValue);
                                commandResultInstance.ExitCode = exitCodeInstance;
                            }
                        }
                    }
                    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();
                }
            }
        }