text:
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
using Hyak.Common;
using Hyak.Common.Internals;
using Microsoft.Azure;
using Microsoft.Azure.Management.Resources;
using Microsoft.Azure.Management.Resources.Models;
using Newtonsoft.Json.Linq;

namespace Microsoft.Azure.Management.Resources
{
    /// <summary>
    /// Operations for managing deployments.
    /// </summary>
    internal partial class DeploymentOperations : IServiceOperations<ResourceManagementClient>, IDeploymentOperations
    {
        /// <summary>
        /// Initializes a new instance of the DeploymentOperations class.
        /// </summary>
        /// <param name='client'>
        /// Reference to the service client.
        /// </param>
        internal DeploymentOperations(ResourceManagementClient client)
        {
            this._client = client;
        }

        private ResourceManagementClient _client;

        /// <summary>
        /// Gets a reference to the
        /// Microsoft.Azure.Management.Resources.ResourceManagementClient.
        /// </summary>
        public ResourceManagementClient Client
        {
            get { return this._client; }
        }

        /// <summary>
        /// Begin deleting deployment.To determine whether the operation has
        /// finished processing the request, call
        /// GetLongRunningOperationStatus.
        /// </summary>
        /// <param name='resourceGroupName'>
        /// Required. The name of the resource group. The name is case
        /// insensitive.
        /// </param>
        /// <param name='deploymentName'>
        /// Required. The name of the deployment to be deleted.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// A standard service response for long running operations.
        /// </returns>
        public async Task<LongRunningOperationResponse> BeginDeletingAsync(string resourceGroupName, string deploymentName, CancellationToken cancellationToken)
        {
            // Validate
            if (resourceGroupName == null)
            {
                throw new ArgumentNullException("resourceGroupName");
            }
            if (resourceGroupName != null && resourceGroupName.Length > 1000)
            {
                throw new ArgumentOutOfRangeException("resourceGroupName");
            }
            if (Regex.IsMatch(resourceGroupName, "^[-\\w\\._]+$") == false)
            {
                throw new ArgumentOutOfRangeException("resourceGroupName");
            }
            if (deploymentName == null)
            {
                throw new ArgumentNullException("deploymentName");
            }

            // 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("deploymentName", deploymentName);
                TracingAdapter.Enter(invocationId, this, "BeginDeletingAsync", 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 + "/deployments/";
            url = url + Uri.EscapeDataString(deploymentName);
            List<string> queryParameters = new List<string>();
            queryParameters.Add("api-version=2016-02-01");
            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.Delete;
                httpRequest.RequestUri = new Uri(url);

                // Set Headers

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

                // 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.Accepted && statusCode != HttpStatusCode.NoContent)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
                        if (shouldTrace)
                        {
                            TracingAdapter.Error(invocationId, ex);
                        }
                        throw ex;
                    }

                    // Create Result
                    LongRunningOperationResponse result = null;
                    // Deserialize Response
                    result = new LongRunningOperationResponse();
                    result.StatusCode = statusCode;
                    if (httpResponse.Headers.Contains("Location"))
                    {
                        result.OperationStatusLink = httpResponse.Headers.GetValues("Location").FirstOrDefault();
                    }
                    if (httpResponse.Headers.Contains("Retry-After"))
                    {
                        result.RetryAfter = int.Parse(httpResponse.Headers.GetValues("Retry-After").FirstOrDefault(), CultureInfo.InvariantCulture);
                    }
                    if (httpResponse.Headers.Contains("x-ms-request-id"))
                    {
                        result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
                    }
                    if (statusCode == HttpStatusCode.Conflict)
                    {
                        result.Status = OperationStatus.Failed;
                    }
                    if (statusCode == HttpStatusCode.Accepted)
                    {
                        result.Status = OperationStatus.InProgress;
                    }
                    if (statusCode == HttpStatusCode.NoContent)
                    {
                        result.Status = OperationStatus.Succeeded;
                    }

                    if (shouldTrace)
                    {
                        TracingAdapter.Exit(invocationId, result);
                    }
                    return result;
                }
                finally
                {
                    if (httpResponse != null)
                    {
                        httpResponse.Dispose();
                    }
                }
            }
            finally
            {
                if (httpRequest != null)
                {
                    httpRequest.Dispose();
                }
            }
        }

        /// <summary>
        /// Cancel a currently running template deployment.
        /// </summary>
        /// <param name='resourceGroupName'>
        /// Required. The name of the resource group. The name is case
        /// insensitive.
        /// </param>
        /// <param name='deploymentName'>
        /// Required. The name of the deployment.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// A standard service response including an HTTP status code and
        /// request ID.
        /// </returns>
        public async Task<AzureOperationResponse> CancelAsync(string resourceGroupName, string deploymentName, CancellationToken cancellationToken)
        {
            // Validate
            if (resourceGroupName == null)
            {
                throw new ArgumentNullException("resourceGroupName");
            }
            if (resourceGroupName != null && resourceGroupName.Length > 1000)
            {
                throw new ArgumentOutOfRangeException("resourceGroupName");
            }
            if (Regex.IsMatch(resourceGroupName, "^[-\\w\\._]+$") == false)
            {
                throw new ArgumentOutOfRangeException("resourceGroupName");
            }
            if (deploymentName == null)
            {
                throw new ArgumentNullException("deploymentName");
            }

            // 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("deploymentName", deploymentName);
                TracingAdapter.Enter(invocationId, this, "CancelAsync", 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 + "/deployments/";
            url = url + Uri.EscapeDataString(deploymentName);
            url = url + "/cancel";
            List<string> queryParameters = new List<string>();
            queryParameters.Add("api-version=2016-02-01");
            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.Post;
                httpRequest.RequestUri = new Uri(url);

                // Set Headers

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

                // 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.NoContent)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
                        if (shouldTrace)
                        {
                            TracingAdapter.Error(invocationId, ex);
                        }
                        throw ex;
                    }

                    // Create Result
                    AzureOperationResponse result = null;
                    // Deserialize Response
                    result = new AzureOperationResponse();
                    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>
        /// Checks whether deployment exists.
        /// </summary>
        /// <param name='resourceGroupName'>
        /// Required. The name of the resource group to check. The name is case
        /// insensitive.
        /// </param>
        /// <param name='deploymentName'>
        /// Required. The name of the deployment.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// Deployment information.
        /// </returns>
        public async Task<DeploymentExistsResult> CheckExistenceAsync(string resourceGroupName, string deploymentName, CancellationToken cancellationToken)
        {
            // Validate
            if (resourceGroupName == null)
            {
                throw new ArgumentNullException("resourceGroupName");
            }
            if (resourceGroupName != null && resourceGroupName.Length > 1000)
            {
                throw new ArgumentOutOfRangeException("resourceGroupName");
            }
            if (Regex.IsMatch(resourceGroupName, "^[-\\w\\._]+$") == false)
            {
                throw new ArgumentOutOfRangeException("resourceGroupName");
            }
            if (deploymentName == null)
            {
                throw new ArgumentNullException("deploymentName");
            }

            // 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("deploymentName", deploymentName);
                TracingAdapter.Enter(invocationId, this, "CheckExistenceAsync", 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 + "/deployments/";
            url = url + Uri.EscapeDataString(deploymentName);
            List<string> queryParameters = new List<string>();
            queryParameters.Add("api-version=2016-02-01");
            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.Head;
                httpRequest.RequestUri = new Uri(url);

                // Set Headers

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

                // 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.NoContent && statusCode != HttpStatusCode.NotFound)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
                        if (shouldTrace)
                        {
                            TracingAdapter.Error(invocationId, ex);
                        }
                        throw ex;
                    }

                    // Create Result
                    DeploymentExistsResult result = null;
                    // Deserialize Response
                    result = new DeploymentExistsResult();
                    result.StatusCode = statusCode;
                    if (httpResponse.Headers.Contains("x-ms-request-id"))
                    {
                        result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
                    }
                    if (statusCode == HttpStatusCode.NoContent)
                    {
                        result.Exists = true;
                    }

                    if (shouldTrace)
                    {
                        TracingAdapter.Exit(invocationId, result);
                    }
                    return result;
                }
                finally
                {
                    if (httpResponse != null)
                    {
                        httpResponse.Dispose();
                    }
                }
            }
            finally
            {
                if (httpRequest != null)
                {
                    httpRequest.Dispose();
                }
            }
        }

        /// <summary>
        /// Create a named template deployment using a template.
        /// </summary>
        /// <param name='resourceGroupName'>
        /// Required. The name of the resource group. The name is case
        /// insensitive.
        /// </param>
        /// <param name='deploymentName'>
        /// Required. The name of the deployment.
        /// </param>
        /// <param name='parameters'>
        /// Required. Additional parameters supplied to the operation.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// Template deployment operation create result.
        /// </returns>
        public async Task<DeploymentOperationsCreateResult> CreateOrUpdateAsync(string resourceGroupName, string deploymentName, Deployment parameters, CancellationToken cancellationToken)
        {
            // Validate
            if (resourceGroupName == null)
            {
                throw new ArgumentNullException("resourceGroupName");
            }
            if (resourceGroupName != null && resourceGroupName.Length > 1000)
            {
                throw new ArgumentOutOfRangeException("resourceGroupName");
            }
            if (Regex.IsMatch(resourceGroupName, "^[-\\w\\._]+$") == false)
            {
                throw new ArgumentOutOfRangeException("resourceGroupName");
            }
            if (deploymentName == null)
            {
                throw new ArgumentNullException("deploymentName");
            }
            if (parameters == null)
            {
                throw new ArgumentNullException("parameters");
            }
            if (parameters.Properties != null)
            {
                if (parameters.Properties.DebugSetting != null)
                {
                    if (parameters.Properties.DebugSetting.DeploymentDebugDetailLevel == null)
                    {
                        throw new ArgumentNullException("parameters.Properties.DebugSetting.DeploymentDebugDetailLevel");
                    }
                }
                if (parameters.Properties.ParametersLink != null)
                {
                    if (parameters.Properties.ParametersLink.Uri == null)
                    {
                        throw new ArgumentNullException("parameters.Properties.ParametersLink.Uri");
                    }
                }
                if (parameters.Properties.TemplateLink != null)
                {
                    if (parameters.Properties.TemplateLink.Uri == null)
                    {
                        throw new ArgumentNullException("parameters.Properties.TemplateLink.Uri");
                    }
                }
            }

            // 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("deploymentName", deploymentName);
                tracingParameters.Add("parameters", parameters);
                TracingAdapter.Enter(invocationId, this, "CreateOrUpdateAsync", 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 + "/deployments/";
            url = url + Uri.EscapeDataString(deploymentName);
            List<string> queryParameters = new List<string>();
            queryParameters.Add("api-version=2016-02-01");
            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

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

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

                JObject deploymentValue = new JObject();
                requestDoc = deploymentValue;

                if (parameters.Properties != null)
                {
                    JObject propertiesValue = new JObject();
                    deploymentValue["properties"] = propertiesValue;

                    if (parameters.Properties.Template != null)
                    {
                        propertiesValue["template"] = JObject.Parse(parameters.Properties.Template);
                    }

                    if (parameters.Properties.TemplateLink != null)
                    {
                        JObject templateLinkValue = new JObject();
                        propertiesValue["templateLink"] = templateLinkValue;

                        templateLinkValue["uri"] = parameters.Properties.TemplateLink.Uri.AbsoluteUri;

                        if (parameters.Properties.TemplateLink.ContentVersion != null)
                        {
                            templateLinkValue["contentVersion"] = parameters.Properties.TemplateLink.ContentVersion;
                        }
                    }

                    if (parameters.Properties.Parameters != null)
                    {
                        propertiesValue["parameters"] = JObject.Parse(parameters.Properties.Parameters);
                    }

                    if (parameters.Properties.ParametersLink != null)
                    {
                        JObject parametersLinkValue = new JObject();
                        propertiesValue["parametersLink"] = parametersLinkValue;

                        parametersLinkValue["uri"] = parameters.Properties.ParametersLink.Uri.AbsoluteUri;

                        if (parameters.Properties.ParametersLink.ContentVersion != null)
                        {
                            parametersLinkValue["contentVersion"] = parameters.Properties.ParametersLink.ContentVersion;
                        }
                    }

                    propertiesValue["mode"] = parameters.Properties.Mode.ToString();

                    if (parameters.Properties.DebugSetting != null)
                    {
                        JObject debugSettingValue = new JObject();
                        propertiesValue["debugSetting"] = debugSettingValue;

                        debugSettingValue["detailLevel"] = parameters.Properties.DebugSetting.DeploymentDebugDetailLevel;
                    }
                }

                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 && 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
                    DeploymentOperationsCreateResult result = null;
                    // Deserialize Response
                    if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Created)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
                        result = new DeploymentOperationsCreateResult();
                        JToken responseDoc = null;
                        if (string.IsNullOrEmpty(responseContent) == false)
                        {
                            responseDoc = JToken.Parse(responseContent);
                        }

                        if (responseDoc != null && responseDoc.Type != JTokenType.Null)
                        {
                            DeploymentExtended deploymentInstance = new DeploymentExtended();
                            result.Deployment = deploymentInstance;

                            JToken idValue = responseDoc["id"];
                            if (idValue != null && idValue.Type != JTokenType.Null)
                            {
                                string idInstance = ((string)idValue);
                                deploymentInstance.Id = idInstance;
                            }

                            JToken nameValue = responseDoc["name"];
                            if (nameValue != null && nameValue.Type != JTokenType.Null)
                            {
                                string nameInstance = ((string)nameValue);
                                deploymentInstance.Name = nameInstance;
                            }

                            JToken propertiesValue2 = responseDoc["properties"];
                            if (propertiesValue2 != null && propertiesValue2.Type != JTokenType.Null)
                            {
                                DeploymentPropertiesExtended propertiesInstance = new DeploymentPropertiesExtended();
                                deploymentInstance.Properties = propertiesInstance;

                                JToken provisioningStateValue = propertiesValue2["provisioningState"];
                                if (provisioningStateValue != null && provisioningStateValue.Type != JTokenType.Null)
                                {
                                    string provisioningStateInstance = ((string)provisioningStateValue);
                                    propertiesInstance.ProvisioningState = provisioningStateInstance;
                                }

                                JToken correlationIdValue = propertiesValue2["correlationId"];
                                if (correlationIdValue != null && correlationIdValue.Type != JTokenType.Null)
                                {
                                    string correlationIdInstance = ((string)correlationIdValue);
                                    propertiesInstance.CorrelationId = correlationIdInstance;
                                }

                                JToken timestampValue = propertiesValue2["timestamp"];
                                if (timestampValue != null && timestampValue.Type != JTokenType.Null)
                                {
                                    DateTime timestampInstance = ((DateTime)timestampValue);
                                    propertiesInstance.Timestamp = timestampInstance;
                                }

                                JToken durationValue = propertiesValue2["duration"];
                                if (durationValue != null && durationValue.Type != JTokenType.Null)
                                {
                                    TimeSpan durationInstance = XmlConvert.ToTimeSpan(((string)durationValue));
                                    propertiesInstance.Duration = durationInstance;
                                }

                                JToken outputsValue = propertiesValue2["outputs"];
                                if (outputsValue != null && outputsValue.Type != JTokenType.Null)
                                {
                                    string outputsInstance = outputsValue.ToString(Newtonsoft.Json.Formatting.Indented);
                                    propertiesInstance.Outputs = outputsInstance;
                                }

                                JToken providersArray = propertiesValue2["providers"];
                                if (providersArray != null && providersArray.Type != JTokenType.Null)
                                {
                                    foreach (JToken providersValue in ((JArray)providersArray))
                                    {
                                        Provider providerInstance = new Provider();
                                        propertiesInstance.Providers.Add(providerInstance);

                                        JToken idValue2 = providersValue["id"];
                                        if (idValue2 != null && idValue2.Type != JTokenType.Null)
                                        {
                                            string idInstance2 = ((string)idValue2);
                                            providerInstance.Id = idInstance2;
                                        }

                                        JToken namespaceValue = providersValue["namespace"];
                                        if (namespaceValue != null && namespaceValue.Type != JTokenType.Null)
                                        {
                                            string namespaceInstance = ((string)namespaceValue);
                                            providerInstance.Namespace = namespaceInstance;
                                        }

                                        JToken registrationStateValue = providersValue["registrationState"];
                                        if (registrationStateValue != null && registrationStateValue.Type != JTokenType.Null)
                                        {
                                            string registrationStateInstance = ((string)registrationStateValue);
                                            providerInstance.RegistrationState = registrationStateInstance;
                                        }

                                        JToken resourceTypesArray = providersValue["resourceTypes"];
                                        if (resourceTypesArray != null && resourceTypesArray.Type != JTokenType.Null)
                                        {
                                            foreach (JToken resourceTypesValue in ((JArray)resourceTypesArray))
                                            {
                                                ProviderResourceType providerResourceTypeInstance = new ProviderResourceType();
                                                providerInstance.ResourceTypes.Add(providerResourceTypeInstance);

                                                JToken resourceTypeValue = resourceTypesValue["resourceType"];
                                                if (resourceTypeValue != null && resourceTypeValue.Type != JTokenType.Null)
                                                {
                                                    string resourceTypeInstance = ((string)resourceTypeValue);
                                                    providerResourceTypeInstance.Name = resourceTypeInstance;
                                                }

                                                JToken locationsArray = resourceTypesValue["locations"];
                                                if (locationsArray != null && locationsArray.Type != JTokenType.Null)
                                                {
                                                    foreach (JToken locationsValue in ((JArray)locationsArray))
                                                    {
                                                        providerResourceTypeInstance.Locations.Add(((string)locationsValue));
                                                    }
                                                }

                                                JToken apiVersionsArray = resourceTypesValue["apiVersions"];
                                                if (apiVersionsArray != null && apiVersionsArray.Type != JTokenType.Null)
                                                {
                                                    foreach (JToken apiVersionsValue in ((JArray)apiVersionsArray))
                                                    {
                                                        providerResourceTypeInstance.ApiVersions.Add(((string)apiVersionsValue));
                                                    }
                                                }

                                                JToken propertiesSequenceElement = ((JToken)resourceTypesValue["properties"]);
                                                if (propertiesSequenceElement != null && propertiesSequenceElement.Type != JTokenType.Null)
                                                {
                                                    foreach (JProperty property in propertiesSequenceElement)
                                                    {
                                                        string propertiesKey = ((string)property.Name);
                                                        string propertiesValue3 = ((string)property.Value);
                                                        providerResourceTypeInstance.Properties.Add(propertiesKey, propertiesValue3);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }

                                JToken dependenciesArray = propertiesValue2["dependencies"];
                                if (dependenciesArray != null && dependenciesArray.Type != JTokenType.Null)
                                {
                                    foreach (JToken dependenciesValue in ((JArray)dependenciesArray))
                                    {
                                        Dependency dependencyInstance = new Dependency();
                                        propertiesInstance.Dependencies.Add(dependencyInstance);

                                        JToken dependsOnArray = dependenciesValue["dependsOn"];
                                        if (dependsOnArray != null && dependsOnArray.Type != JTokenType.Null)
                                        {
                                            foreach (JToken dependsOnValue in ((JArray)dependsOnArray))
                                            {
                                                BasicDependency basicDependencyInstance = new BasicDependency();
                                                dependencyInstance.DependsOn.Add(basicDependencyInstance);

                                                JToken idValue3 = dependsOnValue["id"];
                                                if (idValue3 != null && idValue3.Type != JTokenType.Null)
                                                {
                                                    string idInstance3 = ((string)idValue3);
                                                    basicDependencyInstance.Id = idInstance3;
                                                }

                                                JToken resourceTypeValue2 = dependsOnValue["resourceType"];
                                                if (resourceTypeValue2 != null && resourceTypeValue2.Type != JTokenType.Null)
                                                {
                                                    string resourceTypeInstance2 = ((string)resourceTypeValue2);
                                                    basicDependencyInstance.ResourceType = resourceTypeInstance2;
                                                }

                                                JToken resourceNameValue = dependsOnValue["resourceName"];
                                                if (resourceNameValue != null && resourceNameValue.Type != JTokenType.Null)
                                                {
                                                    string resourceNameInstance = ((string)resourceNameValue);
                                                    basicDependencyInstance.ResourceName = resourceNameInstance;
                                                }
                                            }
                                        }

                                        JToken idValue4 = dependenciesValue["id"];
                                        if (idValue4 != null && idValue4.Type != JTokenType.Null)
                                        {
                                            string idInstance4 = ((string)idValue4);
                                            dependencyInstance.Id = idInstance4;
                                        }

                                        JToken resourceTypeValue3 = dependenciesValue["resourceType"];
                                        if (resourceTypeValue3 != null && resourceTypeValue3.Type != JTokenType.Null)
                                        {
                                            string resourceTypeInstance3 = ((string)resourceTypeValue3);
                                            dependencyInstance.ResourceType = resourceTypeInstance3;
                                        }

                                        JToken resourceNameValue2 = dependenciesValue["resourceName"];
                                        if (resourceNameValue2 != null && resourceNameValue2.Type != JTokenType.Null)
                                        {
                                            string resourceNameInstance2 = ((string)resourceNameValue2);
                                            dependencyInstance.ResourceName = resourceNameInstance2;
                                        }
                                    }
                                }

                                JToken validatedResourcesArray = propertiesValue2["validatedResources"];
                                if (validatedResourcesArray != null && validatedResourcesArray.Type != JTokenType.Null)
                                {
                                    foreach (JToken validatedResourcesValue in ((JArray)validatedResourcesArray))
                                    {
                                        DeploymentPreFlightResource deploymentPreFlightResourceInstance = new DeploymentPreFlightResource();
                                        propertiesInstance.ValidatedResources.Add(deploymentPreFlightResourceInstance);

                                        JToken apiVersionValue = validatedResourcesValue["apiVersion"];
                                        if (apiVersionValue != null && apiVersionValue.Type != JTokenType.Null)
                                        {
                                            string apiVersionInstance = ((string)apiVersionValue);
                                            deploymentPreFlightResourceInstance.ApiVersion = apiVersionInstance;
                                        }

                                        JToken dependsOnArray2 = validatedResourcesValue["dependsOn"];
                                        if (dependsOnArray2 != null && dependsOnArray2.Type != JTokenType.Null)
                                        {
                                            foreach (JToken dependsOnValue2 in ((JArray)dependsOnArray2))
                                            {
                                                deploymentPreFlightResourceInstance.DependsOn.Add(((string)dependsOnValue2));
                                            }
                                        }

                                        JToken propertiesValue4 = validatedResourcesValue["properties"];
                                        if (propertiesValue4 != null && propertiesValue4.Type != JTokenType.Null)
                                        {
                                            string propertiesInstance2 = propertiesValue4.ToString(Newtonsoft.Json.Formatting.Indented);
                                            deploymentPreFlightResourceInstance.Properties = propertiesInstance2;
                                        }

                                        JToken provisioningStateValue2 = validatedResourcesValue["provisioningState"];
                                        if (provisioningStateValue2 != null && provisioningStateValue2.Type != JTokenType.Null)
                                        {
                                            string provisioningStateInstance2 = ((string)provisioningStateValue2);
                                            deploymentPreFlightResourceInstance.ProvisioningState = provisioningStateInstance2;
                                        }

                                        JToken planValue = validatedResourcesValue["plan"];
                                        if (planValue != null && planValue.Type != JTokenType.Null)
                                        {
                                            Plan planInstance = new Plan();
                                            deploymentPreFlightResourceInstance.Plan = planInstance;

                                            JToken nameValue2 = planValue["name"];
                                            if (nameValue2 != null && nameValue2.Type != JTokenType.Null)
                                            {
                                                string nameInstance2 = ((string)nameValue2);
                                                planInstance.Name = nameInstance2;
                                            }

                                            JToken publisherValue = planValue["publisher"];
                                            if (publisherValue != null && publisherValue.Type != JTokenType.Null)
                                            {
                                                string publisherInstance = ((string)publisherValue);
                                                planInstance.Publisher = publisherInstance;
                                            }

                                            JToken productValue = planValue["product"];
                                            if (productValue != null && productValue.Type != JTokenType.Null)
                                            {
                                                string productInstance = ((string)productValue);
                                                planInstance.Product = productInstance;
                                            }

                                            JToken promotionCodeValue = planValue["promotionCode"];
                                            if (promotionCodeValue != null && promotionCodeValue.Type != JTokenType.Null)
                                            {
                                                string promotionCodeInstance = ((string)promotionCodeValue);
                                                planInstance.PromotionCode = promotionCodeInstance;
                                            }
                                        }

                                        JToken idValue5 = validatedResourcesValue["id"];
                                        if (idValue5 != null && idValue5.Type != JTokenType.Null)
                                        {
                                            string idInstance5 = ((string)idValue5);
                                            deploymentPreFlightResourceInstance.Id = idInstance5;
                                        }

                                        JToken nameValue3 = validatedResourcesValue["name"];
                                        if (nameValue3 != null && nameValue3.Type != JTokenType.Null)
                                        {
                                            string nameInstance3 = ((string)nameValue3);
                                            deploymentPreFlightResourceInstance.Name = nameInstance3;
                                        }

                                        JToken typeValue = validatedResourcesValue["type"];
                                        if (typeValue != null && typeValue.Type != JTokenType.Null)
                                        {
                                            string typeInstance = ((string)typeValue);
                                            deploymentPreFlightResourceInstance.Type = typeInstance;
                                        }

                                        JToken locationValue = validatedResourcesValue["location"];
                                        if (locationValue != null && locationValue.Type != JTokenType.Null)
                                        {
                                            string locationInstance = ((string)locationValue);
                                            deploymentPreFlightResourceInstance.Location = locationInstance;
                                        }

                                        JToken tagsSequenceElement = ((JToken)validatedResourcesValue["tags"]);
                                        if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
                                        {
                                            foreach (JProperty property2 in tagsSequenceElement)
                                            {
                                                string tagsKey = ((string)property2.Name);
                                                string tagsValue = ((string)property2.Value);
                                                deploymentPreFlightResourceInstance.Tags.Add(tagsKey, tagsValue);
                                            }
                                        }
                                    }
                                }

                                JToken debugSettingValue2 = propertiesValue2["debugSetting"];
                                if (debugSettingValue2 != null && debugSettingValue2.Type != JTokenType.Null)
                                {
                                    DeploymentDebugSetting debugSettingInstance = new DeploymentDebugSetting();
                                    propertiesInstance.DebugSettingResponse = debugSettingInstance;

                                    JToken detailLevelValue = debugSettingValue2["detailLevel"];
                                    if (detailLevelValue != null && detailLevelValue.Type != JTokenType.Null)
                                    {
                                        string detailLevelInstance = ((string)detailLevelValue);
                                        debugSettingInstance.DeploymentDebugDetailLevel = detailLevelInstance;
                                    }
                                }

                                JToken templateValue = propertiesValue2["template"];
                                if (templateValue != null && templateValue.Type != JTokenType.Null)
                                {
                                    string templateInstance = templateValue.ToString(Newtonsoft.Json.Formatting.Indented);
                                    propertiesInstance.Template = templateInstance;
                                }

                                JToken templateLinkValue2 = propertiesValue2["templateLink"];
                                if (templateLinkValue2 != null && templateLinkValue2.Type != JTokenType.Null)
                                {
                                    TemplateLink templateLinkInstance = new TemplateLink();
                                    propertiesInstance.TemplateLink = templateLinkInstance;

                                    JToken uriValue = templateLinkValue2["uri"];
                                    if (uriValue != null && uriValue.Type != JTokenType.Null)
                                    {
                                        Uri uriInstance = TypeConversion.TryParseUri(((string)uriValue));
                                        templateLinkInstance.Uri = uriInstance;
                                    }

                                    JToken contentVersionValue = templateLinkValue2["contentVersion"];
                                    if (contentVersionValue != null && contentVersionValue.Type != JTokenType.Null)
                                    {
                                        string contentVersionInstance = ((string)contentVersionValue);
                                        templateLinkInstance.ContentVersion = contentVersionInstance;
                                    }
                                }

                                JToken parametersValue = propertiesValue2["parameters"];
                                if (parametersValue != null && parametersValue.Type != JTokenType.Null)
                                {
                                    string parametersInstance = parametersValue.ToString(Newtonsoft.Json.Formatting.Indented);
                                    propertiesInstance.Parameters = parametersInstance;
                                }

                                JToken parametersLinkValue2 = propertiesValue2["parametersLink"];
                                if (parametersLinkValue2 != null && parametersLinkValue2.Type != JTokenType.Null)
                                {
                                    ParametersLink parametersLinkInstance = new ParametersLink();
                                    propertiesInstance.ParametersLink = parametersLinkInstance;

                                    JToken uriValue2 = parametersLinkValue2["uri"];
                                    if (uriValue2 != null && uriValue2.Type != JTokenType.Null)
                                    {
                                        Uri uriInstance2 = TypeConversion.TryParseUri(((string)uriValue2));
                                        parametersLinkInstance.Uri = uriInstance2;
                                    }

                                    JToken contentVersionValue2 = parametersLinkValue2["contentVersion"];
                                    if (contentVersionValue2 != null && contentVersionValue2.Type != JTokenType.Null)
                                    {
                                        string contentVersionInstance2 = ((string)contentVersionValue2);
                                        parametersLinkInstance.ContentVersion = contentVersionInstance2;
                                    }
                                }

                                JToken modeValue = propertiesValue2["mode"];
                                if (modeValue != null && modeValue.Type != JTokenType.Null)
                                {
                                    DeploymentMode modeInstance = ((DeploymentMode)Enum.Parse(typeof(DeploymentMode), ((string)modeValue), true));
                                    propertiesInstance.Mode = modeInstance;
                                }

                                JToken debugSettingValue3 = propertiesValue2["debugSetting"];
                                if (debugSettingValue3 != null && debugSettingValue3.Type != JTokenType.Null)
                                {
                                    DeploymentDebugSetting debugSettingInstance2 = new DeploymentDebugSetting();
                                    propertiesInstance.DebugSetting = debugSettingInstance2;

                                    JToken detailLevelValue2 = debugSettingValue3["detailLevel"];
                                    if (detailLevelValue2 != null && detailLevelValue2.Type != JTokenType.Null)
                                    {
                                        string detailLevelInstance2 = ((string)detailLevelValue2);
                                        debugSettingInstance2.DeploymentDebugDetailLevel = detailLevelInstance2;
                                    }
                                }
                            }
                        }

                    }
                    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>
        /// Delete deployment and all of its resources.
        /// </summary>
        /// <param name='resourceGroupName'>
        /// Required. The name of the resource group. The name is case
        /// insensitive.
        /// </param>
        /// <param name='deploymentName'>
        /// Required. The name of the deployment to be deleted.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// A standard service response including an HTTP status code and
        /// request ID.
        /// </returns>
        public async Task<AzureOperationResponse> DeleteAsync(string resourceGroupName, string deploymentName, CancellationToken cancellationToken)
        {
            ResourceManagementClient client = this.Client;
            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("deploymentName", deploymentName);
                TracingAdapter.Enter(invocationId, this, "DeleteAsync", tracingParameters);
            }

            cancellationToken.ThrowIfCancellationRequested();
            LongRunningOperationResponse response = await client.Deployments.BeginDeletingAsync(resourceGroupName, deploymentName, cancellationToken).ConfigureAwait(false);
            cancellationToken.ThrowIfCancellationRequested();
            LongRunningOperationResponse result = await client.GetLongRunningOperationStatusAsync(response.OperationStatusLink, cancellationToken).ConfigureAwait(false);
            int delayInSeconds = response.RetryAfter;
            if (delayInSeconds == 0)
            {
                delayInSeconds = 30;
            }
            if (client.LongRunningOperationInitialTimeout >= 0)
            {
                delayInSeconds = client.LongRunningOperationInitialTimeout;
            }
            while (result.Status == OperationStatus.InProgress)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false);
                cancellationToken.ThrowIfCancellationRequested();
                result = await client.GetLongRunningOperationStatusAsync(response.OperationStatusLink, cancellationToken).ConfigureAwait(false);
                delayInSeconds = result.RetryAfter;
                if (delayInSeconds == 0)
                {
                    delayInSeconds = 15;
                }
                if (client.LongRunningOperationRetryTimeout >= 0)
                {
                    delayInSeconds = client.LongRunningOperationRetryTimeout;
                }
            }

            if (shouldTrace)
            {
                TracingAdapter.Exit(invocationId, result);
            }

            return result;
        }

        /// <summary>
        /// Get a deployment.
        /// </summary>
        /// <param name='resourceGroupName'>
        /// Required. The name of the resource group to get. The name is case
        /// insensitive.
        /// </param>
        /// <param name='deploymentName'>
        /// Required. The name of the deployment.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// Template deployment information.
        /// </returns>
        public async Task<DeploymentGetResult> GetAsync(string resourceGroupName, string deploymentName, CancellationToken cancellationToken)
        {
            // Validate
            if (resourceGroupName == null)
            {
                throw new ArgumentNullException("resourceGroupName");
            }
            if (resourceGroupName != null && resourceGroupName.Length > 1000)
            {
                throw new ArgumentOutOfRangeException("resourceGroupName");
            }
            if (Regex.IsMatch(resourceGroupName, "^[-\\w\\._]+$") == false)
            {
                throw new ArgumentOutOfRangeException("resourceGroupName");
            }
            if (deploymentName == null)
            {
                throw new ArgumentNullException("deploymentName");
            }

            // 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("deploymentName", deploymentName);
                TracingAdapter.Enter(invocationId, this, "GetAsync", 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 + "/deployments/";
            url = url + Uri.EscapeDataString(deploymentName);
            List<string> queryParameters = new List<string>();
            queryParameters.Add("api-version=2016-02-01");
            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.Get;
                httpRequest.RequestUri = new Uri(url);

                // Set Headers

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

                // 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, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
                        if (shouldTrace)
                        {
                            TracingAdapter.Error(invocationId, ex);
                        }
                        throw ex;
                    }

                    // Create Result
                    DeploymentGetResult result = null;
                    // Deserialize Response
                    if (statusCode == HttpStatusCode.OK)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
                        result = new DeploymentGetResult();
                        JToken responseDoc = null;
                        if (string.IsNullOrEmpty(responseContent) == false)
                        {
                            responseDoc = JToken.Parse(responseContent);
                        }

                        if (responseDoc != null && responseDoc.Type != JTokenType.Null)
                        {
                            DeploymentExtended deploymentInstance = new DeploymentExtended();
                            result.Deployment = deploymentInstance;

                            JToken idValue = responseDoc["id"];
                            if (idValue != null && idValue.Type != JTokenType.Null)
                            {
                                string idInstance = ((string)idValue);
                                deploymentInstance.Id = idInstance;
                            }

                            JToken nameValue = responseDoc["name"];
                            if (nameValue != null && nameValue.Type != JTokenType.Null)
                            {
                                string nameInstance = ((string)nameValue);
                                deploymentInstance.Name = nameInstance;
                            }

                            JToken propertiesValue = responseDoc["properties"];
                            if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
                            {
                                DeploymentPropertiesExtended propertiesInstance = new DeploymentPropertiesExtended();
                                deploymentInstance.Properties = propertiesInstance;

                                JToken provisioningStateValue = propertiesValue["provisioningState"];
                                if (provisioningStateValue != null && provisioningStateValue.Type != JTokenType.Null)
                                {
                                    string provisioningStateInstance = ((string)provisioningStateValue);
                                    propertiesInstance.ProvisioningState = provisioningStateInstance;
                                }

                                JToken correlationIdValue = propertiesValue["correlationId"];
                                if (correlationIdValue != null && correlationIdValue.Type != JTokenType.Null)
                                {
                                    string correlationIdInstance = ((string)correlationIdValue);
                                    propertiesInstance.CorrelationId = correlationIdInstance;
                                }

                                JToken timestampValue = propertiesValue["timestamp"];
                                if (timestampValue != null && timestampValue.Type != JTokenType.Null)
                                {
                                    DateTime timestampInstance = ((DateTime)timestampValue);
                                    propertiesInstance.Timestamp = timestampInstance;
                                }

                                JToken durationValue = propertiesValue["duration"];
                                if (durationValue != null && durationValue.Type != JTokenType.Null)
                                {
                                    TimeSpan durationInstance = XmlConvert.ToTimeSpan(((string)durationValue));
                                    propertiesInstance.Duration = durationInstance;
                                }

                                JToken outputsValue = propertiesValue["outputs"];
                                if (outputsValue != null && outputsValue.Type != JTokenType.Null)
                                {
                                    string outputsInstance = outputsValue.ToString(Newtonsoft.Json.Formatting.Indented);
                                    propertiesInstance.Outputs = outputsInstance;
                                }

                                JToken providersArray = propertiesValue["providers"];
                                if (providersArray != null && providersArray.Type != JTokenType.Null)
                                {
                                    foreach (JToken providersValue in ((JArray)providersArray))
                                    {
                                        Provider providerInstance = new Provider();
                                        propertiesInstance.Providers.Add(providerInstance);

                                        JToken idValue2 = providersValue["id"];
                                        if (idValue2 != null && idValue2.Type != JTokenType.Null)
                                        {
                                            string idInstance2 = ((string)idValue2);
                                            providerInstance.Id = idInstance2;
                                        }

                                        JToken namespaceValue = providersValue["namespace"];
                                        if (namespaceValue != null && namespaceValue.Type != JTokenType.Null)
                                        {
                                            string namespaceInstance = ((string)namespaceValue);
                                            providerInstance.Namespace = namespaceInstance;
                                        }

                                        JToken registrationStateValue = providersValue["registrationState"];
                                        if (registrationStateValue != null && registrationStateValue.Type != JTokenType.Null)
                                        {
                                            string registrationStateInstance = ((string)registrationStateValue);
                                            providerInstance.RegistrationState = registrationStateInstance;
                                        }

                                        JToken resourceTypesArray = providersValue["resourceTypes"];
                                        if (resourceTypesArray != null && resourceTypesArray.Type != JTokenType.Null)
                                        {
                                            foreach (JToken resourceTypesValue in ((JArray)resourceTypesArray))
                                            {
                                                ProviderResourceType providerResourceTypeInstance = new ProviderResourceType();
                                                providerInstance.ResourceTypes.Add(providerResourceTypeInstance);

                                                JToken resourceTypeValue = resourceTypesValue["resourceType"];
                                                if (resourceTypeValue != null && resourceTypeValue.Type != JTokenType.Null)
                                                {
                                                    string resourceTypeInstance = ((string)resourceTypeValue);
                                                    providerResourceTypeInstance.Name = resourceTypeInstance;
                                                }

                                                JToken locationsArray = resourceTypesValue["locations"];
                                                if (locationsArray != null && locationsArray.Type != JTokenType.Null)
                                                {
                                                    foreach (JToken locationsValue in ((JArray)locationsArray))
                                                    {
                                                        providerResourceTypeInstance.Locations.Add(((string)locationsValue));
                                                    }
                                                }

                                                JToken apiVersionsArray = resourceTypesValue["apiVersions"];
                                                if (apiVersionsArray != null && apiVersionsArray.Type != JTokenType.Null)
                                                {
                                                    foreach (JToken apiVersionsValue in ((JArray)apiVersionsArray))
                                                    {
                                                        providerResourceTypeInstance.ApiVersions.Add(((string)apiVersionsValue));
                                                    }
                                                }

                                                JToken propertiesSequenceElement = ((JToken)resourceTypesValue["properties"]);
                                                if (propertiesSequenceElement != null && propertiesSequenceElement.Type != JTokenType.Null)
                                                {
                                                    foreach (JProperty property in propertiesSequenceElement)
                                                    {
                                                        string propertiesKey = ((string)property.Name);
                                                        string propertiesValue2 = ((string)property.Value);
                                                        providerResourceTypeInstance.Properties.Add(propertiesKey, propertiesValue2);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }

                                JToken dependenciesArray = propertiesValue["dependencies"];
                                if (dependenciesArray != null && dependenciesArray.Type != JTokenType.Null)
                                {
                                    foreach (JToken dependenciesValue in ((JArray)dependenciesArray))
                                    {
                                        Dependency dependencyInstance = new Dependency();
                                        propertiesInstance.Dependencies.Add(dependencyInstance);

                                        JToken dependsOnArray = dependenciesValue["dependsOn"];
                                        if (dependsOnArray != null && dependsOnArray.Type != JTokenType.Null)
                                        {
                                            foreach (JToken dependsOnValue in ((JArray)dependsOnArray))
                                            {
                                                BasicDependency basicDependencyInstance = new BasicDependency();
                                                dependencyInstance.DependsOn.Add(basicDependencyInstance);

                                                JToken idValue3 = dependsOnValue["id"];
                                                if (idValue3 != null && idValue3.Type != JTokenType.Null)
                                                {
                                                    string idInstance3 = ((string)idValue3);
                                                    basicDependencyInstance.Id = idInstance3;
                                                }

                                                JToken resourceTypeValue2 = dependsOnValue["resourceType"];
                                                if (resourceTypeValue2 != null && resourceTypeValue2.Type != JTokenType.Null)
                                                {
                                                    string resourceTypeInstance2 = ((string)resourceTypeValue2);
                                                    basicDependencyInstance.ResourceType = resourceTypeInstance2;
                                                }

                                                JToken resourceNameValue = dependsOnValue["resourceName"];
                                                if (resourceNameValue != null && resourceNameValue.Type != JTokenType.Null)
                                                {
                                                    string resourceNameInstance = ((string)resourceNameValue);
                                                    basicDependencyInstance.ResourceName = resourceNameInstance;
                                                }
                                            }
                                        }

                                        JToken idValue4 = dependenciesValue["id"];
                                        if (idValue4 != null && idValue4.Type != JTokenType.Null)
                                        {
                                            string idInstance4 = ((string)idValue4);
                                            dependencyInstance.Id = idInstance4;
                                        }

                                        JToken resourceTypeValue3 = dependenciesValue["resourceType"];
                                        if (resourceTypeValue3 != null && resourceTypeValue3.Type != JTokenType.Null)
                                        {
                                            string resourceTypeInstance3 = ((string)resourceTypeValue3);
                                            dependencyInstance.ResourceType = resourceTypeInstance3;
                                        }

                                        JToken resourceNameValue2 = dependenciesValue["resourceName"];
                                        if (resourceNameValue2 != null && resourceNameValue2.Type != JTokenType.Null)
                                        {
                                            string resourceNameInstance2 = ((string)resourceNameValue2);
                                            dependencyInstance.ResourceName = resourceNameInstance2;
                                        }
                                    }
                                }

                                JToken validatedResourcesArray = propertiesValue["validatedResources"];
                                if (validatedResourcesArray != null && validatedResourcesArray.Type != JTokenType.Null)
                                {
                                    foreach (JToken validatedResourcesValue in ((JArray)validatedResourcesArray))
                                    {
                                        DeploymentPreFlightResource deploymentPreFlightResourceInstance = new DeploymentPreFlightResource();
                                        propertiesInstance.ValidatedResources.Add(deploymentPreFlightResourceInstance);

                                        JToken apiVersionValue = validatedResourcesValue["apiVersion"];
                                        if (apiVersionValue != null && apiVersionValue.Type != JTokenType.Null)
                                        {
                                            string apiVersionInstance = ((string)apiVersionValue);
                                            deploymentPreFlightResourceInstance.ApiVersion = apiVersionInstance;
                                        }

                                        JToken dependsOnArray2 = validatedResourcesValue["dependsOn"];
                                        if (dependsOnArray2 != null && dependsOnArray2.Type != JTokenType.Null)
                                        {
                                            foreach (JToken dependsOnValue2 in ((JArray)dependsOnArray2))
                                            {
                                                deploymentPreFlightResourceInstance.DependsOn.Add(((string)dependsOnValue2));
                                            }
                                        }

                                        JToken propertiesValue3 = validatedResourcesValue["properties"];
                                        if (propertiesValue3 != null && propertiesValue3.Type != JTokenType.Null)
                                        {
                                            string propertiesInstance2 = propertiesValue3.ToString(Newtonsoft.Json.Formatting.Indented);
                                            deploymentPreFlightResourceInstance.Properties = propertiesInstance2;
                                        }

                                        JToken provisioningStateValue2 = validatedResourcesValue["provisioningState"];
                                        if (provisioningStateValue2 != null && provisioningStateValue2.Type != JTokenType.Null)
                                        {
                                            string provisioningStateInstance2 = ((string)provisioningStateValue2);
                                            deploymentPreFlightResourceInstance.ProvisioningState = provisioningStateInstance2;
                                        }

                                        JToken planValue = validatedResourcesValue["plan"];
                                        if (planValue != null && planValue.Type != JTokenType.Null)
                                        {
                                            Plan planInstance = new Plan();
                                            deploymentPreFlightResourceInstance.Plan = planInstance;

                                            JToken nameValue2 = planValue["name"];
                                            if (nameValue2 != null && nameValue2.Type != JTokenType.Null)
                                            {
                                                string nameInstance2 = ((string)nameValue2);
                                                planInstance.Name = nameInstance2;
                                            }

                                            JToken publisherValue = planValue["publisher"];
                                            if (publisherValue != null && publisherValue.Type != JTokenType.Null)
                                            {
                                                string publisherInstance = ((string)publisherValue);
                                                planInstance.Publisher = publisherInstance;
                                            }

                                            JToken productValue = planValue["product"];
                                            if (productValue != null && productValue.Type != JTokenType.Null)
                                            {
                                                string productInstance = ((string)productValue);
                                                planInstance.Product = productInstance;
                                            }

                                            JToken promotionCodeValue = planValue["promotionCode"];
                                            if (promotionCodeValue != null && promotionCodeValue.Type != JTokenType.Null)
                                            {
                                                string promotionCodeInstance = ((string)promotionCodeValue);
                                                planInstance.PromotionCode = promotionCodeInstance;
                                            }
                                        }

                                        JToken idValue5 = validatedResourcesValue["id"];
                                        if (idValue5 != null && idValue5.Type != JTokenType.Null)
                                        {
                                            string idInstance5 = ((string)idValue5);
                                            deploymentPreFlightResourceInstance.Id = idInstance5;
                                        }

                                        JToken nameValue3 = validatedResourcesValue["name"];
                                        if (nameValue3 != null && nameValue3.Type != JTokenType.Null)
                                        {
                                            string nameInstance3 = ((string)nameValue3);
                                            deploymentPreFlightResourceInstance.Name = nameInstance3;
                                        }

                                        JToken typeValue = validatedResourcesValue["type"];
                                        if (typeValue != null && typeValue.Type != JTokenType.Null)
                                        {
                                            string typeInstance = ((string)typeValue);
                                            deploymentPreFlightResourceInstance.Type = typeInstance;
                                        }

                                        JToken locationValue = validatedResourcesValue["location"];
                                        if (locationValue != null && locationValue.Type != JTokenType.Null)
                                        {
                                            string locationInstance = ((string)locationValue);
                                            deploymentPreFlightResourceInstance.Location = locationInstance;
                                        }

                                        JToken tagsSequenceElement = ((JToken)validatedResourcesValue["tags"]);
                                        if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
                                        {
                                            foreach (JProperty property2 in tagsSequenceElement)
                                            {
                                                string tagsKey = ((string)property2.Name);
                                                string tagsValue = ((string)property2.Value);
                                                deploymentPreFlightResourceInstance.Tags.Add(tagsKey, tagsValue);
                                            }
                                        }
                                    }
                                }

                                JToken debugSettingValue = propertiesValue["debugSetting"];
                                if (debugSettingValue != null && debugSettingValue.Type != JTokenType.Null)
                                {
                                    DeploymentDebugSetting debugSettingInstance = new DeploymentDebugSetting();
                                    propertiesInstance.DebugSettingResponse = debugSettingInstance;

                                    JToken detailLevelValue = debugSettingValue["detailLevel"];
                                    if (detailLevelValue != null && detailLevelValue.Type != JTokenType.Null)
                                    {
                                        string detailLevelInstance = ((string)detailLevelValue);
                                        debugSettingInstance.DeploymentDebugDetailLevel = detailLevelInstance;
                                    }
                                }

                                JToken templateValue = propertiesValue["template"];
                                if (templateValue != null && templateValue.Type != JTokenType.Null)
                                {
                                    string templateInstance = templateValue.ToString(Newtonsoft.Json.Formatting.Indented);
                                    propertiesInstance.Template = templateInstance;
                                }

                                JToken templateLinkValue = propertiesValue["templateLink"];
                                if (templateLinkValue != null && templateLinkValue.Type != JTokenType.Null)
                                {
                                    TemplateLink templateLinkInstance = new TemplateLink();
                                    propertiesInstance.TemplateLink = templateLinkInstance;

                                    JToken uriValue = templateLinkValue["uri"];
                                    if (uriValue != null && uriValue.Type != JTokenType.Null)
                                    {
                                        Uri uriInstance = TypeConversion.TryParseUri(((string)uriValue));
                                        templateLinkInstance.Uri = uriInstance;
                                    }

                                    JToken contentVersionValue = templateLinkValue["contentVersion"];
                                    if (contentVersionValue != null && contentVersionValue.Type != JTokenType.Null)
                                    {
                                        string contentVersionInstance = ((string)contentVersionValue);
                                        templateLinkInstance.ContentVersion = contentVersionInstance;
                                    }
                                }

                                JToken parametersValue = propertiesValue["parameters"];
                                if (parametersValue != null && parametersValue.Type != JTokenType.Null)
                                {
                                    string parametersInstance = parametersValue.ToString(Newtonsoft.Json.Formatting.Indented);
                                    propertiesInstance.Parameters = parametersInstance;
                                }

                                JToken parametersLinkValue = propertiesValue["parametersLink"];
                                if (parametersLinkValue != null && parametersLinkValue.Type != JTokenType.Null)
                                {
                                    ParametersLink parametersLinkInstance = new ParametersLink();
                                    propertiesInstance.ParametersLink = parametersLinkInstance;

                                    JToken uriValue2 = parametersLinkValue["uri"];
                                    if (uriValue2 != null && uriValue2.Type != JTokenType.Null)
                                    {
                                        Uri uriInstance2 = TypeConversion.TryParseUri(((string)uriValue2));
                                        parametersLinkInstance.Uri = uriInstance2;
                                    }

                                    JToken contentVersionValue2 = parametersLinkValue["contentVersion"];
                                    if (contentVersionValue2 != null && contentVersionValue2.Type != JTokenType.Null)
                                    {
                                        string contentVersionInstance2 = ((string)contentVersionValue2);
                                        parametersLinkInstance.ContentVersion = contentVersionInstance2;
                                    }
                                }

                                JToken modeValue = propertiesValue["mode"];
                                if (modeValue != null && modeValue.Type != JTokenType.Null)
                                {
                                    DeploymentMode modeInstance = ((DeploymentMode)Enum.Parse(typeof(DeploymentMode), ((string)modeValue), true));
                                    propertiesInstance.Mode = modeInstance;
                                }

                                JToken debugSettingValue2 = propertiesValue["debugSetting"];
                                if (debugSettingValue2 != null && debugSettingValue2.Type != JTokenType.Null)
                                {
                                    DeploymentDebugSetting debugSettingInstance2 = new DeploymentDebugSetting();
                                    propertiesInstance.DebugSetting = debugSettingInstance2;

                                    JToken detailLevelValue2 = debugSettingValue2["detailLevel"];
                                    if (detailLevelValue2 != null && detailLevelValue2.Type != JTokenType.Null)
                                    {
                                        string detailLevelInstance2 = ((string)detailLevelValue2);
                                        debugSettingInstance2.DeploymentDebugDetailLevel = detailLevelInstance2;
                                    }
                                }
                            }
                        }

                    }
                    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>
        /// Get a list of deployments.
        /// </summary>
        /// <param name='resourceGroupName'>
        /// Required. The name of the resource group to filter by. The name is
        /// case insensitive.
        /// </param>
        /// <param name='parameters'>
        /// Optional. Query parameters. If null is passed returns all
        /// deployments.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// List of deployments.
        /// </returns>
        public async Task<DeploymentListResult> ListAsync(string resourceGroupName, DeploymentListParameters parameters, CancellationToken cancellationToken)
        {
            // Validate
            if (resourceGroupName == null)
            {
                throw new ArgumentNullException("resourceGroupName");
            }

            // 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("parameters", parameters);
                TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters);
            }

            // Construct URL
            string url = "";
            url = url + "/subscriptions/";
            if (this.Client.Credentials.SubscriptionId != null)
            {
                url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
            }
            url = url + "/";
            url = url + "resourcegroups/" + Uri.EscapeDataString(resourceGroupName) + "/";
            url = url + "deployments/";
            List<string> queryParameters = new List<string>();
            List<string> odataFilter = new List<string>();
            if (parameters != null && parameters.ProvisioningState != null)
            {
                odataFilter.Add("provisioningState eq '" + Uri.EscapeDataString(parameters.ProvisioningState) + "'");
            }
            if (odataFilter.Count > 0)
            {
                queryParameters.Add("$filter=" + string.Join(null, odataFilter));
            }
            if (parameters != null && parameters.Top != null)
            {
                queryParameters.Add("$top=" + Uri.EscapeDataString(parameters.Top.Value.ToString()));
            }
            queryParameters.Add("api-version=2016-02-01");
            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.Get;
                httpRequest.RequestUri = new Uri(url);

                // Set Headers

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

                // 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, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
                        if (shouldTrace)
                        {
                            TracingAdapter.Error(invocationId, ex);
                        }
                        throw ex;
                    }

                    // Create Result
                    DeploymentListResult result = null;
                    // Deserialize Response
                    if (statusCode == HttpStatusCode.OK)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
                        result = new DeploymentListResult();
                        JToken responseDoc = null;
                        if (string.IsNullOrEmpty(responseContent) == false)
                        {
                            responseDoc = JToken.Parse(responseContent);
                        }

                        if (responseDoc != null && responseDoc.Type != JTokenType.Null)
                        {
                            JToken valueArray = responseDoc["value"];
                            if (valueArray != null && valueArray.Type != JTokenType.Null)
                            {
                                foreach (JToken valueValue in ((JArray)valueArray))
                                {
                                    DeploymentExtended deploymentExtendedInstance = new DeploymentExtended();
                                    result.Deployments.Add(deploymentExtendedInstance);

                                    JToken idValue = valueValue["id"];
                                    if (idValue != null && idValue.Type != JTokenType.Null)
                                    {
                                        string idInstance = ((string)idValue);
                                        deploymentExtendedInstance.Id = idInstance;
                                    }

                                    JToken nameValue = valueValue["name"];
                                    if (nameValue != null && nameValue.Type != JTokenType.Null)
                                    {
                                        string nameInstance = ((string)nameValue);
                                        deploymentExtendedInstance.Name = nameInstance;
                                    }

                                    JToken propertiesValue = valueValue["properties"];
                                    if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
                                    {
                                        DeploymentPropertiesExtended propertiesInstance = new DeploymentPropertiesExtended();
                                        deploymentExtendedInstance.Properties = propertiesInstance;

                                        JToken provisioningStateValue = propertiesValue["provisioningState"];
                                        if (provisioningStateValue != null && provisioningStateValue.Type != JTokenType.Null)
                                        {
                                            string provisioningStateInstance = ((string)provisioningStateValue);
                                            propertiesInstance.ProvisioningState = provisioningStateInstance;
                                        }

                                        JToken correlationIdValue = propertiesValue["correlationId"];
                                        if (correlationIdValue != null && correlationIdValue.Type != JTokenType.Null)
                                        {
                                            string correlationIdInstance = ((string)correlationIdValue);
                                            propertiesInstance.CorrelationId = correlationIdInstance;
                                        }

                                        JToken timestampValue = propertiesValue["timestamp"];
                                        if (timestampValue != null && timestampValue.Type != JTokenType.Null)
                                        {
                                            DateTime timestampInstance = ((DateTime)timestampValue);
                                            propertiesInstance.Timestamp = timestampInstance;
                                        }

                                        JToken durationValue = propertiesValue["duration"];
                                        if (durationValue != null && durationValue.Type != JTokenType.Null)
                                        {
                                            TimeSpan durationInstance = XmlConvert.ToTimeSpan(((string)durationValue));
                                            propertiesInstance.Duration = durationInstance;
                                        }

                                        JToken outputsValue = propertiesValue["outputs"];
                                        if (outputsValue != null && outputsValue.Type != JTokenType.Null)
                                        {
                                            string outputsInstance = outputsValue.ToString(Newtonsoft.Json.Formatting.Indented);
                                            propertiesInstance.Outputs = outputsInstance;
                                        }

                                        JToken providersArray = propertiesValue["providers"];
                                        if (providersArray != null && providersArray.Type != JTokenType.Null)
                                        {
                                            foreach (JToken providersValue in ((JArray)providersArray))
                                            {
                                                Provider providerInstance = new Provider();
                                                propertiesInstance.Providers.Add(providerInstance);

                                                JToken idValue2 = providersValue["id"];
                                                if (idValue2 != null && idValue2.Type != JTokenType.Null)
                                                {
                                                    string idInstance2 = ((string)idValue2);
                                                    providerInstance.Id = idInstance2;
                                                }

                                                JToken namespaceValue = providersValue["namespace"];
                                                if (namespaceValue != null && namespaceValue.Type != JTokenType.Null)
                                                {
                                                    string namespaceInstance = ((string)namespaceValue);
                                                    providerInstance.Namespace = namespaceInstance;
                                                }

                                                JToken registrationStateValue = providersValue["registrationState"];
                                                if (registrationStateValue != null && registrationStateValue.Type != JTokenType.Null)
                                                {
                                                    string registrationStateInstance = ((string)registrationStateValue);
                                                    providerInstance.RegistrationState = registrationStateInstance;
                                                }

                                                JToken resourceTypesArray = providersValue["resourceTypes"];
                                                if (resourceTypesArray != null && resourceTypesArray.Type != JTokenType.Null)
                                                {
                                                    foreach (JToken resourceTypesValue in ((JArray)resourceTypesArray))
                                                    {
                                                        ProviderResourceType providerResourceTypeInstance = new ProviderResourceType();
                                                        providerInstance.ResourceTypes.Add(providerResourceTypeInstance);

                                                        JToken resourceTypeValue = resourceTypesValue["resourceType"];
                                                        if (resourceTypeValue != null && resourceTypeValue.Type != JTokenType.Null)
                                                        {
                                                            string resourceTypeInstance = ((string)resourceTypeValue);
                                                            providerResourceTypeInstance.Name = resourceTypeInstance;
                                                        }

                                                        JToken locationsArray = resourceTypesValue["locations"];
                                                        if (locationsArray != null && locationsArray.Type != JTokenType.Null)
                                                        {
                                                            foreach (JToken locationsValue in ((JArray)locationsArray))
                                                            {
                                                                providerResourceTypeInstance.Locations.Add(((string)locationsValue));
                                                            }
                                                        }

                                                        JToken apiVersionsArray = resourceTypesValue["apiVersions"];
                                                        if (apiVersionsArray != null && apiVersionsArray.Type != JTokenType.Null)
                                                        {
                                                            foreach (JToken apiVersionsValue in ((JArray)apiVersionsArray))
                                                            {
                                                                providerResourceTypeInstance.ApiVersions.Add(((string)apiVersionsValue));
                                                            }
                                                        }

                                                        JToken propertiesSequenceElement = ((JToken)resourceTypesValue["properties"]);
                                                        if (propertiesSequenceElement != null && propertiesSequenceElement.Type != JTokenType.Null)
                                                        {
                                                            foreach (JProperty property in propertiesSequenceElement)
                                                            {
                                                                string propertiesKey = ((string)property.Name);
                                                                string propertiesValue2 = ((string)property.Value);
                                                                providerResourceTypeInstance.Properties.Add(propertiesKey, propertiesValue2);
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }

                                        JToken dependenciesArray = propertiesValue["dependencies"];
                                        if (dependenciesArray != null && dependenciesArray.Type != JTokenType.Null)
                                        {
                                            foreach (JToken dependenciesValue in ((JArray)dependenciesArray))
                                            {
                                                Dependency dependencyInstance = new Dependency();
                                                propertiesInstance.Dependencies.Add(dependencyInstance);

                                                JToken dependsOnArray = dependenciesValue["dependsOn"];
                                                if (dependsOnArray != null && dependsOnArray.Type != JTokenType.Null)
                                                {
                                                    foreach (JToken dependsOnValue in ((JArray)dependsOnArray))
                                                    {
                                                        BasicDependency basicDependencyInstance = new BasicDependency();
                                                        dependencyInstance.DependsOn.Add(basicDependencyInstance);

                                                        JToken idValue3 = dependsOnValue["id"];
                                                        if (idValue3 != null && idValue3.Type != JTokenType.Null)
                                                        {
                                                            string idInstance3 = ((string)idValue3);
                                                            basicDependencyInstance.Id = idInstance3;
                                                        }

                                                        JToken resourceTypeValue2 = dependsOnValue["resourceType"];
                                                        if (resourceTypeValue2 != null && resourceTypeValue2.Type != JTokenType.Null)
                                                        {
                                                            string resourceTypeInstance2 = ((string)resourceTypeValue2);
                                                            basicDependencyInstance.ResourceType = resourceTypeInstance2;
                                                        }

                                                        JToken resourceNameValue = dependsOnValue["resourceName"];
                                                        if (resourceNameValue != null && resourceNameValue.Type != JTokenType.Null)
                                                        {
                                                            string resourceNameInstance = ((string)resourceNameValue);
                                                            basicDependencyInstance.ResourceName = resourceNameInstance;
                                                        }
                                                    }
                                                }

                                                JToken idValue4 = dependenciesValue["id"];
                                                if (idValue4 != null && idValue4.Type != JTokenType.Null)
                                                {
                                                    string idInstance4 = ((string)idValue4);
                                                    dependencyInstance.Id = idInstance4;
                                                }

                                                JToken resourceTypeValue3 = dependenciesValue["resourceType"];
                                                if (resourceTypeValue3 != null && resourceTypeValue3.Type != JTokenType.Null)
                                                {
                                                    string resourceTypeInstance3 = ((string)resourceTypeValue3);
                                                    dependencyInstance.ResourceType = resourceTypeInstance3;
                                                }

                                                JToken resourceNameValue2 = dependenciesValue["resourceName"];
                                                if (resourceNameValue2 != null && resourceNameValue2.Type != JTokenType.Null)
                                                {
                                                    string resourceNameInstance2 = ((string)resourceNameValue2);
                                                    dependencyInstance.ResourceName = resourceNameInstance2;
                                                }
                                            }
                                        }

                                        JToken validatedResourcesArray = propertiesValue["validatedResources"];
                                        if (validatedResourcesArray != null && validatedResourcesArray.Type != JTokenType.Null)
                                        {
                                            foreach (JToken validatedResourcesValue in ((JArray)validatedResourcesArray))
                                            {
                                                DeploymentPreFlightResource deploymentPreFlightResourceInstance = new DeploymentPreFlightResource();
                                                propertiesInstance.ValidatedResources.Add(deploymentPreFlightResourceInstance);

                                                JToken apiVersionValue = validatedResourcesValue["apiVersion"];
                                                if (apiVersionValue != null && apiVersionValue.Type != JTokenType.Null)
                                                {
                                                    string apiVersionInstance = ((string)apiVersionValue);
                                                    deploymentPreFlightResourceInstance.ApiVersion = apiVersionInstance;
                                                }

                                                JToken dependsOnArray2 = validatedResourcesValue["dependsOn"];
                                                if (dependsOnArray2 != null && dependsOnArray2.Type != JTokenType.Null)
                                                {
                                                    foreach (JToken dependsOnValue2 in ((JArray)dependsOnArray2))
                                                    {
                                                        deploymentPreFlightResourceInstance.DependsOn.Add(((string)dependsOnValue2));
                                                    }
                                                }

                                                JToken propertiesValue3 = validatedResourcesValue["properties"];
                                                if (propertiesValue3 != null && propertiesValue3.Type != JTokenType.Null)
                                                {
                                                    string propertiesInstance2 = propertiesValue3.ToString(Newtonsoft.Json.Formatting.Indented);
                                                    deploymentPreFlightResourceInstance.Properties = propertiesInstance2;
                                                }

                                                JToken provisioningStateValue2 = validatedResourcesValue["provisioningState"];
                                                if (provisioningStateValue2 != null && provisioningStateValue2.Type != JTokenType.Null)
                                                {
                                                    string provisioningStateInstance2 = ((string)provisioningStateValue2);
                                                    deploymentPreFlightResourceInstance.ProvisioningState = provisioningStateInstance2;
                                                }

                                                JToken planValue = validatedResourcesValue["plan"];
                                                if (planValue != null && planValue.Type != JTokenType.Null)
                                                {
                                                    Plan planInstance = new Plan();
                                                    deploymentPreFlightResourceInstance.Plan = planInstance;

                                                    JToken nameValue2 = planValue["name"];
                                                    if (nameValue2 != null && nameValue2.Type != JTokenType.Null)
                                                    {
                                                        string nameInstance2 = ((string)nameValue2);
                                                        planInstance.Name = nameInstance2;
                                                    }

                                                    JToken publisherValue = planValue["publisher"];
                                                    if (publisherValue != null && publisherValue.Type != JTokenType.Null)
                                                    {
                                                        string publisherInstance = ((string)publisherValue);
                                                        planInstance.Publisher = publisherInstance;
                                                    }

                                                    JToken productValue = planValue["product"];
                                                    if (productValue != null && productValue.Type != JTokenType.Null)
                                                    {
                                                        string productInstance = ((string)productValue);
                                                        planInstance.Product = productInstance;
                                                    }

                                                    JToken promotionCodeValue = planValue["promotionCode"];
                                                    if (promotionCodeValue != null && promotionCodeValue.Type != JTokenType.Null)
                                                    {
                                                        string promotionCodeInstance = ((string)promotionCodeValue);
                                                        planInstance.PromotionCode = promotionCodeInstance;
                                                    }
                                                }

                                                JToken idValue5 = validatedResourcesValue["id"];
                                                if (idValue5 != null && idValue5.Type != JTokenType.Null)
                                                {
                                                    string idInstance5 = ((string)idValue5);
                                                    deploymentPreFlightResourceInstance.Id = idInstance5;
                                                }

                                                JToken nameValue3 = validatedResourcesValue["name"];
                                                if (nameValue3 != null && nameValue3.Type != JTokenType.Null)
                                                {
                                                    string nameInstance3 = ((string)nameValue3);
                                                    deploymentPreFlightResourceInstance.Name = nameInstance3;
                                                }

                                                JToken typeValue = validatedResourcesValue["type"];
                                                if (typeValue != null && typeValue.Type != JTokenType.Null)
                                                {
                                                    string typeInstance = ((string)typeValue);
                                                    deploymentPreFlightResourceInstance.Type = typeInstance;
                                                }

                                                JToken locationValue = validatedResourcesValue["location"];
                                                if (locationValue != null && locationValue.Type != JTokenType.Null)
                                                {
                                                    string locationInstance = ((string)locationValue);
                                                    deploymentPreFlightResourceInstance.Location = locationInstance;
                                                }

                                                JToken tagsSequenceElement = ((JToken)validatedResourcesValue["tags"]);
                                                if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
                                                {
                                                    foreach (JProperty property2 in tagsSequenceElement)
                                                    {
                                                        string tagsKey = ((string)property2.Name);
                                                        string tagsValue = ((string)property2.Value);
                                                        deploymentPreFlightResourceInstance.Tags.Add(tagsKey, tagsValue);
                                                    }
                                                }
                                            }
                                        }

                                        JToken debugSettingValue = propertiesValue["debugSetting"];
                                        if (debugSettingValue != null && debugSettingValue.Type != JTokenType.Null)
                                        {
                                            DeploymentDebugSetting debugSettingInstance = new DeploymentDebugSetting();
                                            propertiesInstance.DebugSettingResponse = debugSettingInstance;

                                            JToken detailLevelValue = debugSettingValue["detailLevel"];
                                            if (detailLevelValue != null && detailLevelValue.Type != JTokenType.Null)
                                            {
                                                string detailLevelInstance = ((string)detailLevelValue);
                                                debugSettingInstance.DeploymentDebugDetailLevel = detailLevelInstance;
                                            }
                                        }

                                        JToken templateValue = propertiesValue["template"];
                                        if (templateValue != null && templateValue.Type != JTokenType.Null)
                                        {
                                            string templateInstance = templateValue.ToString(Newtonsoft.Json.Formatting.Indented);
                                            propertiesInstance.Template = templateInstance;
                                        }

                                        JToken templateLinkValue = propertiesValue["templateLink"];
                                        if (templateLinkValue != null && templateLinkValue.Type != JTokenType.Null)
                                        {
                                            TemplateLink templateLinkInstance = new TemplateLink();
                                            propertiesInstance.TemplateLink = templateLinkInstance;

                                            JToken uriValue = templateLinkValue["uri"];
                                            if (uriValue != null && uriValue.Type != JTokenType.Null)
                                            {
                                                Uri uriInstance = TypeConversion.TryParseUri(((string)uriValue));
                                                templateLinkInstance.Uri = uriInstance;
                                            }

                                            JToken contentVersionValue = templateLinkValue["contentVersion"];
                                            if (contentVersionValue != null && contentVersionValue.Type != JTokenType.Null)
                                            {
                                                string contentVersionInstance = ((string)contentVersionValue);
                                                templateLinkInstance.ContentVersion = contentVersionInstance;
                                            }
                                        }

                                        JToken parametersValue = propertiesValue["parameters"];
                                        if (parametersValue != null && parametersValue.Type != JTokenType.Null)
                                        {
                                            string parametersInstance = parametersValue.ToString(Newtonsoft.Json.Formatting.Indented);
                                            propertiesInstance.Parameters = parametersInstance;
                                        }

                                        JToken parametersLinkValue = propertiesValue["parametersLink"];
                                        if (parametersLinkValue != null && parametersLinkValue.Type != JTokenType.Null)
                                        {
                                            ParametersLink parametersLinkInstance = new ParametersLink();
                                            propertiesInstance.ParametersLink = parametersLinkInstance;

                                            JToken uriValue2 = parametersLinkValue["uri"];
                                            if (uriValue2 != null && uriValue2.Type != JTokenType.Null)
                                            {
                                                Uri uriInstance2 = TypeConversion.TryParseUri(((string)uriValue2));
                                                parametersLinkInstance.Uri = uriInstance2;
                                            }

                                            JToken contentVersionValue2 = parametersLinkValue["contentVersion"];
                                            if (contentVersionValue2 != null && contentVersionValue2.Type != JTokenType.Null)
                                            {
                                                string contentVersionInstance2 = ((string)contentVersionValue2);
                                                parametersLinkInstance.ContentVersion = contentVersionInstance2;
                                            }
                                        }

                                        JToken modeValue = propertiesValue["mode"];
                                        if (modeValue != null && modeValue.Type != JTokenType.Null)
                                        {
                                            DeploymentMode modeInstance = ((DeploymentMode)Enum.Parse(typeof(DeploymentMode), ((string)modeValue), true));
                                            propertiesInstance.Mode = modeInstance;
                                        }

                                        JToken debugSettingValue2 = propertiesValue["debugSetting"];
                                        if (debugSettingValue2 != null && debugSettingValue2.Type != JTokenType.Null)
                                        {
                                            DeploymentDebugSetting debugSettingInstance2 = new DeploymentDebugSetting();
                                            propertiesInstance.DebugSetting = debugSettingInstance2;

                                            JToken detailLevelValue2 = debugSettingValue2["detailLevel"];
                                            if (detailLevelValue2 != null && detailLevelValue2.Type != JTokenType.Null)
                                            {
                                                string detailLevelInstance2 = ((string)detailLevelValue2);
                                                debugSettingInstance2.DeploymentDebugDetailLevel = detailLevelInstance2;
                                            }
                                        }
                                    }
                                }
                            }

                            JToken nextLinkValue = responseDoc["nextLink"];
                            if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null)
                            {
                                string nextLinkInstance = ((string)nextLinkValue);
                                result.NextLink = nextLinkInstance;
                            }
                        }

                    }
                    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>
        /// Get a list of deployments.
        /// </summary>
        /// <param name='nextLink'>
        /// Required. NextLink from the previous successful call to List
        /// operation.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// List of deployments.
        /// </returns>
        public async Task<DeploymentListResult> ListNextAsync(string nextLink, CancellationToken cancellationToken)
        {
            // Validate
            if (nextLink == null)
            {
                throw new ArgumentNullException("nextLink");
            }

            // Tracing
            bool shouldTrace = TracingAdapter.IsEnabled;
            string invocationId = null;
            if (shouldTrace)
            {
                invocationId = TracingAdapter.NextInvocationId.ToString();
                Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
                tracingParameters.Add("nextLink", nextLink);
                TracingAdapter.Enter(invocationId, this, "ListNextAsync", tracingParameters);
            }

            // Construct URL
            string url = "";
            url = url + nextLink;
            url = url.Replace(" ", "%20");

            // Create HTTP transport objects
            HttpRequestMessage httpRequest = null;
            try
            {
                httpRequest = new HttpRequestMessage();
                httpRequest.Method = HttpMethod.Get;
                httpRequest.RequestUri = new Uri(url);

                // Set Headers

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

                // 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, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
                        if (shouldTrace)
                        {
                            TracingAdapter.Error(invocationId, ex);
                        }
                        throw ex;
                    }

                    // Create Result
                    DeploymentListResult result = null;
                    // Deserialize Response
                    if (statusCode == HttpStatusCode.OK)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
                        result = new DeploymentListResult();
                        JToken responseDoc = null;
                        if (string.IsNullOrEmpty(responseContent) == false)
                        {
                            responseDoc = JToken.Parse(responseContent);
                        }

                        if (responseDoc != null && responseDoc.Type != JTokenType.Null)
                        {
                            JToken valueArray = responseDoc["value"];
                            if (valueArray != null && valueArray.Type != JTokenType.Null)
                            {
                                foreach (JToken valueValue in ((JArray)valueArray))
                                {
                                    DeploymentExtended deploymentExtendedInstance = new DeploymentExtended();
                                    result.Deployments.Add(deploymentExtendedInstance);

                                    JToken idValue = valueValue["id"];
                                    if (idValue != null && idValue.Type != JTokenType.Null)
                                    {
                                        string idInstance = ((string)idValue);
                                        deploymentExtendedInstance.Id = idInstance;
                                    }

                                    JToken nameValue = valueValue["name"];
                                    if (nameValue != null && nameValue.Type != JTokenType.Null)
                                    {
                                        string nameInstance = ((string)nameValue);
                                        deploymentExtendedInstance.Name = nameInstance;
                                    }

                                    JToken propertiesValue = valueValue["properties"];
                                    if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
                                    {
                                        DeploymentPropertiesExtended propertiesInstance = new DeploymentPropertiesExtended();
                                        deploymentExtendedInstance.Properties = propertiesInstance;

                                        JToken provisioningStateValue = propertiesValue["provisioningState"];
                                        if (provisioningStateValue != null && provisioningStateValue.Type != JTokenType.Null)
                                        {
                                            string provisioningStateInstance = ((string)provisioningStateValue);
                                            propertiesInstance.ProvisioningState = provisioningStateInstance;
                                        }

                                        JToken correlationIdValue = propertiesValue["correlationId"];
                                        if (correlationIdValue != null && correlationIdValue.Type != JTokenType.Null)
                                        {
                                            string correlationIdInstance = ((string)correlationIdValue);
                                            propertiesInstance.CorrelationId = correlationIdInstance;
                                        }

                                        JToken timestampValue = propertiesValue["timestamp"];
                                        if (timestampValue != null && timestampValue.Type != JTokenType.Null)
                                        {
                                            DateTime timestampInstance = ((DateTime)timestampValue);
                                            propertiesInstance.Timestamp = timestampInstance;
                                        }

                                        JToken durationValue = propertiesValue["duration"];
                                        if (durationValue != null && durationValue.Type != JTokenType.Null)
                                        {
                                            TimeSpan durationInstance = XmlConvert.ToTimeSpan(((string)durationValue));
                                            propertiesInstance.Duration = durationInstance;
                                        }

                                        JToken outputsValue = propertiesValue["outputs"];
                                        if (outputsValue != null && outputsValue.Type != JTokenType.Null)
                                        {
                                            string outputsInstance = outputsValue.ToString(Newtonsoft.Json.Formatting.Indented);
                                            propertiesInstance.Outputs = outputsInstance;
                                        }

                                        JToken providersArray = propertiesValue["providers"];
                                        if (providersArray != null && providersArray.Type != JTokenType.Null)
                                        {
                                            foreach (JToken providersValue in ((JArray)providersArray))
                                            {
                                                Provider providerInstance = new Provider();
                                                propertiesInstance.Providers.Add(providerInstance);

                                                JToken idValue2 = providersValue["id"];
                                                if (idValue2 != null && idValue2.Type != JTokenType.Null)
                                                {
                                                    string idInstance2 = ((string)idValue2);
                                                    providerInstance.Id = idInstance2;
                                                }

                                                JToken namespaceValue = providersValue["namespace"];
                                                if (namespaceValue != null && namespaceValue.Type != JTokenType.Null)
                                                {
                                                    string namespaceInstance = ((string)namespaceValue);
                                                    providerInstance.Namespace = namespaceInstance;
                                                }

                                                JToken registrationStateValue = providersValue["registrationState"];
                                                if (registrationStateValue != null && registrationStateValue.Type != JTokenType.Null)
                                                {
                                                    string registrationStateInstance = ((string)registrationStateValue);
                                                    providerInstance.RegistrationState = registrationStateInstance;
                                                }

                                                JToken resourceTypesArray = providersValue["resourceTypes"];
                                                if (resourceTypesArray != null && resourceTypesArray.Type != JTokenType.Null)
                                                {
                                                    foreach (JToken resourceTypesValue in ((JArray)resourceTypesArray))
                                                    {
                                                        ProviderResourceType providerResourceTypeInstance = new ProviderResourceType();
                                                        providerInstance.ResourceTypes.Add(providerResourceTypeInstance);

                                                        JToken resourceTypeValue = resourceTypesValue["resourceType"];
                                                        if (resourceTypeValue != null && resourceTypeValue.Type != JTokenType.Null)
                                                        {
                                                            string resourceTypeInstance = ((string)resourceTypeValue);
                                                            providerResourceTypeInstance.Name = resourceTypeInstance;
                                                        }

                                                        JToken locationsArray = resourceTypesValue["locations"];
                                                        if (locationsArray != null && locationsArray.Type != JTokenType.Null)
                                                        {
                                                            foreach (JToken locationsValue in ((JArray)locationsArray))
                                                            {
                                                                providerResourceTypeInstance.Locations.Add(((string)locationsValue));
                                                            }
                                                        }

                                                        JToken apiVersionsArray = resourceTypesValue["apiVersions"];
                                                        if (apiVersionsArray != null && apiVersionsArray.Type != JTokenType.Null)
                                                        {
                                                            foreach (JToken apiVersionsValue in ((JArray)apiVersionsArray))
                                                            {
                                                                providerResourceTypeInstance.ApiVersions.Add(((string)apiVersionsValue));
                                                            }
                                                        }

                                                        JToken propertiesSequenceElement = ((JToken)resourceTypesValue["properties"]);
                                                        if (propertiesSequenceElement != null && propertiesSequenceElement.Type != JTokenType.Null)
                                                        {
                                                            foreach (JProperty property in propertiesSequenceElement)
                                                            {
                                                                string propertiesKey = ((string)property.Name);
                                                                string propertiesValue2 = ((string)property.Value);
                                                                providerResourceTypeInstance.Properties.Add(propertiesKey, propertiesValue2);
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }

                                        JToken dependenciesArray = propertiesValue["dependencies"];
                                        if (dependenciesArray != null && dependenciesArray.Type != JTokenType.Null)
                                        {
                                            foreach (JToken dependenciesValue in ((JArray)dependenciesArray))
                                            {
                                                Dependency dependencyInstance = new Dependency();
                                                propertiesInstance.Dependencies.Add(dependencyInstance);

                                                JToken dependsOnArray = dependenciesValue["dependsOn"];
                                                if (dependsOnArray != null && dependsOnArray.Type != JTokenType.Null)
                                                {
                                                    foreach (JToken dependsOnValue in ((JArray)dependsOnArray))
                                                    {
                                                        BasicDependency basicDependencyInstance = new BasicDependency();
                                                        dependencyInstance.DependsOn.Add(basicDependencyInstance);

                                                        JToken idValue3 = dependsOnValue["id"];
                                                        if (idValue3 != null && idValue3.Type != JTokenType.Null)
                                                        {
                                                            string idInstance3 = ((string)idValue3);
                                                            basicDependencyInstance.Id = idInstance3;
                                                        }

                                                        JToken resourceTypeValue2 = dependsOnValue["resourceType"];
                                                        if (resourceTypeValue2 != null && resourceTypeValue2.Type != JTokenType.Null)
                                                        {
                                                            string resourceTypeInstance2 = ((string)resourceTypeValue2);
                                                            basicDependencyInstance.ResourceType = resourceTypeInstance2;
                                                        }

                                                        JToken resourceNameValue = dependsOnValue["resourceName"];
                                                        if (resourceNameValue != null && resourceNameValue.Type != JTokenType.Null)
                                                        {
                                                            string resourceNameInstance = ((string)resourceNameValue);
                                                            basicDependencyInstance.ResourceName = resourceNameInstance;
                                                        }
                                                    }
                                                }

                                                JToken idValue4 = dependenciesValue["id"];
                                                if (idValue4 != null && idValue4.Type != JTokenType.Null)
                                                {
                                                    string idInstance4 = ((string)idValue4);
                                                    dependencyInstance.Id = idInstance4;
                                                }

                                                JToken resourceTypeValue3 = dependenciesValue["resourceType"];
                                                if (resourceTypeValue3 != null && resourceTypeValue3.Type != JTokenType.Null)
                                                {
                                                    string resourceTypeInstance3 = ((string)resourceTypeValue3);
                                                    dependencyInstance.ResourceType = resourceTypeInstance3;
                                                }

                                                JToken resourceNameValue2 = dependenciesValue["resourceName"];
                                                if (resourceNameValue2 != null && resourceNameValue2.Type != JTokenType.Null)
                                                {
                                                    string resourceNameInstance2 = ((string)resourceNameValue2);
                                                    dependencyInstance.ResourceName = resourceNameInstance2;
                                                }
                                            }
                                        }

                                        JToken validatedResourcesArray = propertiesValue["validatedResources"];
                                        if (validatedResourcesArray != null && validatedResourcesArray.Type != JTokenType.Null)
                                        {
                                            foreach (JToken validatedResourcesValue in ((JArray)validatedResourcesArray))
                                            {
                                                DeploymentPreFlightResource deploymentPreFlightResourceInstance = new DeploymentPreFlightResource();
                                                propertiesInstance.ValidatedResources.Add(deploymentPreFlightResourceInstance);

                                                JToken apiVersionValue = validatedResourcesValue["apiVersion"];
                                                if (apiVersionValue != null && apiVersionValue.Type != JTokenType.Null)
                                                {
                                                    string apiVersionInstance = ((string)apiVersionValue);
                                                    deploymentPreFlightResourceInstance.ApiVersion = apiVersionInstance;
                                                }

                                                JToken dependsOnArray2 = validatedResourcesValue["dependsOn"];
                                                if (dependsOnArray2 != null && dependsOnArray2.Type != JTokenType.Null)
                                                {
                                                    foreach (JToken dependsOnValue2 in ((JArray)dependsOnArray2))
                                                    {
                                                        deploymentPreFlightResourceInstance.DependsOn.Add(((string)dependsOnValue2));
                                                    }
                                                }

                                                JToken propertiesValue3 = validatedResourcesValue["properties"];
                                                if (propertiesValue3 != null && propertiesValue3.Type != JTokenType.Null)
                                                {
                                                    string propertiesInstance2 = propertiesValue3.ToString(Newtonsoft.Json.Formatting.Indented);
                                                    deploymentPreFlightResourceInstance.Properties = propertiesInstance2;
                                                }

                                                JToken provisioningStateValue2 = validatedResourcesValue["provisioningState"];
                                                if (provisioningStateValue2 != null && provisioningStateValue2.Type != JTokenType.Null)
                                                {
                                                    string provisioningStateInstance2 = ((string)provisioningStateValue2);
                                                    deploymentPreFlightResourceInstance.ProvisioningState = provisioningStateInstance2;
                                                }

                                                JToken planValue = validatedResourcesValue["plan"];
                                                if (planValue != null && planValue.Type != JTokenType.Null)
                                                {
                                                    Plan planInstance = new Plan();
                                                    deploymentPreFlightResourceInstance.Plan = planInstance;

                                                    JToken nameValue2 = planValue["name"];
                                                    if (nameValue2 != null && nameValue2.Type != JTokenType.Null)
                                                    {
                                                        string nameInstance2 = ((string)nameValue2);
                                                        planInstance.Name = nameInstance2;
                                                    }

                                                    JToken publisherValue = planValue["publisher"];
                                                    if (publisherValue != null && publisherValue.Type != JTokenType.Null)
                                                    {
                                                        string publisherInstance = ((string)publisherValue);
                                                        planInstance.Publisher = publisherInstance;
                                                    }

                                                    JToken productValue = planValue["product"];
                                                    if (productValue != null && productValue.Type != JTokenType.Null)
                                                    {
                                                        string productInstance = ((string)productValue);
                                                        planInstance.Product = productInstance;
                                                    }

                                                    JToken promotionCodeValue = planValue["promotionCode"];
                                                    if (promotionCodeValue != null && promotionCodeValue.Type != JTokenType.Null)
                                                    {
                                                        string promotionCodeInstance = ((string)promotionCodeValue);
                                                        planInstance.PromotionCode = promotionCodeInstance;
                                                    }
                                                }

                                                JToken idValue5 = validatedResourcesValue["id"];
                                                if (idValue5 != null && idValue5.Type != JTokenType.Null)
                                                {
                                                    string idInstance5 = ((string)idValue5);
                                                    deploymentPreFlightResourceInstance.Id = idInstance5;
                                                }

                                                JToken nameValue3 = validatedResourcesValue["name"];
                                                if (nameValue3 != null && nameValue3.Type != JTokenType.Null)
                                                {
                                                    string nameInstance3 = ((string)nameValue3);
                                                    deploymentPreFlightResourceInstance.Name = nameInstance3;
                                                }

                                                JToken typeValue = validatedResourcesValue["type"];
                                                if (typeValue != null && typeValue.Type != JTokenType.Null)
                                                {
                                                    string typeInstance = ((string)typeValue);
                                                    deploymentPreFlightResourceInstance.Type = typeInstance;
                                                }

                                                JToken locationValue = validatedResourcesValue["location"];
                                                if (locationValue != null && locationValue.Type != JTokenType.Null)
                                                {
                                                    string locationInstance = ((string)locationValue);
                                                    deploymentPreFlightResourceInstance.Location = locationInstance;
                                                }

                                                JToken tagsSequenceElement = ((JToken)validatedResourcesValue["tags"]);
                                                if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
                                                {
                                                    foreach (JProperty property2 in tagsSequenceElement)
                                                    {
                                                        string tagsKey = ((string)property2.Name);
                                                        string tagsValue = ((string)property2.Value);
                                                        deploymentPreFlightResourceInstance.Tags.Add(tagsKey, tagsValue);
                                                    }
                                                }
                                            }
                                        }

                                        JToken debugSettingValue = propertiesValue["debugSetting"];
                                        if (debugSettingValue != null && debugSettingValue.Type != JTokenType.Null)
                                        {
                                            DeploymentDebugSetting debugSettingInstance = new DeploymentDebugSetting();
                                            propertiesInstance.DebugSettingResponse = debugSettingInstance;

                                            JToken detailLevelValue = debugSettingValue["detailLevel"];
                                            if (detailLevelValue != null && detailLevelValue.Type != JTokenType.Null)
                                            {
                                                string detailLevelInstance = ((string)detailLevelValue);
                                                debugSettingInstance.DeploymentDebugDetailLevel = detailLevelInstance;
                                            }
                                        }

                                        JToken templateValue = propertiesValue["template"];
                                        if (templateValue != null && templateValue.Type != JTokenType.Null)
                                        {
                                            string templateInstance = templateValue.ToString(Newtonsoft.Json.Formatting.Indented);
                                            propertiesInstance.Template = templateInstance;
                                        }

                                        JToken templateLinkValue = propertiesValue["templateLink"];
                                        if (templateLinkValue != null && templateLinkValue.Type != JTokenType.Null)
                                        {
                                            TemplateLink templateLinkInstance = new TemplateLink();
                                            propertiesInstance.TemplateLink = templateLinkInstance;

                                            JToken uriValue = templateLinkValue["uri"];
                                            if (uriValue != null && uriValue.Type != JTokenType.Null)
                                            {
                                                Uri uriInstance = TypeConversion.TryParseUri(((string)uriValue));
                                                templateLinkInstance.Uri = uriInstance;
                                            }

                                            JToken contentVersionValue = templateLinkValue["contentVersion"];
                                            if (contentVersionValue != null && contentVersionValue.Type != JTokenType.Null)
                                            {
                                                string contentVersionInstance = ((string)contentVersionValue);
                                                templateLinkInstance.ContentVersion = contentVersionInstance;
                                            }
                                        }

                                        JToken parametersValue = propertiesValue["parameters"];
                                        if (parametersValue != null && parametersValue.Type != JTokenType.Null)
                                        {
                                            string parametersInstance = parametersValue.ToString(Newtonsoft.Json.Formatting.Indented);
                                            propertiesInstance.Parameters = parametersInstance;
                                        }

                                        JToken parametersLinkValue = propertiesValue["parametersLink"];
                                        if (parametersLinkValue != null && parametersLinkValue.Type != JTokenType.Null)
                                        {
                                            ParametersLink parametersLinkInstance = new ParametersLink();
                                            propertiesInstance.ParametersLink = parametersLinkInstance;

                                            JToken uriValue2 = parametersLinkValue["uri"];
                                            if (uriValue2 != null && uriValue2.Type != JTokenType.Null)
                                            {
                                                Uri uriInstance2 = TypeConversion.TryParseUri(((string)uriValue2));
                                                parametersLinkInstance.Uri = uriInstance2;
                                            }

                                            JToken contentVersionValue2 = parametersLinkValue["contentVersion"];
                                            if (contentVersionValue2 != null && contentVersionValue2.Type != JTokenType.Null)
                                            {
                                                string contentVersionInstance2 = ((string)contentVersionValue2);
                                                parametersLinkInstance.ContentVersion = contentVersionInstance2;
                                            }
                                        }

                                        JToken modeValue = propertiesValue["mode"];
                                        if (modeValue != null && modeValue.Type != JTokenType.Null)
                                        {
                                            DeploymentMode modeInstance = ((DeploymentMode)Enum.Parse(typeof(DeploymentMode), ((string)modeValue), true));
                                            propertiesInstance.Mode = modeInstance;
                                        }

                                        JToken debugSettingValue2 = propertiesValue["debugSetting"];
                                        if (debugSettingValue2 != null && debugSettingValue2.Type != JTokenType.Null)
                                        {
                                            DeploymentDebugSetting debugSettingInstance2 = new DeploymentDebugSetting();
                                            propertiesInstance.DebugSetting = debugSettingInstance2;

                                            JToken detailLevelValue2 = debugSettingValue2["detailLevel"];
                                            if (detailLevelValue2 != null && detailLevelValue2.Type != JTokenType.Null)
                                            {
                                                string detailLevelInstance2 = ((string)detailLevelValue2);
                                                debugSettingInstance2.DeploymentDebugDetailLevel = detailLevelInstance2;
                                            }
                                        }
                                    }
                                }
                            }

                            JToken nextLinkValue = responseDoc["nextLink"];
                            if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null)
                            {
                                string nextLinkInstance = ((string)nextLinkValue);
                                result.NextLink = nextLinkInstance;
                            }
                        }

                    }
                    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>
        /// Validate a deployment template.
        /// </summary>
        /// <param name='resourceGroupName'>
        /// Required. The name of the resource group. The name is case
        /// insensitive.
        /// </param>
        /// <param name='deploymentName'>
        /// Required. The name of the deployment.
        /// </param>
        /// <param name='parameters'>
        /// Required. Deployment to validate.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// Information from validate template deployment response.
        /// </returns>
        public async Task<DeploymentValidateResponse> ValidateAsync(string resourceGroupName, string deploymentName, Deployment parameters, CancellationToken cancellationToken)
        {
            // Validate
            if (resourceGroupName == null)
            {
                throw new ArgumentNullException("resourceGroupName");
            }
            if (resourceGroupName != null && resourceGroupName.Length > 1000)
            {
                throw new ArgumentOutOfRangeException("resourceGroupName");
            }
            if (Regex.IsMatch(resourceGroupName, "^[-\\w\\._]+$") == false)
            {
                throw new ArgumentOutOfRangeException("resourceGroupName");
            }
            if (deploymentName == null)
            {
                throw new ArgumentNullException("deploymentName");
            }
            if (parameters == null)
            {
                throw new ArgumentNullException("parameters");
            }
            if (parameters.Properties != null)
            {
                if (parameters.Properties.DebugSetting != null)
                {
                    if (parameters.Properties.DebugSetting.DeploymentDebugDetailLevel == null)
                    {
                        throw new ArgumentNullException("parameters.Properties.DebugSetting.DeploymentDebugDetailLevel");
                    }
                }
                if (parameters.Properties.ParametersLink != null)
                {
                    if (parameters.Properties.ParametersLink.Uri == null)
                    {
                        throw new ArgumentNullException("parameters.Properties.ParametersLink.Uri");
                    }
                }
                if (parameters.Properties.TemplateLink != null)
                {
                    if (parameters.Properties.TemplateLink.Uri == null)
                    {
                        throw new ArgumentNullException("parameters.Properties.TemplateLink.Uri");
                    }
                }
            }

            // 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("deploymentName", deploymentName);
                tracingParameters.Add("parameters", parameters);
                TracingAdapter.Enter(invocationId, this, "ValidateAsync", 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/microsoft.resources/deployments/";
            url = url + Uri.EscapeDataString(deploymentName);
            url = url + "/validate";
            List<string> queryParameters = new List<string>();
            queryParameters.Add("api-version=2016-02-01");
            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.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 deploymentValue = new JObject();
                requestDoc = deploymentValue;

                if (parameters.Properties != null)
                {
                    JObject propertiesValue = new JObject();
                    deploymentValue["properties"] = propertiesValue;

                    if (parameters.Properties.Template != null)
                    {
                        propertiesValue["template"] = JObject.Parse(parameters.Properties.Template);
                    }

                    if (parameters.Properties.TemplateLink != null)
                    {
                        JObject templateLinkValue = new JObject();
                        propertiesValue["templateLink"] = templateLinkValue;

                        templateLinkValue["uri"] = parameters.Properties.TemplateLink.Uri.AbsoluteUri;

                        if (parameters.Properties.TemplateLink.ContentVersion != null)
                        {
                            templateLinkValue["contentVersion"] = parameters.Properties.TemplateLink.ContentVersion;
                        }
                    }

                    if (parameters.Properties.Parameters != null)
                    {
                        propertiesValue["parameters"] = JObject.Parse(parameters.Properties.Parameters);
                    }

                    if (parameters.Properties.ParametersLink != null)
                    {
                        JObject parametersLinkValue = new JObject();
                        propertiesValue["parametersLink"] = parametersLinkValue;

                        parametersLinkValue["uri"] = parameters.Properties.ParametersLink.Uri.AbsoluteUri;

                        if (parameters.Properties.ParametersLink.ContentVersion != null)
                        {
                            parametersLinkValue["contentVersion"] = parameters.Properties.ParametersLink.ContentVersion;
                        }
                    }

                    propertiesValue["mode"] = parameters.Properties.Mode.ToString();

                    if (parameters.Properties.DebugSetting != null)
                    {
                        JObject debugSettingValue = new JObject();
                        propertiesValue["debugSetting"] = debugSettingValue;

                        debugSettingValue["detailLevel"] = parameters.Properties.DebugSetting.DeploymentDebugDetailLevel;
                    }
                }

                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 && statusCode != HttpStatusCode.BadRequest)
                    {
                        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
                    DeploymentValidateResponse result = null;
                    // Deserialize Response
                    if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.BadRequest)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
                        result = new DeploymentValidateResponse();
                        JToken responseDoc = null;
                        if (string.IsNullOrEmpty(responseContent) == false)
                        {
                            responseDoc = JToken.Parse(responseContent);
                        }

                        if (responseDoc != null && responseDoc.Type != JTokenType.Null)
                        {
                            JToken errorValue = responseDoc["error"];
                            if (errorValue != null && errorValue.Type != JTokenType.Null)
                            {
                                ResourceManagementError errorInstance = new ResourceManagementError();
                                result.Error = errorInstance;

                                JToken codeValue = errorValue["code"];
                                if (codeValue != null && codeValue.Type != JTokenType.Null)
                                {
                                    string codeInstance = ((string)codeValue);
                                    errorInstance.Code = codeInstance;
                                }

                                JToken messageValue = errorValue["message"];
                                if (messageValue != null && messageValue.Type != JTokenType.Null)
                                {
                                    string messageInstance = ((string)messageValue);
                                    errorInstance.Message = messageInstance;
                                }

                                JToken targetValue = errorValue["target"];
                                if (targetValue != null && targetValue.Type != JTokenType.Null)
                                {
                                    string targetInstance = ((string)targetValue);
                                    errorInstance.Target = targetInstance;
                                }

                                JToken detailsValue = errorValue["details"];
                                if (detailsValue != null && detailsValue.Type != JTokenType.Null)
                                {
                                    string detailsInstance = detailsValue.ToString(Newtonsoft.Json.Formatting.Indented);
                                    errorInstance.Details = detailsInstance;
                                }
                            }

                            JToken propertiesValue2 = responseDoc["properties"];
                            if (propertiesValue2 != null && propertiesValue2.Type != JTokenType.Null)
                            {
                                DeploymentPropertiesExtended propertiesInstance = new DeploymentPropertiesExtended();
                                result.Properties = propertiesInstance;

                                JToken provisioningStateValue = propertiesValue2["provisioningState"];
                                if (provisioningStateValue != null && provisioningStateValue.Type != JTokenType.Null)
                                {
                                    string provisioningStateInstance = ((string)provisioningStateValue);
                                    propertiesInstance.ProvisioningState = provisioningStateInstance;
                                }

                                JToken correlationIdValue = propertiesValue2["correlationId"];
                                if (correlationIdValue != null && correlationIdValue.Type != JTokenType.Null)
                                {
                                    string correlationIdInstance = ((string)correlationIdValue);
                                    propertiesInstance.CorrelationId = correlationIdInstance;
                                }

                                JToken timestampValue = propertiesValue2["timestamp"];
                                if (timestampValue != null && timestampValue.Type != JTokenType.Null)
                                {
                                    DateTime timestampInstance = ((DateTime)timestampValue);
                                    propertiesInstance.Timestamp = timestampInstance;
                                }

                                JToken durationValue = propertiesValue2["duration"];
                                if (durationValue != null && durationValue.Type != JTokenType.Null)
                                {
                                    TimeSpan durationInstance = XmlConvert.ToTimeSpan(((string)durationValue));
                                    propertiesInstance.Duration = durationInstance;
                                }

                                JToken outputsValue = propertiesValue2["outputs"];
                                if (outputsValue != null && outputsValue.Type != JTokenType.Null)
                                {
                                    string outputsInstance = outputsValue.ToString(Newtonsoft.Json.Formatting.Indented);
                                    propertiesInstance.Outputs = outputsInstance;
                                }

                                JToken providersArray = propertiesValue2["providers"];
                                if (providersArray != null && providersArray.Type != JTokenType.Null)
                                {
                                    foreach (JToken providersValue in ((JArray)providersArray))
                                    {
                                        Provider providerInstance = new Provider();
                                        propertiesInstance.Providers.Add(providerInstance);

                                        JToken idValue = providersValue["id"];
                                        if (idValue != null && idValue.Type != JTokenType.Null)
                                        {
                                            string idInstance = ((string)idValue);
                                            providerInstance.Id = idInstance;
                                        }

                                        JToken namespaceValue = providersValue["namespace"];
                                        if (namespaceValue != null && namespaceValue.Type != JTokenType.Null)
                                        {
                                            string namespaceInstance = ((string)namespaceValue);
                                            providerInstance.Namespace = namespaceInstance;
                                        }

                                        JToken registrationStateValue = providersValue["registrationState"];
                                        if (registrationStateValue != null && registrationStateValue.Type != JTokenType.Null)
                                        {
                                            string registrationStateInstance = ((string)registrationStateValue);
                                            providerInstance.RegistrationState = registrationStateInstance;
                                        }

                                        JToken resourceTypesArray = providersValue["resourceTypes"];
                                        if (resourceTypesArray != null && resourceTypesArray.Type != JTokenType.Null)
                                        {
                                            foreach (JToken resourceTypesValue in ((JArray)resourceTypesArray))
                                            {
                                                ProviderResourceType providerResourceTypeInstance = new ProviderResourceType();
                                                providerInstance.ResourceTypes.Add(providerResourceTypeInstance);

                                                JToken resourceTypeValue = resourceTypesValue["resourceType"];
                                                if (resourceTypeValue != null && resourceTypeValue.Type != JTokenType.Null)
                                                {
                                                    string resourceTypeInstance = ((string)resourceTypeValue);
                                                    providerResourceTypeInstance.Name = resourceTypeInstance;
                                                }

                                                JToken locationsArray = resourceTypesValue["locations"];
                                                if (locationsArray != null && locationsArray.Type != JTokenType.Null)
                                                {
                                                    foreach (JToken locationsValue in ((JArray)locationsArray))
                                                    {
                                                        providerResourceTypeInstance.Locations.Add(((string)locationsValue));
                                                    }
                                                }

                                                JToken apiVersionsArray = resourceTypesValue["apiVersions"];
                                                if (apiVersionsArray != null && apiVersionsArray.Type != JTokenType.Null)
                                                {
                                                    foreach (JToken apiVersionsValue in ((JArray)apiVersionsArray))
                                                    {
                                                        providerResourceTypeInstance.ApiVersions.Add(((string)apiVersionsValue));
                                                    }
                                                }

                                                JToken propertiesSequenceElement = ((JToken)resourceTypesValue["properties"]);
                                                if (propertiesSequenceElement != null && propertiesSequenceElement.Type != JTokenType.Null)
                                                {
                                                    foreach (JProperty property in propertiesSequenceElement)
                                                    {
                                                        string propertiesKey = ((string)property.Name);
                                                        string propertiesValue3 = ((string)property.Value);
                                                        providerResourceTypeInstance.Properties.Add(propertiesKey, propertiesValue3);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }

                                JToken dependenciesArray = propertiesValue2["dependencies"];
                                if (dependenciesArray != null && dependenciesArray.Type != JTokenType.Null)
                                {
                                    foreach (JToken dependenciesValue in ((JArray)dependenciesArray))
                                    {
                                        Dependency dependencyInstance = new Dependency();
                                        propertiesInstance.Dependencies.Add(dependencyInstance);

                                        JToken dependsOnArray = dependenciesValue["dependsOn"];
                                        if (dependsOnArray != null && dependsOnArray.Type != JTokenType.Null)
                                        {
                                            foreach (JToken dependsOnValue in ((JArray)dependsOnArray))
                                            {
                                                BasicDependency basicDependencyInstance = new BasicDependency();
                                                dependencyInstance.DependsOn.Add(basicDependencyInstance);

                                                JToken idValue2 = dependsOnValue["id"];
                                                if (idValue2 != null && idValue2.Type != JTokenType.Null)
                                                {
                                                    string idInstance2 = ((string)idValue2);
                                                    basicDependencyInstance.Id = idInstance2;
                                                }

                                                JToken resourceTypeValue2 = dependsOnValue["resourceType"];
                                                if (resourceTypeValue2 != null && resourceTypeValue2.Type != JTokenType.Null)
                                                {
                                                    string resourceTypeInstance2 = ((string)resourceTypeValue2);
                                                    basicDependencyInstance.ResourceType = resourceTypeInstance2;
                                                }

                                                JToken resourceNameValue = dependsOnValue["resourceName"];
                                                if (resourceNameValue != null && resourceNameValue.Type != JTokenType.Null)
                                                {
                                                    string resourceNameInstance = ((string)resourceNameValue);
                                                    basicDependencyInstance.ResourceName = resourceNameInstance;
                                                }
                                            }
                                        }

                                        JToken idValue3 = dependenciesValue["id"];
                                        if (idValue3 != null && idValue3.Type != JTokenType.Null)
                                        {
                                            string idInstance3 = ((string)idValue3);
                                            dependencyInstance.Id = idInstance3;
                                        }

                                        JToken resourceTypeValue3 = dependenciesValue["resourceType"];
                                        if (resourceTypeValue3 != null && resourceTypeValue3.Type != JTokenType.Null)
                                        {
                                            string resourceTypeInstance3 = ((string)resourceTypeValue3);
                                            dependencyInstance.ResourceType = resourceTypeInstance3;
                                        }

                                        JToken resourceNameValue2 = dependenciesValue["resourceName"];
                                        if (resourceNameValue2 != null && resourceNameValue2.Type != JTokenType.Null)
                                        {
                                            string resourceNameInstance2 = ((string)resourceNameValue2);
                                            dependencyInstance.ResourceName = resourceNameInstance2;
                                        }
                                    }
                                }

                                JToken validatedResourcesArray = propertiesValue2["validatedResources"];
                                if (validatedResourcesArray != null && validatedResourcesArray.Type != JTokenType.Null)
                                {
                                    foreach (JToken validatedResourcesValue in ((JArray)validatedResourcesArray))
                                    {
                                        DeploymentPreFlightResource deploymentPreFlightResourceInstance = new DeploymentPreFlightResource();
                                        propertiesInstance.ValidatedResources.Add(deploymentPreFlightResourceInstance);

                                        JToken apiVersionValue = validatedResourcesValue["apiVersion"];
                                        if (apiVersionValue != null && apiVersionValue.Type != JTokenType.Null)
                                        {
                                            string apiVersionInstance = ((string)apiVersionValue);
                                            deploymentPreFlightResourceInstance.ApiVersion = apiVersionInstance;
                                        }

                                        JToken dependsOnArray2 = validatedResourcesValue["dependsOn"];
                                        if (dependsOnArray2 != null && dependsOnArray2.Type != JTokenType.Null)
                                        {
                                            foreach (JToken dependsOnValue2 in ((JArray)dependsOnArray2))
                                            {
                                                deploymentPreFlightResourceInstance.DependsOn.Add(((string)dependsOnValue2));
                                            }
                                        }

                                        JToken propertiesValue4 = validatedResourcesValue["properties"];
                                        if (propertiesValue4 != null && propertiesValue4.Type != JTokenType.Null)
                                        {
                                            string propertiesInstance2 = propertiesValue4.ToString(Newtonsoft.Json.Formatting.Indented);
                                            deploymentPreFlightResourceInstance.Properties = propertiesInstance2;
                                        }

                                        JToken provisioningStateValue2 = validatedResourcesValue["provisioningState"];
                                        if (provisioningStateValue2 != null && provisioningStateValue2.Type != JTokenType.Null)
                                        {
                                            string provisioningStateInstance2 = ((string)provisioningStateValue2);
                                            deploymentPreFlightResourceInstance.ProvisioningState = provisioningStateInstance2;
                                        }

                                        JToken planValue = validatedResourcesValue["plan"];
                                        if (planValue != null && planValue.Type != JTokenType.Null)
                                        {
                                            Plan planInstance = new Plan();
                                            deploymentPreFlightResourceInstance.Plan = planInstance;

                                            JToken nameValue = planValue["name"];
                                            if (nameValue != null && nameValue.Type != JTokenType.Null)
                                            {
                                                string nameInstance = ((string)nameValue);
                                                planInstance.Name = nameInstance;
                                            }

                                            JToken publisherValue = planValue["publisher"];
                                            if (publisherValue != null && publisherValue.Type != JTokenType.Null)
                                            {
                                                string publisherInstance = ((string)publisherValue);
                                                planInstance.Publisher = publisherInstance;
                                            }

                                            JToken productValue = planValue["product"];
                                            if (productValue != null && productValue.Type != JTokenType.Null)
                                            {
                                                string productInstance = ((string)productValue);
                                                planInstance.Product = productInstance;
                                            }

                                            JToken promotionCodeValue = planValue["promotionCode"];
                                            if (promotionCodeValue != null && promotionCodeValue.Type != JTokenType.Null)
                                            {
                                                string promotionCodeInstance = ((string)promotionCodeValue);
                                                planInstance.PromotionCode = promotionCodeInstance;
                                            }
                                        }

                                        JToken idValue4 = validatedResourcesValue["id"];
                                        if (idValue4 != null && idValue4.Type != JTokenType.Null)
                                        {
                                            string idInstance4 = ((string)idValue4);
                                            deploymentPreFlightResourceInstance.Id = idInstance4;
                                        }

                                        JToken nameValue2 = validatedResourcesValue["name"];
                                        if (nameValue2 != null && nameValue2.Type != JTokenType.Null)
                                        {
                                            string nameInstance2 = ((string)nameValue2);
                                            deploymentPreFlightResourceInstance.Name = nameInstance2;
                                        }

                                        JToken typeValue = validatedResourcesValue["type"];
                                        if (typeValue != null && typeValue.Type != JTokenType.Null)
                                        {
                                            string typeInstance = ((string)typeValue);
                                            deploymentPreFlightResourceInstance.Type = typeInstance;
                                        }

                                        JToken locationValue = validatedResourcesValue["location"];
                                        if (locationValue != null && locationValue.Type != JTokenType.Null)
                                        {
                                            string locationInstance = ((string)locationValue);
                                            deploymentPreFlightResourceInstance.Location = locationInstance;
                                        }

                                        JToken tagsSequenceElement = ((JToken)validatedResourcesValue["tags"]);
                                        if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
                                        {
                                            foreach (JProperty property2 in tagsSequenceElement)
                                            {
                                                string tagsKey = ((string)property2.Name);
                                                string tagsValue = ((string)property2.Value);
                                                deploymentPreFlightResourceInstance.Tags.Add(tagsKey, tagsValue);
                                            }
                                        }
                                    }
                                }

                                JToken debugSettingValue2 = propertiesValue2["debugSetting"];
                                if (debugSettingValue2 != null && debugSettingValue2.Type != JTokenType.Null)
                                {
                                    DeploymentDebugSetting debugSettingInstance = new DeploymentDebugSetting();
                                    propertiesInstance.DebugSettingResponse = debugSettingInstance;

                                    JToken detailLevelValue = debugSettingValue2["detailLevel"];
                                    if (detailLevelValue != null && detailLevelValue.Type != JTokenType.Null)
                                    {
                                        string detailLevelInstance = ((string)detailLevelValue);
                                        debugSettingInstance.DeploymentDebugDetailLevel = detailLevelInstance;
                                    }
                                }

                                JToken templateValue = propertiesValue2["template"];
                                if (templateValue != null && templateValue.Type != JTokenType.Null)
                                {
                                    string templateInstance = templateValue.ToString(Newtonsoft.Json.Formatting.Indented);
                                    propertiesInstance.Template = templateInstance;
                                }

                                JToken templateLinkValue2 = propertiesValue2["templateLink"];
                                if (templateLinkValue2 != null && templateLinkValue2.Type != JTokenType.Null)
                                {
                                    TemplateLink templateLinkInstance = new TemplateLink();
                                    propertiesInstance.TemplateLink = templateLinkInstance;

                                    JToken uriValue = templateLinkValue2["uri"];
                                    if (uriValue != null && uriValue.Type != JTokenType.Null)
                                    {
                                        Uri uriInstance = TypeConversion.TryParseUri(((string)uriValue));
                                        templateLinkInstance.Uri = uriInstance;
                                    }

                                    JToken contentVersionValue = templateLinkValue2["contentVersion"];
                                    if (contentVersionValue != null && contentVersionValue.Type != JTokenType.Null)
                                    {
                                        string contentVersionInstance = ((string)contentVersionValue);
                                        templateLinkInstance.ContentVersion = contentVersionInstance;
                                    }
                                }

                                JToken parametersValue = propertiesValue2["parameters"];
                                if (parametersValue != null && parametersValue.Type != JTokenType.Null)
                                {
                                    string parametersInstance = parametersValue.ToString(Newtonsoft.Json.Formatting.Indented);
                                    propertiesInstance.Parameters = parametersInstance;
                                }

                                JToken parametersLinkValue2 = propertiesValue2["parametersLink"];
                                if (parametersLinkValue2 != null && parametersLinkValue2.Type != JTokenType.Null)
                                {
                                    ParametersLink parametersLinkInstance = new ParametersLink();
                                    propertiesInstance.ParametersLink = parametersLinkInstance;

                                    JToken uriValue2 = parametersLinkValue2["uri"];
                                    if (uriValue2 != null && uriValue2.Type != JTokenType.Null)
                                    {
                                        Uri uriInstance2 = TypeConversion.TryParseUri(((string)uriValue2));
                                        parametersLinkInstance.Uri = uriInstance2;
                                    }

                                    JToken contentVersionValue2 = parametersLinkValue2["contentVersion"];
                                    if (contentVersionValue2 != null && contentVersionValue2.Type != JTokenType.Null)
                                    {
                                        string contentVersionInstance2 = ((string)contentVersionValue2);
                                        parametersLinkInstance.ContentVersion = contentVersionInstance2;
                                    }
                                }

                                JToken modeValue = propertiesValue2["mode"];
                                if (modeValue != null && modeValue.Type != JTokenType.Null)
                                {
                                    DeploymentMode modeInstance = ((DeploymentMode)Enum.Parse(typeof(DeploymentMode), ((string)modeValue), true));
                                    propertiesInstance.Mode = modeInstance;
                                }

                                JToken debugSettingValue3 = propertiesValue2["debugSetting"];
                                if (debugSettingValue3 != null && debugSettingValue3.Type != JTokenType.Null)
                                {
                                    DeploymentDebugSetting debugSettingInstance2 = new DeploymentDebugSetting();
                                    propertiesInstance.DebugSetting = debugSettingInstance2;

                                    JToken detailLevelValue2 = debugSettingValue3["detailLevel"];
                                    if (detailLevelValue2 != null && detailLevelValue2.Type != JTokenType.Null)
                                    {
                                        string detailLevelInstance2 = ((string)detailLevelValue2);
                                        debugSettingInstance2.DeploymentDebugDetailLevel = detailLevelInstance2;
                                    }
                                }
                            }
                        }

                    }
                    result.StatusCode = statusCode;
                    if (httpResponse.Headers.Contains("x-ms-request-id"))
                    {
                        result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
                    }
                    if (statusCode == HttpStatusCode.OK)
                    {
                        result.IsValid = true;
                    }

                    if (shouldTrace)
                    {
                        TracingAdapter.Exit(invocationId, result);
                    }
                    return result;
                }
                finally
                {
                    if (httpResponse != null)
                    {
                        httpResponse.Dispose();
                    }
                }
            }
            finally
            {
                if (httpRequest != null)
                {
                    httpRequest.Dispose();
                }
            }
        }
    }
}