// Copyright (c) Microsoft and contributors.  All rights reserved.
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// 
// See the License for the specific language governing permissions and
// limitations under the License.
// 
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.

namespace Microsoft.Azure.Batch.Protocol
{
    using System;
    using System.Linq;
    using System.Collections.Generic;
    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 Microsoft.Rest;
    using Microsoft.Rest.Serialization;
    using Newtonsoft.Json;
    using Microsoft.Rest.Azure;
    using Models;

    /// <summary>
    /// PoolOperations operations.
    /// </summary>
    internal partial class PoolOperations : IServiceOperations<BatchServiceClient>, IPoolOperations
    {
        /// <summary>
        /// Initializes a new instance of the PoolOperations class.
        /// </summary>
        /// <param name='client'>
        /// Reference to the service client.
        /// </param>
        /// <exception cref="ArgumentNullException">
        /// Thrown when a required parameter is null
        /// </exception>
        internal PoolOperations(BatchServiceClient client)
        {
            if (client == null) 
            {
                throw new ArgumentNullException("client");
            }
            this.Client = client;
        }

        /// <summary>
        /// Gets a reference to the BatchServiceClient
        /// </summary>
        public BatchServiceClient Client { get; private set; }

        /// <summary>
        /// Lists the usage metrics, aggregated by pool across individual time
        /// intervals, for the specified account.
        /// </summary>
        /// <param name='poolListPoolUsageMetricsOptions'>
        /// Additional parameters for the operation
        /// </param>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="BatchErrorException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public async Task<AzureOperationResponse<IPage<PoolUsageMetrics>,PoolListPoolUsageMetricsHeaders>> ListPoolUsageMetricsWithHttpMessagesAsync(PoolListPoolUsageMetricsOptions poolListPoolUsageMetricsOptions = default(PoolListPoolUsageMetricsOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (this.Client.ApiVersion == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
            }
            DateTime? startTime = default(DateTime?);
            if (poolListPoolUsageMetricsOptions != null)
            {
                startTime = poolListPoolUsageMetricsOptions.StartTime;
            }
            DateTime? endTime = default(DateTime?);
            if (poolListPoolUsageMetricsOptions != null)
            {
                endTime = poolListPoolUsageMetricsOptions.EndTime;
            }
            string filter = default(string);
            if (poolListPoolUsageMetricsOptions != null)
            {
                filter = poolListPoolUsageMetricsOptions.Filter;
            }
            int? maxResults = default(int?);
            if (poolListPoolUsageMetricsOptions != null)
            {
                maxResults = poolListPoolUsageMetricsOptions.MaxResults;
            }
            int? timeout = default(int?);
            if (poolListPoolUsageMetricsOptions != null)
            {
                timeout = poolListPoolUsageMetricsOptions.Timeout;
            }
            string clientRequestId = default(string);
            if (poolListPoolUsageMetricsOptions != null)
            {
                clientRequestId = poolListPoolUsageMetricsOptions.ClientRequestId;
            }
            bool? returnClientRequestId = default(bool?);
            if (poolListPoolUsageMetricsOptions != null)
            {
                returnClientRequestId = poolListPoolUsageMetricsOptions.ReturnClientRequestId;
            }
            DateTime? ocpDate = default(DateTime?);
            if (poolListPoolUsageMetricsOptions != null)
            {
                ocpDate = poolListPoolUsageMetricsOptions.OcpDate;
            }
            // Tracing
            bool _shouldTrace = ServiceClientTracing.IsEnabled;
            string _invocationId = null;
            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
                tracingParameters.Add("startTime", startTime);
                tracingParameters.Add("endTime", endTime);
                tracingParameters.Add("filter", filter);
                tracingParameters.Add("maxResults", maxResults);
                tracingParameters.Add("timeout", timeout);
                tracingParameters.Add("clientRequestId", clientRequestId);
                tracingParameters.Add("returnClientRequestId", returnClientRequestId);
                tracingParameters.Add("ocpDate", ocpDate);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "ListPoolUsageMetrics", tracingParameters);
            }
            // Construct URL
            var _baseUrl = this.Client.BaseUri.AbsoluteUri;
            var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "poolusagemetrics").ToString();
            List<string> _queryParameters = new List<string>();
            if (this.Client.ApiVersion != null)
            {
                _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
            }
            if (startTime != null)
            {
                _queryParameters.Add(string.Format("starttime={0}", Uri.EscapeDataString(SafeJsonConvert.SerializeObject(startTime, this.Client.SerializationSettings).Trim('"'))));
            }
            if (endTime != null)
            {
                _queryParameters.Add(string.Format("endtime={0}", Uri.EscapeDataString(SafeJsonConvert.SerializeObject(endTime, this.Client.SerializationSettings).Trim('"'))));
            }
            if (filter != null)
            {
                _queryParameters.Add(string.Format("$filter={0}", Uri.EscapeDataString(filter)));
            }
            if (maxResults != null)
            {
                _queryParameters.Add(string.Format("maxresults={0}", Uri.EscapeDataString(SafeJsonConvert.SerializeObject(maxResults, this.Client.SerializationSettings).Trim('"'))));
            }
            if (timeout != null)
            {
                _queryParameters.Add(string.Format("timeout={0}", Uri.EscapeDataString(SafeJsonConvert.SerializeObject(timeout, this.Client.SerializationSettings).Trim('"'))));
            }
            if (_queryParameters.Count > 0)
            {
                _url += "?" + string.Join("&", _queryParameters);
            }
            // Create HTTP transport objects
            HttpRequestMessage _httpRequest = new HttpRequestMessage();
            HttpResponseMessage _httpResponse = null;
            _httpRequest.Method = new HttpMethod("GET");
            _httpRequest.RequestUri = new Uri(_url);
            // Set Headers
            if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
            {
                _httpRequest.Headers.TryAddWithoutValidation("client-request-id", Guid.NewGuid().ToString());
            }
            if (this.Client.AcceptLanguage != null)
            {
                if (_httpRequest.Headers.Contains("accept-language"))
                {
                    _httpRequest.Headers.Remove("accept-language");
                }
                _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
            }
            if (clientRequestId != null)
            {
                if (_httpRequest.Headers.Contains("client-request-id"))
                {
                    _httpRequest.Headers.Remove("client-request-id");
                }
                _httpRequest.Headers.TryAddWithoutValidation("client-request-id", clientRequestId);
            }
            if (returnClientRequestId != null)
            {
                if (_httpRequest.Headers.Contains("return-client-request-id"))
                {
                    _httpRequest.Headers.Remove("return-client-request-id");
                }
                _httpRequest.Headers.TryAddWithoutValidation("return-client-request-id", SafeJsonConvert.SerializeObject(returnClientRequestId, this.Client.SerializationSettings).Trim('"'));
            }
            if (ocpDate != null)
            {
                if (_httpRequest.Headers.Contains("ocp-date"))
                {
                    _httpRequest.Headers.Remove("ocp-date");
                }
                _httpRequest.Headers.TryAddWithoutValidation("ocp-date", SafeJsonConvert.SerializeObject(ocpDate, new DateTimeRfc1123JsonConverter()).Trim('"'));
            }
            if (customHeaders != null)
            {
                foreach(var _header in customHeaders)
                {
                    if (_httpRequest.Headers.Contains(_header.Key))
                    {
                        _httpRequest.Headers.Remove(_header.Key);
                    }
                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
                }
            }

            // Serialize Request
            string _requestContent = null;
            // Set Credentials
            if (this.Client.Credentials != null)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            }
            // Send Request
            if (_shouldTrace)
            {
                ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            if (_shouldTrace)
            {
                ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
            }
            HttpStatusCode _statusCode = _httpResponse.StatusCode;
            cancellationToken.ThrowIfCancellationRequested();
            string _responseContent = null;
            if ((int)_statusCode != 200)
            {
                var ex = new BatchErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                try
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
                    BatchError _errorBody = SafeJsonConvert.DeserializeObject<BatchError>(_responseContent, this.Client.DeserializationSettings);
                    if (_errorBody != null)
                    {
                        ex.Body = _errorBody;
                    }
                }
                catch (JsonException)
                {
                    // Ignore the exception
                }
                ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
                ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
                if (_shouldTrace)
                {
                    ServiceClientTracing.Error(_invocationId, ex);
                }
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            // Create Result
            var _result = new AzureOperationResponse<IPage<PoolUsageMetrics>,PoolListPoolUsageMetricsHeaders>();
            _result.Request = _httpRequest;
            _result.Response = _httpResponse;
            if (_httpResponse.Headers.Contains("request-id"))
            {
                _result.RequestId = _httpResponse.Headers.GetValues("request-id").FirstOrDefault();
            }
            // Deserialize Response
            if ((int)_statusCode == 200)
            {
                _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
                try
                {
                    _result.Body = SafeJsonConvert.DeserializeObject<Page<PoolUsageMetrics>>(_responseContent, this.Client.DeserializationSettings);
                }
                catch (JsonException ex)
                {
                    _httpRequest.Dispose();
                    if (_httpResponse != null)
                    {
                        _httpResponse.Dispose();
                    }
                    throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
                }
            }
            try
            {
                _result.Headers = _httpResponse.GetHeadersAsJson().ToObject<PoolListPoolUsageMetricsHeaders>(JsonSerializer.Create(this.Client.DeserializationSettings));
            }
            catch (JsonException ex)
            {
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw new SerializationException("Unable to deserialize the headers.", _httpResponse.GetHeadersAsJson().ToString(), ex);
            }
            if (_shouldTrace)
            {
                ServiceClientTracing.Exit(_invocationId, _result);
            }
            return _result;
        }

        /// <summary>
        /// Gets lifetime summary statistics for all of the pools in the specified
        /// account.
        /// </summary>
        /// <remarks>
        /// Statistics are aggregated across all pools that have ever existed in the
        /// account, from account creation to the last update time of the statistics.
        /// </remarks>
        /// <param name='poolGetAllPoolsLifetimeStatisticsOptions'>
        /// Additional parameters for the operation
        /// </param>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="BatchErrorException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public async Task<AzureOperationResponse<PoolStatistics,PoolGetAllPoolsLifetimeStatisticsHeaders>> GetAllPoolsLifetimeStatisticsWithHttpMessagesAsync(PoolGetAllPoolsLifetimeStatisticsOptions poolGetAllPoolsLifetimeStatisticsOptions = default(PoolGetAllPoolsLifetimeStatisticsOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (this.Client.ApiVersion == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
            }
            int? timeout = default(int?);
            if (poolGetAllPoolsLifetimeStatisticsOptions != null)
            {
                timeout = poolGetAllPoolsLifetimeStatisticsOptions.Timeout;
            }
            string clientRequestId = default(string);
            if (poolGetAllPoolsLifetimeStatisticsOptions != null)
            {
                clientRequestId = poolGetAllPoolsLifetimeStatisticsOptions.ClientRequestId;
            }
            bool? returnClientRequestId = default(bool?);
            if (poolGetAllPoolsLifetimeStatisticsOptions != null)
            {
                returnClientRequestId = poolGetAllPoolsLifetimeStatisticsOptions.ReturnClientRequestId;
            }
            DateTime? ocpDate = default(DateTime?);
            if (poolGetAllPoolsLifetimeStatisticsOptions != null)
            {
                ocpDate = poolGetAllPoolsLifetimeStatisticsOptions.OcpDate;
            }
            // Tracing
            bool _shouldTrace = ServiceClientTracing.IsEnabled;
            string _invocationId = null;
            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
                tracingParameters.Add("timeout", timeout);
                tracingParameters.Add("clientRequestId", clientRequestId);
                tracingParameters.Add("returnClientRequestId", returnClientRequestId);
                tracingParameters.Add("ocpDate", ocpDate);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "GetAllPoolsLifetimeStatistics", tracingParameters);
            }
            // Construct URL
            var _baseUrl = this.Client.BaseUri.AbsoluteUri;
            var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "lifetimepoolstats").ToString();
            List<string> _queryParameters = new List<string>();
            if (this.Client.ApiVersion != null)
            {
                _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
            }
            if (timeout != null)
            {
                _queryParameters.Add(string.Format("timeout={0}", Uri.EscapeDataString(SafeJsonConvert.SerializeObject(timeout, this.Client.SerializationSettings).Trim('"'))));
            }
            if (_queryParameters.Count > 0)
            {
                _url += "?" + string.Join("&", _queryParameters);
            }
            // Create HTTP transport objects
            HttpRequestMessage _httpRequest = new HttpRequestMessage();
            HttpResponseMessage _httpResponse = null;
            _httpRequest.Method = new HttpMethod("GET");
            _httpRequest.RequestUri = new Uri(_url);
            // Set Headers
            if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
            {
                _httpRequest.Headers.TryAddWithoutValidation("client-request-id", Guid.NewGuid().ToString());
            }
            if (this.Client.AcceptLanguage != null)
            {
                if (_httpRequest.Headers.Contains("accept-language"))
                {
                    _httpRequest.Headers.Remove("accept-language");
                }
                _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
            }
            if (clientRequestId != null)
            {
                if (_httpRequest.Headers.Contains("client-request-id"))
                {
                    _httpRequest.Headers.Remove("client-request-id");
                }
                _httpRequest.Headers.TryAddWithoutValidation("client-request-id", clientRequestId);
            }
            if (returnClientRequestId != null)
            {
                if (_httpRequest.Headers.Contains("return-client-request-id"))
                {
                    _httpRequest.Headers.Remove("return-client-request-id");
                }
                _httpRequest.Headers.TryAddWithoutValidation("return-client-request-id", SafeJsonConvert.SerializeObject(returnClientRequestId, this.Client.SerializationSettings).Trim('"'));
            }
            if (ocpDate != null)
            {
                if (_httpRequest.Headers.Contains("ocp-date"))
                {
                    _httpRequest.Headers.Remove("ocp-date");
                }
                _httpRequest.Headers.TryAddWithoutValidation("ocp-date", SafeJsonConvert.SerializeObject(ocpDate, new DateTimeRfc1123JsonConverter()).Trim('"'));
            }
            if (customHeaders != null)
            {
                foreach(var _header in customHeaders)
                {
                    if (_httpRequest.Headers.Contains(_header.Key))
                    {
                        _httpRequest.Headers.Remove(_header.Key);
                    }
                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
                }
            }

            // Serialize Request
            string _requestContent = null;
            // Set Credentials
            if (this.Client.Credentials != null)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            }
            // Send Request
            if (_shouldTrace)
            {
                ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            if (_shouldTrace)
            {
                ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
            }
            HttpStatusCode _statusCode = _httpResponse.StatusCode;
            cancellationToken.ThrowIfCancellationRequested();
            string _responseContent = null;
            if ((int)_statusCode != 200)
            {
                var ex = new BatchErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                try
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
                    BatchError _errorBody = SafeJsonConvert.DeserializeObject<BatchError>(_responseContent, this.Client.DeserializationSettings);
                    if (_errorBody != null)
                    {
                        ex.Body = _errorBody;
                    }
                }
                catch (JsonException)
                {
                    // Ignore the exception
                }
                ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
                ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
                if (_shouldTrace)
                {
                    ServiceClientTracing.Error(_invocationId, ex);
                }
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            // Create Result
            var _result = new AzureOperationResponse<PoolStatistics,PoolGetAllPoolsLifetimeStatisticsHeaders>();
            _result.Request = _httpRequest;
            _result.Response = _httpResponse;
            if (_httpResponse.Headers.Contains("request-id"))
            {
                _result.RequestId = _httpResponse.Headers.GetValues("request-id").FirstOrDefault();
            }
            // Deserialize Response
            if ((int)_statusCode == 200)
            {
                _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
                try
                {
                    _result.Body = SafeJsonConvert.DeserializeObject<PoolStatistics>(_responseContent, this.Client.DeserializationSettings);
                }
                catch (JsonException ex)
                {
                    _httpRequest.Dispose();
                    if (_httpResponse != null)
                    {
                        _httpResponse.Dispose();
                    }
                    throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
                }
            }
            try
            {
                _result.Headers = _httpResponse.GetHeadersAsJson().ToObject<PoolGetAllPoolsLifetimeStatisticsHeaders>(JsonSerializer.Create(this.Client.DeserializationSettings));
            }
            catch (JsonException ex)
            {
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw new SerializationException("Unable to deserialize the headers.", _httpResponse.GetHeadersAsJson().ToString(), ex);
            }
            if (_shouldTrace)
            {
                ServiceClientTracing.Exit(_invocationId, _result);
            }
            return _result;
        }

        /// <summary>
        /// Adds a pool to the specified account.
        /// </summary>
        /// <param name='pool'>
        /// The pool to be added.
        /// </param>
        /// <param name='poolAddOptions'>
        /// Additional parameters for the operation
        /// </param>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="BatchErrorException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public async Task<AzureOperationHeaderResponse<PoolAddHeaders>> AddWithHttpMessagesAsync(PoolAddParameter pool, PoolAddOptions poolAddOptions = default(PoolAddOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (pool == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "pool");
            }
            if (pool != null)
            {
                pool.Validate();
            }
            if (this.Client.ApiVersion == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
            }
            int? timeout = default(int?);
            if (poolAddOptions != null)
            {
                timeout = poolAddOptions.Timeout;
            }
            string clientRequestId = default(string);
            if (poolAddOptions != null)
            {
                clientRequestId = poolAddOptions.ClientRequestId;
            }
            bool? returnClientRequestId = default(bool?);
            if (poolAddOptions != null)
            {
                returnClientRequestId = poolAddOptions.ReturnClientRequestId;
            }
            DateTime? ocpDate = default(DateTime?);
            if (poolAddOptions != null)
            {
                ocpDate = poolAddOptions.OcpDate;
            }
            // Tracing
            bool _shouldTrace = ServiceClientTracing.IsEnabled;
            string _invocationId = null;
            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
                tracingParameters.Add("pool", pool);
                tracingParameters.Add("timeout", timeout);
                tracingParameters.Add("clientRequestId", clientRequestId);
                tracingParameters.Add("returnClientRequestId", returnClientRequestId);
                tracingParameters.Add("ocpDate", ocpDate);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "Add", tracingParameters);
            }
            // Construct URL
            var _baseUrl = this.Client.BaseUri.AbsoluteUri;
            var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "pools").ToString();
            List<string> _queryParameters = new List<string>();
            if (this.Client.ApiVersion != null)
            {
                _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
            }
            if (timeout != null)
            {
                _queryParameters.Add(string.Format("timeout={0}", Uri.EscapeDataString(SafeJsonConvert.SerializeObject(timeout, this.Client.SerializationSettings).Trim('"'))));
            }
            if (_queryParameters.Count > 0)
            {
                _url += "?" + string.Join("&", _queryParameters);
            }
            // Create HTTP transport objects
            HttpRequestMessage _httpRequest = new HttpRequestMessage();
            HttpResponseMessage _httpResponse = null;
            _httpRequest.Method = new HttpMethod("POST");
            _httpRequest.RequestUri = new Uri(_url);
            // Set Headers
            if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
            {
                _httpRequest.Headers.TryAddWithoutValidation("client-request-id", Guid.NewGuid().ToString());
            }
            if (this.Client.AcceptLanguage != null)
            {
                if (_httpRequest.Headers.Contains("accept-language"))
                {
                    _httpRequest.Headers.Remove("accept-language");
                }
                _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
            }
            if (clientRequestId != null)
            {
                if (_httpRequest.Headers.Contains("client-request-id"))
                {
                    _httpRequest.Headers.Remove("client-request-id");
                }
                _httpRequest.Headers.TryAddWithoutValidation("client-request-id", clientRequestId);
            }
            if (returnClientRequestId != null)
            {
                if (_httpRequest.Headers.Contains("return-client-request-id"))
                {
                    _httpRequest.Headers.Remove("return-client-request-id");
                }
                _httpRequest.Headers.TryAddWithoutValidation("return-client-request-id", SafeJsonConvert.SerializeObject(returnClientRequestId, this.Client.SerializationSettings).Trim('"'));
            }
            if (ocpDate != null)
            {
                if (_httpRequest.Headers.Contains("ocp-date"))
                {
                    _httpRequest.Headers.Remove("ocp-date");
                }
                _httpRequest.Headers.TryAddWithoutValidation("ocp-date", SafeJsonConvert.SerializeObject(ocpDate, new DateTimeRfc1123JsonConverter()).Trim('"'));
            }
            if (customHeaders != null)
            {
                foreach(var _header in customHeaders)
                {
                    if (_httpRequest.Headers.Contains(_header.Key))
                    {
                        _httpRequest.Headers.Remove(_header.Key);
                    }
                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
                }
            }

            // Serialize Request
            string _requestContent = null;
            if(pool != null)
            {
                _requestContent = SafeJsonConvert.SerializeObject(pool, this.Client.SerializationSettings);
                _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8);
                _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; odata=minimalmetadata; charset=utf-8");
            }
            // Set Credentials
            if (this.Client.Credentials != null)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            }
            // Send Request
            if (_shouldTrace)
            {
                ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            if (_shouldTrace)
            {
                ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
            }
            HttpStatusCode _statusCode = _httpResponse.StatusCode;
            cancellationToken.ThrowIfCancellationRequested();
            string _responseContent = null;
            if ((int)_statusCode != 201)
            {
                var ex = new BatchErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                try
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
                    BatchError _errorBody = SafeJsonConvert.DeserializeObject<BatchError>(_responseContent, this.Client.DeserializationSettings);
                    if (_errorBody != null)
                    {
                        ex.Body = _errorBody;
                    }
                }
                catch (JsonException)
                {
                    // Ignore the exception
                }
                ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
                ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
                if (_shouldTrace)
                {
                    ServiceClientTracing.Error(_invocationId, ex);
                }
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            // Create Result
            var _result = new AzureOperationHeaderResponse<PoolAddHeaders>();
            _result.Request = _httpRequest;
            _result.Response = _httpResponse;
            if (_httpResponse.Headers.Contains("request-id"))
            {
                _result.RequestId = _httpResponse.Headers.GetValues("request-id").FirstOrDefault();
            }
            try
            {
                _result.Headers = _httpResponse.GetHeadersAsJson().ToObject<PoolAddHeaders>(JsonSerializer.Create(this.Client.DeserializationSettings));
            }
            catch (JsonException ex)
            {
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw new SerializationException("Unable to deserialize the headers.", _httpResponse.GetHeadersAsJson().ToString(), ex);
            }
            if (_shouldTrace)
            {
                ServiceClientTracing.Exit(_invocationId, _result);
            }
            return _result;
        }

        /// <summary>
        /// Lists all of the pools in the specified account.
        /// </summary>
        /// <param name='poolListOptions'>
        /// Additional parameters for the operation
        /// </param>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="BatchErrorException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public async Task<AzureOperationResponse<IPage<CloudPool>,PoolListHeaders>> ListWithHttpMessagesAsync(PoolListOptions poolListOptions = default(PoolListOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (this.Client.ApiVersion == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
            }
            string filter = default(string);
            if (poolListOptions != null)
            {
                filter = poolListOptions.Filter;
            }
            string select = default(string);
            if (poolListOptions != null)
            {
                select = poolListOptions.Select;
            }
            string expand = default(string);
            if (poolListOptions != null)
            {
                expand = poolListOptions.Expand;
            }
            int? maxResults = default(int?);
            if (poolListOptions != null)
            {
                maxResults = poolListOptions.MaxResults;
            }
            int? timeout = default(int?);
            if (poolListOptions != null)
            {
                timeout = poolListOptions.Timeout;
            }
            string clientRequestId = default(string);
            if (poolListOptions != null)
            {
                clientRequestId = poolListOptions.ClientRequestId;
            }
            bool? returnClientRequestId = default(bool?);
            if (poolListOptions != null)
            {
                returnClientRequestId = poolListOptions.ReturnClientRequestId;
            }
            DateTime? ocpDate = default(DateTime?);
            if (poolListOptions != null)
            {
                ocpDate = poolListOptions.OcpDate;
            }
            // Tracing
            bool _shouldTrace = ServiceClientTracing.IsEnabled;
            string _invocationId = null;
            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
                tracingParameters.Add("filter", filter);
                tracingParameters.Add("select", select);
                tracingParameters.Add("expand", expand);
                tracingParameters.Add("maxResults", maxResults);
                tracingParameters.Add("timeout", timeout);
                tracingParameters.Add("clientRequestId", clientRequestId);
                tracingParameters.Add("returnClientRequestId", returnClientRequestId);
                tracingParameters.Add("ocpDate", ocpDate);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
            }
            // Construct URL
            var _baseUrl = this.Client.BaseUri.AbsoluteUri;
            var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "pools").ToString();
            List<string> _queryParameters = new List<string>();
            if (this.Client.ApiVersion != null)
            {
                _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
            }
            if (filter != null)
            {
                _queryParameters.Add(string.Format("$filter={0}", Uri.EscapeDataString(filter)));
            }
            if (select != null)
            {
                _queryParameters.Add(string.Format("$select={0}", Uri.EscapeDataString(select)));
            }
            if (expand != null)
            {
                _queryParameters.Add(string.Format("$expand={0}", Uri.EscapeDataString(expand)));
            }
            if (maxResults != null)
            {
                _queryParameters.Add(string.Format("maxresults={0}", Uri.EscapeDataString(SafeJsonConvert.SerializeObject(maxResults, this.Client.SerializationSettings).Trim('"'))));
            }
            if (timeout != null)
            {
                _queryParameters.Add(string.Format("timeout={0}", Uri.EscapeDataString(SafeJsonConvert.SerializeObject(timeout, this.Client.SerializationSettings).Trim('"'))));
            }
            if (_queryParameters.Count > 0)
            {
                _url += "?" + string.Join("&", _queryParameters);
            }
            // Create HTTP transport objects
            HttpRequestMessage _httpRequest = new HttpRequestMessage();
            HttpResponseMessage _httpResponse = null;
            _httpRequest.Method = new HttpMethod("GET");
            _httpRequest.RequestUri = new Uri(_url);
            // Set Headers
            if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
            {
                _httpRequest.Headers.TryAddWithoutValidation("client-request-id", Guid.NewGuid().ToString());
            }
            if (this.Client.AcceptLanguage != null)
            {
                if (_httpRequest.Headers.Contains("accept-language"))
                {
                    _httpRequest.Headers.Remove("accept-language");
                }
                _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
            }
            if (clientRequestId != null)
            {
                if (_httpRequest.Headers.Contains("client-request-id"))
                {
                    _httpRequest.Headers.Remove("client-request-id");
                }
                _httpRequest.Headers.TryAddWithoutValidation("client-request-id", clientRequestId);
            }
            if (returnClientRequestId != null)
            {
                if (_httpRequest.Headers.Contains("return-client-request-id"))
                {
                    _httpRequest.Headers.Remove("return-client-request-id");
                }
                _httpRequest.Headers.TryAddWithoutValidation("return-client-request-id", SafeJsonConvert.SerializeObject(returnClientRequestId, this.Client.SerializationSettings).Trim('"'));
            }
            if (ocpDate != null)
            {
                if (_httpRequest.Headers.Contains("ocp-date"))
                {
                    _httpRequest.Headers.Remove("ocp-date");
                }
                _httpRequest.Headers.TryAddWithoutValidation("ocp-date", SafeJsonConvert.SerializeObject(ocpDate, new DateTimeRfc1123JsonConverter()).Trim('"'));
            }
            if (customHeaders != null)
            {
                foreach(var _header in customHeaders)
                {
                    if (_httpRequest.Headers.Contains(_header.Key))
                    {
                        _httpRequest.Headers.Remove(_header.Key);
                    }
                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
                }
            }

            // Serialize Request
            string _requestContent = null;
            // Set Credentials
            if (this.Client.Credentials != null)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            }
            // Send Request
            if (_shouldTrace)
            {
                ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            if (_shouldTrace)
            {
                ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
            }
            HttpStatusCode _statusCode = _httpResponse.StatusCode;
            cancellationToken.ThrowIfCancellationRequested();
            string _responseContent = null;
            if ((int)_statusCode != 200)
            {
                var ex = new BatchErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                try
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
                    BatchError _errorBody = SafeJsonConvert.DeserializeObject<BatchError>(_responseContent, this.Client.DeserializationSettings);
                    if (_errorBody != null)
                    {
                        ex.Body = _errorBody;
                    }
                }
                catch (JsonException)
                {
                    // Ignore the exception
                }
                ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
                ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
                if (_shouldTrace)
                {
                    ServiceClientTracing.Error(_invocationId, ex);
                }
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            // Create Result
            var _result = new AzureOperationResponse<IPage<CloudPool>,PoolListHeaders>();
            _result.Request = _httpRequest;
            _result.Response = _httpResponse;
            if (_httpResponse.Headers.Contains("request-id"))
            {
                _result.RequestId = _httpResponse.Headers.GetValues("request-id").FirstOrDefault();
            }
            // Deserialize Response
            if ((int)_statusCode == 200)
            {
                _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
                try
                {
                    _result.Body = SafeJsonConvert.DeserializeObject<Page<CloudPool>>(_responseContent, this.Client.DeserializationSettings);
                }
                catch (JsonException ex)
                {
                    _httpRequest.Dispose();
                    if (_httpResponse != null)
                    {
                        _httpResponse.Dispose();
                    }
                    throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
                }
            }
            try
            {
                _result.Headers = _httpResponse.GetHeadersAsJson().ToObject<PoolListHeaders>(JsonSerializer.Create(this.Client.DeserializationSettings));
            }
            catch (JsonException ex)
            {
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw new SerializationException("Unable to deserialize the headers.", _httpResponse.GetHeadersAsJson().ToString(), ex);
            }
            if (_shouldTrace)
            {
                ServiceClientTracing.Exit(_invocationId, _result);
            }
            return _result;
        }

        /// <summary>
        /// Deletes a pool from the specified account.
        /// </summary>
        /// <param name='poolId'>
        /// The id of the pool to delete.
        /// </param>
        /// <param name='poolDeleteOptions'>
        /// Additional parameters for the operation
        /// </param>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="BatchErrorException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public async Task<AzureOperationHeaderResponse<PoolDeleteHeaders>> DeleteWithHttpMessagesAsync(string poolId, PoolDeleteOptions poolDeleteOptions = default(PoolDeleteOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (poolId == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "poolId");
            }
            if (this.Client.ApiVersion == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
            }
            int? timeout = default(int?);
            if (poolDeleteOptions != null)
            {
                timeout = poolDeleteOptions.Timeout;
            }
            string clientRequestId = default(string);
            if (poolDeleteOptions != null)
            {
                clientRequestId = poolDeleteOptions.ClientRequestId;
            }
            bool? returnClientRequestId = default(bool?);
            if (poolDeleteOptions != null)
            {
                returnClientRequestId = poolDeleteOptions.ReturnClientRequestId;
            }
            DateTime? ocpDate = default(DateTime?);
            if (poolDeleteOptions != null)
            {
                ocpDate = poolDeleteOptions.OcpDate;
            }
            string ifMatch = default(string);
            if (poolDeleteOptions != null)
            {
                ifMatch = poolDeleteOptions.IfMatch;
            }
            string ifNoneMatch = default(string);
            if (poolDeleteOptions != null)
            {
                ifNoneMatch = poolDeleteOptions.IfNoneMatch;
            }
            DateTime? ifModifiedSince = default(DateTime?);
            if (poolDeleteOptions != null)
            {
                ifModifiedSince = poolDeleteOptions.IfModifiedSince;
            }
            DateTime? ifUnmodifiedSince = default(DateTime?);
            if (poolDeleteOptions != null)
            {
                ifUnmodifiedSince = poolDeleteOptions.IfUnmodifiedSince;
            }
            // Tracing
            bool _shouldTrace = ServiceClientTracing.IsEnabled;
            string _invocationId = null;
            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
                tracingParameters.Add("poolId", poolId);
                tracingParameters.Add("timeout", timeout);
                tracingParameters.Add("clientRequestId", clientRequestId);
                tracingParameters.Add("returnClientRequestId", returnClientRequestId);
                tracingParameters.Add("ocpDate", ocpDate);
                tracingParameters.Add("ifMatch", ifMatch);
                tracingParameters.Add("ifNoneMatch", ifNoneMatch);
                tracingParameters.Add("ifModifiedSince", ifModifiedSince);
                tracingParameters.Add("ifUnmodifiedSince", ifUnmodifiedSince);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "Delete", tracingParameters);
            }
            // Construct URL
            var _baseUrl = this.Client.BaseUri.AbsoluteUri;
            var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "pools/{poolId}").ToString();
            _url = _url.Replace("{poolId}", Uri.EscapeDataString(poolId));
            List<string> _queryParameters = new List<string>();
            if (this.Client.ApiVersion != null)
            {
                _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
            }
            if (timeout != null)
            {
                _queryParameters.Add(string.Format("timeout={0}", Uri.EscapeDataString(SafeJsonConvert.SerializeObject(timeout, this.Client.SerializationSettings).Trim('"'))));
            }
            if (_queryParameters.Count > 0)
            {
                _url += "?" + string.Join("&", _queryParameters);
            }
            // Create HTTP transport objects
            HttpRequestMessage _httpRequest = new HttpRequestMessage();
            HttpResponseMessage _httpResponse = null;
            _httpRequest.Method = new HttpMethod("DELETE");
            _httpRequest.RequestUri = new Uri(_url);
            // Set Headers
            if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
            {
                _httpRequest.Headers.TryAddWithoutValidation("client-request-id", Guid.NewGuid().ToString());
            }
            if (this.Client.AcceptLanguage != null)
            {
                if (_httpRequest.Headers.Contains("accept-language"))
                {
                    _httpRequest.Headers.Remove("accept-language");
                }
                _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
            }
            if (clientRequestId != null)
            {
                if (_httpRequest.Headers.Contains("client-request-id"))
                {
                    _httpRequest.Headers.Remove("client-request-id");
                }
                _httpRequest.Headers.TryAddWithoutValidation("client-request-id", clientRequestId);
            }
            if (returnClientRequestId != null)
            {
                if (_httpRequest.Headers.Contains("return-client-request-id"))
                {
                    _httpRequest.Headers.Remove("return-client-request-id");
                }
                _httpRequest.Headers.TryAddWithoutValidation("return-client-request-id", SafeJsonConvert.SerializeObject(returnClientRequestId, this.Client.SerializationSettings).Trim('"'));
            }
            if (ocpDate != null)
            {
                if (_httpRequest.Headers.Contains("ocp-date"))
                {
                    _httpRequest.Headers.Remove("ocp-date");
                }
                _httpRequest.Headers.TryAddWithoutValidation("ocp-date", SafeJsonConvert.SerializeObject(ocpDate, new DateTimeRfc1123JsonConverter()).Trim('"'));
            }
            if (ifMatch != null)
            {
                if (_httpRequest.Headers.Contains("If-Match"))
                {
                    _httpRequest.Headers.Remove("If-Match");
                }
                _httpRequest.Headers.TryAddWithoutValidation("If-Match", ifMatch);
            }
            if (ifNoneMatch != null)
            {
                if (_httpRequest.Headers.Contains("If-None-Match"))
                {
                    _httpRequest.Headers.Remove("If-None-Match");
                }
                _httpRequest.Headers.TryAddWithoutValidation("If-None-Match", ifNoneMatch);
            }
            if (ifModifiedSince != null)
            {
                if (_httpRequest.Headers.Contains("If-Modified-Since"))
                {
                    _httpRequest.Headers.Remove("If-Modified-Since");
                }
                _httpRequest.Headers.TryAddWithoutValidation("If-Modified-Since", SafeJsonConvert.SerializeObject(ifModifiedSince, new DateTimeRfc1123JsonConverter()).Trim('"'));
            }
            if (ifUnmodifiedSince != null)
            {
                if (_httpRequest.Headers.Contains("If-Unmodified-Since"))
                {
                    _httpRequest.Headers.Remove("If-Unmodified-Since");
                }
                _httpRequest.Headers.TryAddWithoutValidation("If-Unmodified-Since", SafeJsonConvert.SerializeObject(ifUnmodifiedSince, new DateTimeRfc1123JsonConverter()).Trim('"'));
            }
            if (customHeaders != null)
            {
                foreach(var _header in customHeaders)
                {
                    if (_httpRequest.Headers.Contains(_header.Key))
                    {
                        _httpRequest.Headers.Remove(_header.Key);
                    }
                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
                }
            }

            // Serialize Request
            string _requestContent = null;
            // Set Credentials
            if (this.Client.Credentials != null)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            }
            // Send Request
            if (_shouldTrace)
            {
                ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            if (_shouldTrace)
            {
                ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
            }
            HttpStatusCode _statusCode = _httpResponse.StatusCode;
            cancellationToken.ThrowIfCancellationRequested();
            string _responseContent = null;
            if ((int)_statusCode != 202)
            {
                var ex = new BatchErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                try
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
                    BatchError _errorBody = SafeJsonConvert.DeserializeObject<BatchError>(_responseContent, this.Client.DeserializationSettings);
                    if (_errorBody != null)
                    {
                        ex.Body = _errorBody;
                    }
                }
                catch (JsonException)
                {
                    // Ignore the exception
                }
                ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
                ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
                if (_shouldTrace)
                {
                    ServiceClientTracing.Error(_invocationId, ex);
                }
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            // Create Result
            var _result = new AzureOperationHeaderResponse<PoolDeleteHeaders>();
            _result.Request = _httpRequest;
            _result.Response = _httpResponse;
            if (_httpResponse.Headers.Contains("request-id"))
            {
                _result.RequestId = _httpResponse.Headers.GetValues("request-id").FirstOrDefault();
            }
            try
            {
                _result.Headers = _httpResponse.GetHeadersAsJson().ToObject<PoolDeleteHeaders>(JsonSerializer.Create(this.Client.DeserializationSettings));
            }
            catch (JsonException ex)
            {
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw new SerializationException("Unable to deserialize the headers.", _httpResponse.GetHeadersAsJson().ToString(), ex);
            }
            if (_shouldTrace)
            {
                ServiceClientTracing.Exit(_invocationId, _result);
            }
            return _result;
        }

        /// <summary>
        /// Gets basic properties of a pool.
        /// </summary>
        /// <param name='poolId'>
        /// The id of the pool to get.
        /// </param>
        /// <param name='poolExistsOptions'>
        /// Additional parameters for the operation
        /// </param>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="BatchErrorException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public async Task<AzureOperationResponse<bool,PoolExistsHeaders>> ExistsWithHttpMessagesAsync(string poolId, PoolExistsOptions poolExistsOptions = default(PoolExistsOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (poolId == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "poolId");
            }
            if (this.Client.ApiVersion == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
            }
            int? timeout = default(int?);
            if (poolExistsOptions != null)
            {
                timeout = poolExistsOptions.Timeout;
            }
            string clientRequestId = default(string);
            if (poolExistsOptions != null)
            {
                clientRequestId = poolExistsOptions.ClientRequestId;
            }
            bool? returnClientRequestId = default(bool?);
            if (poolExistsOptions != null)
            {
                returnClientRequestId = poolExistsOptions.ReturnClientRequestId;
            }
            DateTime? ocpDate = default(DateTime?);
            if (poolExistsOptions != null)
            {
                ocpDate = poolExistsOptions.OcpDate;
            }
            string ifMatch = default(string);
            if (poolExistsOptions != null)
            {
                ifMatch = poolExistsOptions.IfMatch;
            }
            string ifNoneMatch = default(string);
            if (poolExistsOptions != null)
            {
                ifNoneMatch = poolExistsOptions.IfNoneMatch;
            }
            DateTime? ifModifiedSince = default(DateTime?);
            if (poolExistsOptions != null)
            {
                ifModifiedSince = poolExistsOptions.IfModifiedSince;
            }
            DateTime? ifUnmodifiedSince = default(DateTime?);
            if (poolExistsOptions != null)
            {
                ifUnmodifiedSince = poolExistsOptions.IfUnmodifiedSince;
            }
            // Tracing
            bool _shouldTrace = ServiceClientTracing.IsEnabled;
            string _invocationId = null;
            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
                tracingParameters.Add("poolId", poolId);
                tracingParameters.Add("timeout", timeout);
                tracingParameters.Add("clientRequestId", clientRequestId);
                tracingParameters.Add("returnClientRequestId", returnClientRequestId);
                tracingParameters.Add("ocpDate", ocpDate);
                tracingParameters.Add("ifMatch", ifMatch);
                tracingParameters.Add("ifNoneMatch", ifNoneMatch);
                tracingParameters.Add("ifModifiedSince", ifModifiedSince);
                tracingParameters.Add("ifUnmodifiedSince", ifUnmodifiedSince);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "Exists", tracingParameters);
            }
            // Construct URL
            var _baseUrl = this.Client.BaseUri.AbsoluteUri;
            var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "pools/{poolId}").ToString();
            _url = _url.Replace("{poolId}", Uri.EscapeDataString(poolId));
            List<string> _queryParameters = new List<string>();
            if (this.Client.ApiVersion != null)
            {
                _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
            }
            if (timeout != null)
            {
                _queryParameters.Add(string.Format("timeout={0}", Uri.EscapeDataString(SafeJsonConvert.SerializeObject(timeout, this.Client.SerializationSettings).Trim('"'))));
            }
            if (_queryParameters.Count > 0)
            {
                _url += "?" + string.Join("&", _queryParameters);
            }
            // Create HTTP transport objects
            HttpRequestMessage _httpRequest = new HttpRequestMessage();
            HttpResponseMessage _httpResponse = null;
            _httpRequest.Method = new HttpMethod("HEAD");
            _httpRequest.RequestUri = new Uri(_url);
            // Set Headers
            if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
            {
                _httpRequest.Headers.TryAddWithoutValidation("client-request-id", Guid.NewGuid().ToString());
            }
            if (this.Client.AcceptLanguage != null)
            {
                if (_httpRequest.Headers.Contains("accept-language"))
                {
                    _httpRequest.Headers.Remove("accept-language");
                }
                _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
            }
            if (clientRequestId != null)
            {
                if (_httpRequest.Headers.Contains("client-request-id"))
                {
                    _httpRequest.Headers.Remove("client-request-id");
                }
                _httpRequest.Headers.TryAddWithoutValidation("client-request-id", clientRequestId);
            }
            if (returnClientRequestId != null)
            {
                if (_httpRequest.Headers.Contains("return-client-request-id"))
                {
                    _httpRequest.Headers.Remove("return-client-request-id");
                }
                _httpRequest.Headers.TryAddWithoutValidation("return-client-request-id", SafeJsonConvert.SerializeObject(returnClientRequestId, this.Client.SerializationSettings).Trim('"'));
            }
            if (ocpDate != null)
            {
                if (_httpRequest.Headers.Contains("ocp-date"))
                {
                    _httpRequest.Headers.Remove("ocp-date");
                }
                _httpRequest.Headers.TryAddWithoutValidation("ocp-date", SafeJsonConvert.SerializeObject(ocpDate, new DateTimeRfc1123JsonConverter()).Trim('"'));
            }
            if (ifMatch != null)
            {
                if (_httpRequest.Headers.Contains("If-Match"))
                {
                    _httpRequest.Headers.Remove("If-Match");
                }
                _httpRequest.Headers.TryAddWithoutValidation("If-Match", ifMatch);
            }
            if (ifNoneMatch != null)
            {
                if (_httpRequest.Headers.Contains("If-None-Match"))
                {
                    _httpRequest.Headers.Remove("If-None-Match");
                }
                _httpRequest.Headers.TryAddWithoutValidation("If-None-Match", ifNoneMatch);
            }
            if (ifModifiedSince != null)
            {
                if (_httpRequest.Headers.Contains("If-Modified-Since"))
                {
                    _httpRequest.Headers.Remove("If-Modified-Since");
                }
                _httpRequest.Headers.TryAddWithoutValidation("If-Modified-Since", SafeJsonConvert.SerializeObject(ifModifiedSince, new DateTimeRfc1123JsonConverter()).Trim('"'));
            }
            if (ifUnmodifiedSince != null)
            {
                if (_httpRequest.Headers.Contains("If-Unmodified-Since"))
                {
                    _httpRequest.Headers.Remove("If-Unmodified-Since");
                }
                _httpRequest.Headers.TryAddWithoutValidation("If-Unmodified-Since", SafeJsonConvert.SerializeObject(ifUnmodifiedSince, new DateTimeRfc1123JsonConverter()).Trim('"'));
            }
            if (customHeaders != null)
            {
                foreach(var _header in customHeaders)
                {
                    if (_httpRequest.Headers.Contains(_header.Key))
                    {
                        _httpRequest.Headers.Remove(_header.Key);
                    }
                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
                }
            }

            // Serialize Request
            string _requestContent = null;
            // Set Credentials
            if (this.Client.Credentials != null)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            }
            // Send Request
            if (_shouldTrace)
            {
                ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            if (_shouldTrace)
            {
                ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
            }
            HttpStatusCode _statusCode = _httpResponse.StatusCode;
            cancellationToken.ThrowIfCancellationRequested();
            string _responseContent = null;
            if ((int)_statusCode != 200 && (int)_statusCode != 404)
            {
                var ex = new BatchErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                try
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
                    BatchError _errorBody = SafeJsonConvert.DeserializeObject<BatchError>(_responseContent, this.Client.DeserializationSettings);
                    if (_errorBody != null)
                    {
                        ex.Body = _errorBody;
                    }
                }
                catch (JsonException)
                {
                    // Ignore the exception
                }
                ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
                ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
                if (_shouldTrace)
                {
                    ServiceClientTracing.Error(_invocationId, ex);
                }
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            // Create Result
            var _result = new AzureOperationResponse<bool,PoolExistsHeaders>();
            _result.Request = _httpRequest;
            _result.Response = _httpResponse;
            _result.Body = (_statusCode == HttpStatusCode.OK);
            if (_httpResponse.Headers.Contains("request-id"))
            {
                _result.RequestId = _httpResponse.Headers.GetValues("request-id").FirstOrDefault();
            }
            try
            {
                _result.Headers = _httpResponse.GetHeadersAsJson().ToObject<PoolExistsHeaders>(JsonSerializer.Create(this.Client.DeserializationSettings));
            }
            catch (JsonException ex)
            {
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw new SerializationException("Unable to deserialize the headers.", _httpResponse.GetHeadersAsJson().ToString(), ex);
            }
            if (_shouldTrace)
            {
                ServiceClientTracing.Exit(_invocationId, _result);
            }
            return _result;
        }

        /// <summary>
        /// Gets information about the specified pool.
        /// </summary>
        /// <param name='poolId'>
        /// The id of the pool to get.
        /// </param>
        /// <param name='poolGetOptions'>
        /// Additional parameters for the operation
        /// </param>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="BatchErrorException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public async Task<AzureOperationResponse<CloudPool,PoolGetHeaders>> GetWithHttpMessagesAsync(string poolId, PoolGetOptions poolGetOptions = default(PoolGetOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (poolId == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "poolId");
            }
            if (this.Client.ApiVersion == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
            }
            string select = default(string);
            if (poolGetOptions != null)
            {
                select = poolGetOptions.Select;
            }
            string expand = default(string);
            if (poolGetOptions != null)
            {
                expand = poolGetOptions.Expand;
            }
            int? timeout = default(int?);
            if (poolGetOptions != null)
            {
                timeout = poolGetOptions.Timeout;
            }
            string clientRequestId = default(string);
            if (poolGetOptions != null)
            {
                clientRequestId = poolGetOptions.ClientRequestId;
            }
            bool? returnClientRequestId = default(bool?);
            if (poolGetOptions != null)
            {
                returnClientRequestId = poolGetOptions.ReturnClientRequestId;
            }
            DateTime? ocpDate = default(DateTime?);
            if (poolGetOptions != null)
            {
                ocpDate = poolGetOptions.OcpDate;
            }
            string ifMatch = default(string);
            if (poolGetOptions != null)
            {
                ifMatch = poolGetOptions.IfMatch;
            }
            string ifNoneMatch = default(string);
            if (poolGetOptions != null)
            {
                ifNoneMatch = poolGetOptions.IfNoneMatch;
            }
            DateTime? ifModifiedSince = default(DateTime?);
            if (poolGetOptions != null)
            {
                ifModifiedSince = poolGetOptions.IfModifiedSince;
            }
            DateTime? ifUnmodifiedSince = default(DateTime?);
            if (poolGetOptions != null)
            {
                ifUnmodifiedSince = poolGetOptions.IfUnmodifiedSince;
            }
            // Tracing
            bool _shouldTrace = ServiceClientTracing.IsEnabled;
            string _invocationId = null;
            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
                tracingParameters.Add("poolId", poolId);
                tracingParameters.Add("select", select);
                tracingParameters.Add("expand", expand);
                tracingParameters.Add("timeout", timeout);
                tracingParameters.Add("clientRequestId", clientRequestId);
                tracingParameters.Add("returnClientRequestId", returnClientRequestId);
                tracingParameters.Add("ocpDate", ocpDate);
                tracingParameters.Add("ifMatch", ifMatch);
                tracingParameters.Add("ifNoneMatch", ifNoneMatch);
                tracingParameters.Add("ifModifiedSince", ifModifiedSince);
                tracingParameters.Add("ifUnmodifiedSince", ifUnmodifiedSince);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
            }
            // Construct URL
            var _baseUrl = this.Client.BaseUri.AbsoluteUri;
            var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "pools/{poolId}").ToString();
            _url = _url.Replace("{poolId}", Uri.EscapeDataString(poolId));
            List<string> _queryParameters = new List<string>();
            if (this.Client.ApiVersion != null)
            {
                _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
            }
            if (select != null)
            {
                _queryParameters.Add(string.Format("$select={0}", Uri.EscapeDataString(select)));
            }
            if (expand != null)
            {
                _queryParameters.Add(string.Format("$expand={0}", Uri.EscapeDataString(expand)));
            }
            if (timeout != null)
            {
                _queryParameters.Add(string.Format("timeout={0}", Uri.EscapeDataString(SafeJsonConvert.SerializeObject(timeout, this.Client.SerializationSettings).Trim('"'))));
            }
            if (_queryParameters.Count > 0)
            {
                _url += "?" + string.Join("&", _queryParameters);
            }
            // Create HTTP transport objects
            HttpRequestMessage _httpRequest = new HttpRequestMessage();
            HttpResponseMessage _httpResponse = null;
            _httpRequest.Method = new HttpMethod("GET");
            _httpRequest.RequestUri = new Uri(_url);
            // Set Headers
            if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
            {
                _httpRequest.Headers.TryAddWithoutValidation("client-request-id", Guid.NewGuid().ToString());
            }
            if (this.Client.AcceptLanguage != null)
            {
                if (_httpRequest.Headers.Contains("accept-language"))
                {
                    _httpRequest.Headers.Remove("accept-language");
                }
                _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
            }
            if (clientRequestId != null)
            {
                if (_httpRequest.Headers.Contains("client-request-id"))
                {
                    _httpRequest.Headers.Remove("client-request-id");
                }
                _httpRequest.Headers.TryAddWithoutValidation("client-request-id", clientRequestId);
            }
            if (returnClientRequestId != null)
            {
                if (_httpRequest.Headers.Contains("return-client-request-id"))
                {
                    _httpRequest.Headers.Remove("return-client-request-id");
                }
                _httpRequest.Headers.TryAddWithoutValidation("return-client-request-id", SafeJsonConvert.SerializeObject(returnClientRequestId, this.Client.SerializationSettings).Trim('"'));
            }
            if (ocpDate != null)
            {
                if (_httpRequest.Headers.Contains("ocp-date"))
                {
                    _httpRequest.Headers.Remove("ocp-date");
                }
                _httpRequest.Headers.TryAddWithoutValidation("ocp-date", SafeJsonConvert.SerializeObject(ocpDate, new DateTimeRfc1123JsonConverter()).Trim('"'));
            }
            if (ifMatch != null)
            {
                if (_httpRequest.Headers.Contains("If-Match"))
                {
                    _httpRequest.Headers.Remove("If-Match");
                }
                _httpRequest.Headers.TryAddWithoutValidation("If-Match", ifMatch);
            }
            if (ifNoneMatch != null)
            {
                if (_httpRequest.Headers.Contains("If-None-Match"))
                {
                    _httpRequest.Headers.Remove("If-None-Match");
                }
                _httpRequest.Headers.TryAddWithoutValidation("If-None-Match", ifNoneMatch);
            }
            if (ifModifiedSince != null)
            {
                if (_httpRequest.Headers.Contains("If-Modified-Since"))
                {
                    _httpRequest.Headers.Remove("If-Modified-Since");
                }
                _httpRequest.Headers.TryAddWithoutValidation("If-Modified-Since", SafeJsonConvert.SerializeObject(ifModifiedSince, new DateTimeRfc1123JsonConverter()).Trim('"'));
            }
            if (ifUnmodifiedSince != null)
            {
                if (_httpRequest.Headers.Contains("If-Unmodified-Since"))
                {
                    _httpRequest.Headers.Remove("If-Unmodified-Since");
                }
                _httpRequest.Headers.TryAddWithoutValidation("If-Unmodified-Since", SafeJsonConvert.SerializeObject(ifUnmodifiedSince, new DateTimeRfc1123JsonConverter()).Trim('"'));
            }
            if (customHeaders != null)
            {
                foreach(var _header in customHeaders)
                {
                    if (_httpRequest.Headers.Contains(_header.Key))
                    {
                        _httpRequest.Headers.Remove(_header.Key);
                    }
                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
                }
            }

            // Serialize Request
            string _requestContent = null;
            // Set Credentials
            if (this.Client.Credentials != null)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            }
            // Send Request
            if (_shouldTrace)
            {
                ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            if (_shouldTrace)
            {
                ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
            }
            HttpStatusCode _statusCode = _httpResponse.StatusCode;
            cancellationToken.ThrowIfCancellationRequested();
            string _responseContent = null;
            if ((int)_statusCode != 200)
            {
                var ex = new BatchErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                try
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
                    BatchError _errorBody = SafeJsonConvert.DeserializeObject<BatchError>(_responseContent, this.Client.DeserializationSettings);
                    if (_errorBody != null)
                    {
                        ex.Body = _errorBody;
                    }
                }
                catch (JsonException)
                {
                    // Ignore the exception
                }
                ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
                ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
                if (_shouldTrace)
                {
                    ServiceClientTracing.Error(_invocationId, ex);
                }
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            // Create Result
            var _result = new AzureOperationResponse<CloudPool,PoolGetHeaders>();
            _result.Request = _httpRequest;
            _result.Response = _httpResponse;
            if (_httpResponse.Headers.Contains("request-id"))
            {
                _result.RequestId = _httpResponse.Headers.GetValues("request-id").FirstOrDefault();
            }
            // Deserialize Response
            if ((int)_statusCode == 200)
            {
                _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
                try
                {
                    _result.Body = SafeJsonConvert.DeserializeObject<CloudPool>(_responseContent, this.Client.DeserializationSettings);
                }
                catch (JsonException ex)
                {
                    _httpRequest.Dispose();
                    if (_httpResponse != null)
                    {
                        _httpResponse.Dispose();
                    }
                    throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
                }
            }
            try
            {
                _result.Headers = _httpResponse.GetHeadersAsJson().ToObject<PoolGetHeaders>(JsonSerializer.Create(this.Client.DeserializationSettings));
            }
            catch (JsonException ex)
            {
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw new SerializationException("Unable to deserialize the headers.", _httpResponse.GetHeadersAsJson().ToString(), ex);
            }
            if (_shouldTrace)
            {
                ServiceClientTracing.Exit(_invocationId, _result);
            }
            return _result;
        }

        /// <summary>
        /// Updates the properties of a pool.
        /// </summary>
        /// <param name='poolId'>
        /// The id of the pool to update.
        /// </param>
        /// <param name='poolPatchParameter'>
        /// The parameters for the request.
        /// </param>
        /// <param name='poolPatchOptions'>
        /// Additional parameters for the operation
        /// </param>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="BatchErrorException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public async Task<AzureOperationHeaderResponse<PoolPatchHeaders>> PatchWithHttpMessagesAsync(string poolId, PoolPatchParameter poolPatchParameter, PoolPatchOptions poolPatchOptions = default(PoolPatchOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (poolId == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "poolId");
            }
            if (poolPatchParameter == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "poolPatchParameter");
            }
            if (this.Client.ApiVersion == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
            }
            int? timeout = default(int?);
            if (poolPatchOptions != null)
            {
                timeout = poolPatchOptions.Timeout;
            }
            string clientRequestId = default(string);
            if (poolPatchOptions != null)
            {
                clientRequestId = poolPatchOptions.ClientRequestId;
            }
            bool? returnClientRequestId = default(bool?);
            if (poolPatchOptions != null)
            {
                returnClientRequestId = poolPatchOptions.ReturnClientRequestId;
            }
            DateTime? ocpDate = default(DateTime?);
            if (poolPatchOptions != null)
            {
                ocpDate = poolPatchOptions.OcpDate;
            }
            string ifMatch = default(string);
            if (poolPatchOptions != null)
            {
                ifMatch = poolPatchOptions.IfMatch;
            }
            string ifNoneMatch = default(string);
            if (poolPatchOptions != null)
            {
                ifNoneMatch = poolPatchOptions.IfNoneMatch;
            }
            DateTime? ifModifiedSince = default(DateTime?);
            if (poolPatchOptions != null)
            {
                ifModifiedSince = poolPatchOptions.IfModifiedSince;
            }
            DateTime? ifUnmodifiedSince = default(DateTime?);
            if (poolPatchOptions != null)
            {
                ifUnmodifiedSince = poolPatchOptions.IfUnmodifiedSince;
            }
            // Tracing
            bool _shouldTrace = ServiceClientTracing.IsEnabled;
            string _invocationId = null;
            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
                tracingParameters.Add("poolId", poolId);
                tracingParameters.Add("poolPatchParameter", poolPatchParameter);
                tracingParameters.Add("timeout", timeout);
                tracingParameters.Add("clientRequestId", clientRequestId);
                tracingParameters.Add("returnClientRequestId", returnClientRequestId);
                tracingParameters.Add("ocpDate", ocpDate);
                tracingParameters.Add("ifMatch", ifMatch);
                tracingParameters.Add("ifNoneMatch", ifNoneMatch);
                tracingParameters.Add("ifModifiedSince", ifModifiedSince);
                tracingParameters.Add("ifUnmodifiedSince", ifUnmodifiedSince);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "Patch", tracingParameters);
            }
            // Construct URL
            var _baseUrl = this.Client.BaseUri.AbsoluteUri;
            var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "pools/{poolId}").ToString();
            _url = _url.Replace("{poolId}", Uri.EscapeDataString(poolId));
            List<string> _queryParameters = new List<string>();
            if (this.Client.ApiVersion != null)
            {
                _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
            }
            if (timeout != null)
            {
                _queryParameters.Add(string.Format("timeout={0}", Uri.EscapeDataString(SafeJsonConvert.SerializeObject(timeout, this.Client.SerializationSettings).Trim('"'))));
            }
            if (_queryParameters.Count > 0)
            {
                _url += "?" + string.Join("&", _queryParameters);
            }
            // Create HTTP transport objects
            HttpRequestMessage _httpRequest = new HttpRequestMessage();
            HttpResponseMessage _httpResponse = null;
            _httpRequest.Method = new HttpMethod("PATCH");
            _httpRequest.RequestUri = new Uri(_url);
            // Set Headers
            if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
            {
                _httpRequest.Headers.TryAddWithoutValidation("client-request-id", Guid.NewGuid().ToString());
            }
            if (this.Client.AcceptLanguage != null)
            {
                if (_httpRequest.Headers.Contains("accept-language"))
                {
                    _httpRequest.Headers.Remove("accept-language");
                }
                _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
            }
            if (clientRequestId != null)
            {
                if (_httpRequest.Headers.Contains("client-request-id"))
                {
                    _httpRequest.Headers.Remove("client-request-id");
                }
                _httpRequest.Headers.TryAddWithoutValidation("client-request-id", clientRequestId);
            }
            if (returnClientRequestId != null)
            {
                if (_httpRequest.Headers.Contains("return-client-request-id"))
                {
                    _httpRequest.Headers.Remove("return-client-request-id");
                }
                _httpRequest.Headers.TryAddWithoutValidation("return-client-request-id", SafeJsonConvert.SerializeObject(returnClientRequestId, this.Client.SerializationSettings).Trim('"'));
            }
            if (ocpDate != null)
            {
                if (_httpRequest.Headers.Contains("ocp-date"))
                {
                    _httpRequest.Headers.Remove("ocp-date");
                }
                _httpRequest.Headers.TryAddWithoutValidation("ocp-date", SafeJsonConvert.SerializeObject(ocpDate, new DateTimeRfc1123JsonConverter()).Trim('"'));
            }
            if (ifMatch != null)
            {
                if (_httpRequest.Headers.Contains("If-Match"))
                {
                    _httpRequest.Headers.Remove("If-Match");
                }
                _httpRequest.Headers.TryAddWithoutValidation("If-Match", ifMatch);
            }
            if (ifNoneMatch != null)
            {
                if (_httpRequest.Headers.Contains("If-None-Match"))
                {
                    _httpRequest.Headers.Remove("If-None-Match");
                }
                _httpRequest.Headers.TryAddWithoutValidation("If-None-Match", ifNoneMatch);
            }
            if (ifModifiedSince != null)
            {
                if (_httpRequest.Headers.Contains("If-Modified-Since"))
                {
                    _httpRequest.Headers.Remove("If-Modified-Since");
                }
                _httpRequest.Headers.TryAddWithoutValidation("If-Modified-Since", SafeJsonConvert.SerializeObject(ifModifiedSince, new DateTimeRfc1123JsonConverter()).Trim('"'));
            }
            if (ifUnmodifiedSince != null)
            {
                if (_httpRequest.Headers.Contains("If-Unmodified-Since"))
                {
                    _httpRequest.Headers.Remove("If-Unmodified-Since");
                }
                _httpRequest.Headers.TryAddWithoutValidation("If-Unmodified-Since", SafeJsonConvert.SerializeObject(ifUnmodifiedSince, new DateTimeRfc1123JsonConverter()).Trim('"'));
            }
            if (customHeaders != null)
            {
                foreach(var _header in customHeaders)
                {
                    if (_httpRequest.Headers.Contains(_header.Key))
                    {
                        _httpRequest.Headers.Remove(_header.Key);
                    }
                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
                }
            }

            // Serialize Request
            string _requestContent = null;
            if(poolPatchParameter != null)
            {
                _requestContent = SafeJsonConvert.SerializeObject(poolPatchParameter, this.Client.SerializationSettings);
                _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8);
                _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; odata=minimalmetadata; charset=utf-8");
            }
            // Set Credentials
            if (this.Client.Credentials != null)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            }
            // Send Request
            if (_shouldTrace)
            {
                ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            if (_shouldTrace)
            {
                ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
            }
            HttpStatusCode _statusCode = _httpResponse.StatusCode;
            cancellationToken.ThrowIfCancellationRequested();
            string _responseContent = null;
            if ((int)_statusCode != 200)
            {
                var ex = new BatchErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                try
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
                    BatchError _errorBody = SafeJsonConvert.DeserializeObject<BatchError>(_responseContent, this.Client.DeserializationSettings);
                    if (_errorBody != null)
                    {
                        ex.Body = _errorBody;
                    }
                }
                catch (JsonException)
                {
                    // Ignore the exception
                }
                ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
                ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
                if (_shouldTrace)
                {
                    ServiceClientTracing.Error(_invocationId, ex);
                }
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            // Create Result
            var _result = new AzureOperationHeaderResponse<PoolPatchHeaders>();
            _result.Request = _httpRequest;
            _result.Response = _httpResponse;
            if (_httpResponse.Headers.Contains("request-id"))
            {
                _result.RequestId = _httpResponse.Headers.GetValues("request-id").FirstOrDefault();
            }
            try
            {
                _result.Headers = _httpResponse.GetHeadersAsJson().ToObject<PoolPatchHeaders>(JsonSerializer.Create(this.Client.DeserializationSettings));
            }
            catch (JsonException ex)
            {
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw new SerializationException("Unable to deserialize the headers.", _httpResponse.GetHeadersAsJson().ToString(), ex);
            }
            if (_shouldTrace)
            {
                ServiceClientTracing.Exit(_invocationId, _result);
            }
            return _result;
        }

        /// <summary>
        /// Disables automatic scaling for a pool.
        /// </summary>
        /// <param name='poolId'>
        /// The id of the pool on which to disable automatic scaling.
        /// </param>
        /// <param name='poolDisableAutoScaleOptions'>
        /// Additional parameters for the operation
        /// </param>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="BatchErrorException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public async Task<AzureOperationHeaderResponse<PoolDisableAutoScaleHeaders>> DisableAutoScaleWithHttpMessagesAsync(string poolId, PoolDisableAutoScaleOptions poolDisableAutoScaleOptions = default(PoolDisableAutoScaleOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (poolId == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "poolId");
            }
            if (this.Client.ApiVersion == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
            }
            int? timeout = default(int?);
            if (poolDisableAutoScaleOptions != null)
            {
                timeout = poolDisableAutoScaleOptions.Timeout;
            }
            string clientRequestId = default(string);
            if (poolDisableAutoScaleOptions != null)
            {
                clientRequestId = poolDisableAutoScaleOptions.ClientRequestId;
            }
            bool? returnClientRequestId = default(bool?);
            if (poolDisableAutoScaleOptions != null)
            {
                returnClientRequestId = poolDisableAutoScaleOptions.ReturnClientRequestId;
            }
            DateTime? ocpDate = default(DateTime?);
            if (poolDisableAutoScaleOptions != null)
            {
                ocpDate = poolDisableAutoScaleOptions.OcpDate;
            }
            // Tracing
            bool _shouldTrace = ServiceClientTracing.IsEnabled;
            string _invocationId = null;
            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
                tracingParameters.Add("poolId", poolId);
                tracingParameters.Add("timeout", timeout);
                tracingParameters.Add("clientRequestId", clientRequestId);
                tracingParameters.Add("returnClientRequestId", returnClientRequestId);
                tracingParameters.Add("ocpDate", ocpDate);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "DisableAutoScale", tracingParameters);
            }
            // Construct URL
            var _baseUrl = this.Client.BaseUri.AbsoluteUri;
            var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "pools/{poolId}/disableautoscale").ToString();
            _url = _url.Replace("{poolId}", Uri.EscapeDataString(poolId));
            List<string> _queryParameters = new List<string>();
            if (this.Client.ApiVersion != null)
            {
                _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
            }
            if (timeout != null)
            {
                _queryParameters.Add(string.Format("timeout={0}", Uri.EscapeDataString(SafeJsonConvert.SerializeObject(timeout, this.Client.SerializationSettings).Trim('"'))));
            }
            if (_queryParameters.Count > 0)
            {
                _url += "?" + string.Join("&", _queryParameters);
            }
            // Create HTTP transport objects
            HttpRequestMessage _httpRequest = new HttpRequestMessage();
            HttpResponseMessage _httpResponse = null;
            _httpRequest.Method = new HttpMethod("POST");
            _httpRequest.RequestUri = new Uri(_url);
            // Set Headers
            if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
            {
                _httpRequest.Headers.TryAddWithoutValidation("client-request-id", Guid.NewGuid().ToString());
            }
            if (this.Client.AcceptLanguage != null)
            {
                if (_httpRequest.Headers.Contains("accept-language"))
                {
                    _httpRequest.Headers.Remove("accept-language");
                }
                _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
            }
            if (clientRequestId != null)
            {
                if (_httpRequest.Headers.Contains("client-request-id"))
                {
                    _httpRequest.Headers.Remove("client-request-id");
                }
                _httpRequest.Headers.TryAddWithoutValidation("client-request-id", clientRequestId);
            }
            if (returnClientRequestId != null)
            {
                if (_httpRequest.Headers.Contains("return-client-request-id"))
                {
                    _httpRequest.Headers.Remove("return-client-request-id");
                }
                _httpRequest.Headers.TryAddWithoutValidation("return-client-request-id", SafeJsonConvert.SerializeObject(returnClientRequestId, this.Client.SerializationSettings).Trim('"'));
            }
            if (ocpDate != null)
            {
                if (_httpRequest.Headers.Contains("ocp-date"))
                {
                    _httpRequest.Headers.Remove("ocp-date");
                }
                _httpRequest.Headers.TryAddWithoutValidation("ocp-date", SafeJsonConvert.SerializeObject(ocpDate, new DateTimeRfc1123JsonConverter()).Trim('"'));
            }
            if (customHeaders != null)
            {
                foreach(var _header in customHeaders)
                {
                    if (_httpRequest.Headers.Contains(_header.Key))
                    {
                        _httpRequest.Headers.Remove(_header.Key);
                    }
                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
                }
            }

            // Serialize Request
            string _requestContent = null;
            // Set Credentials
            if (this.Client.Credentials != null)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            }
            // Send Request
            if (_shouldTrace)
            {
                ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            if (_shouldTrace)
            {
                ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
            }
            HttpStatusCode _statusCode = _httpResponse.StatusCode;
            cancellationToken.ThrowIfCancellationRequested();
            string _responseContent = null;
            if ((int)_statusCode != 200)
            {
                var ex = new BatchErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                try
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
                    BatchError _errorBody = SafeJsonConvert.DeserializeObject<BatchError>(_responseContent, this.Client.DeserializationSettings);
                    if (_errorBody != null)
                    {
                        ex.Body = _errorBody;
                    }
                }
                catch (JsonException)
                {
                    // Ignore the exception
                }
                ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
                ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
                if (_shouldTrace)
                {
                    ServiceClientTracing.Error(_invocationId, ex);
                }
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            // Create Result
            var _result = new AzureOperationHeaderResponse<PoolDisableAutoScaleHeaders>();
            _result.Request = _httpRequest;
            _result.Response = _httpResponse;
            if (_httpResponse.Headers.Contains("request-id"))
            {
                _result.RequestId = _httpResponse.Headers.GetValues("request-id").FirstOrDefault();
            }
            try
            {
                _result.Headers = _httpResponse.GetHeadersAsJson().ToObject<PoolDisableAutoScaleHeaders>(JsonSerializer.Create(this.Client.DeserializationSettings));
            }
            catch (JsonException ex)
            {
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw new SerializationException("Unable to deserialize the headers.", _httpResponse.GetHeadersAsJson().ToString(), ex);
            }
            if (_shouldTrace)
            {
                ServiceClientTracing.Exit(_invocationId, _result);
            }
            return _result;
        }

        /// <summary>
        /// Enables automatic scaling for a pool.
        /// </summary>
        /// <param name='poolId'>
        /// The id of the pool on which to enable automatic scaling.
        /// </param>
        /// <param name='poolEnableAutoScaleParameter'>
        /// The parameters for the request.
        /// </param>
        /// <param name='poolEnableAutoScaleOptions'>
        /// Additional parameters for the operation
        /// </param>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="BatchErrorException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public async Task<AzureOperationHeaderResponse<PoolEnableAutoScaleHeaders>> EnableAutoScaleWithHttpMessagesAsync(string poolId, PoolEnableAutoScaleParameter poolEnableAutoScaleParameter, PoolEnableAutoScaleOptions poolEnableAutoScaleOptions = default(PoolEnableAutoScaleOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (poolId == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "poolId");
            }
            if (poolEnableAutoScaleParameter == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "poolEnableAutoScaleParameter");
            }
            if (this.Client.ApiVersion == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
            }
            int? timeout = default(int?);
            if (poolEnableAutoScaleOptions != null)
            {
                timeout = poolEnableAutoScaleOptions.Timeout;
            }
            string clientRequestId = default(string);
            if (poolEnableAutoScaleOptions != null)
            {
                clientRequestId = poolEnableAutoScaleOptions.ClientRequestId;
            }
            bool? returnClientRequestId = default(bool?);
            if (poolEnableAutoScaleOptions != null)
            {
                returnClientRequestId = poolEnableAutoScaleOptions.ReturnClientRequestId;
            }
            DateTime? ocpDate = default(DateTime?);
            if (poolEnableAutoScaleOptions != null)
            {
                ocpDate = poolEnableAutoScaleOptions.OcpDate;
            }
            string ifMatch = default(string);
            if (poolEnableAutoScaleOptions != null)
            {
                ifMatch = poolEnableAutoScaleOptions.IfMatch;
            }
            string ifNoneMatch = default(string);
            if (poolEnableAutoScaleOptions != null)
            {
                ifNoneMatch = poolEnableAutoScaleOptions.IfNoneMatch;
            }
            DateTime? ifModifiedSince = default(DateTime?);
            if (poolEnableAutoScaleOptions != null)
            {
                ifModifiedSince = poolEnableAutoScaleOptions.IfModifiedSince;
            }
            DateTime? ifUnmodifiedSince = default(DateTime?);
            if (poolEnableAutoScaleOptions != null)
            {
                ifUnmodifiedSince = poolEnableAutoScaleOptions.IfUnmodifiedSince;
            }
            // Tracing
            bool _shouldTrace = ServiceClientTracing.IsEnabled;
            string _invocationId = null;
            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
                tracingParameters.Add("poolId", poolId);
                tracingParameters.Add("poolEnableAutoScaleParameter", poolEnableAutoScaleParameter);
                tracingParameters.Add("timeout", timeout);
                tracingParameters.Add("clientRequestId", clientRequestId);
                tracingParameters.Add("returnClientRequestId", returnClientRequestId);
                tracingParameters.Add("ocpDate", ocpDate);
                tracingParameters.Add("ifMatch", ifMatch);
                tracingParameters.Add("ifNoneMatch", ifNoneMatch);
                tracingParameters.Add("ifModifiedSince", ifModifiedSince);
                tracingParameters.Add("ifUnmodifiedSince", ifUnmodifiedSince);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "EnableAutoScale", tracingParameters);
            }
            // Construct URL
            var _baseUrl = this.Client.BaseUri.AbsoluteUri;
            var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "pools/{poolId}/enableautoscale").ToString();
            _url = _url.Replace("{poolId}", Uri.EscapeDataString(poolId));
            List<string> _queryParameters = new List<string>();
            if (this.Client.ApiVersion != null)
            {
                _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
            }
            if (timeout != null)
            {
                _queryParameters.Add(string.Format("timeout={0}", Uri.EscapeDataString(SafeJsonConvert.SerializeObject(timeout, this.Client.SerializationSettings).Trim('"'))));
            }
            if (_queryParameters.Count > 0)
            {
                _url += "?" + string.Join("&", _queryParameters);
            }
            // Create HTTP transport objects
            HttpRequestMessage _httpRequest = new HttpRequestMessage();
            HttpResponseMessage _httpResponse = null;
            _httpRequest.Method = new HttpMethod("POST");
            _httpRequest.RequestUri = new Uri(_url);
            // Set Headers
            if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
            {
                _httpRequest.Headers.TryAddWithoutValidation("client-request-id", Guid.NewGuid().ToString());
            }
            if (this.Client.AcceptLanguage != null)
            {
                if (_httpRequest.Headers.Contains("accept-language"))
                {
                    _httpRequest.Headers.Remove("accept-language");
                }
                _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
            }
            if (clientRequestId != null)
            {
                if (_httpRequest.Headers.Contains("client-request-id"))
                {
                    _httpRequest.Headers.Remove("client-request-id");
                }
                _httpRequest.Headers.TryAddWithoutValidation("client-request-id", clientRequestId);
            }
            if (returnClientRequestId != null)
            {
                if (_httpRequest.Headers.Contains("return-client-request-id"))
                {
                    _httpRequest.Headers.Remove("return-client-request-id");
                }
                _httpRequest.Headers.TryAddWithoutValidation("return-client-request-id", SafeJsonConvert.SerializeObject(returnClientRequestId, this.Client.SerializationSettings).Trim('"'));
            }
            if (ocpDate != null)
            {
                if (_httpRequest.Headers.Contains("ocp-date"))
                {
                    _httpRequest.Headers.Remove("ocp-date");
                }
                _httpRequest.Headers.TryAddWithoutValidation("ocp-date", SafeJsonConvert.SerializeObject(ocpDate, new DateTimeRfc1123JsonConverter()).Trim('"'));
            }
            if (ifMatch != null)
            {
                if (_httpRequest.Headers.Contains("If-Match"))
                {
                    _httpRequest.Headers.Remove("If-Match");
                }
                _httpRequest.Headers.TryAddWithoutValidation("If-Match", ifMatch);
            }
            if (ifNoneMatch != null)
            {
                if (_httpRequest.Headers.Contains("If-None-Match"))
                {
                    _httpRequest.Headers.Remove("If-None-Match");
                }
                _httpRequest.Headers.TryAddWithoutValidation("If-None-Match", ifNoneMatch);
            }
            if (ifModifiedSince != null)
            {
                if (_httpRequest.Headers.Contains("If-Modified-Since"))
                {
                    _httpRequest.Headers.Remove("If-Modified-Since");
                }
                _httpRequest.Headers.TryAddWithoutValidation("If-Modified-Since", SafeJsonConvert.SerializeObject(ifModifiedSince, new DateTimeRfc1123JsonConverter()).Trim('"'));
            }
            if (ifUnmodifiedSince != null)
            {
                if (_httpRequest.Headers.Contains("If-Unmodified-Since"))
                {
                    _httpRequest.Headers.Remove("If-Unmodified-Since");
                }
                _httpRequest.Headers.TryAddWithoutValidation("If-Unmodified-Since", SafeJsonConvert.SerializeObject(ifUnmodifiedSince, new DateTimeRfc1123JsonConverter()).Trim('"'));
            }
            if (customHeaders != null)
            {
                foreach(var _header in customHeaders)
                {
                    if (_httpRequest.Headers.Contains(_header.Key))
                    {
                        _httpRequest.Headers.Remove(_header.Key);
                    }
                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
                }
            }

            // Serialize Request
            string _requestContent = null;
            if(poolEnableAutoScaleParameter != null)
            {
                _requestContent = SafeJsonConvert.SerializeObject(poolEnableAutoScaleParameter, this.Client.SerializationSettings);
                _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8);
                _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; odata=minimalmetadata; charset=utf-8");
            }
            // Set Credentials
            if (this.Client.Credentials != null)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            }
            // Send Request
            if (_shouldTrace)
            {
                ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            if (_shouldTrace)
            {
                ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
            }
            HttpStatusCode _statusCode = _httpResponse.StatusCode;
            cancellationToken.ThrowIfCancellationRequested();
            string _responseContent = null;
            if ((int)_statusCode != 200)
            {
                var ex = new BatchErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                try
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
                    BatchError _errorBody = SafeJsonConvert.DeserializeObject<BatchError>(_responseContent, this.Client.DeserializationSettings);
                    if (_errorBody != null)
                    {
                        ex.Body = _errorBody;
                    }
                }
                catch (JsonException)
                {
                    // Ignore the exception
                }
                ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
                ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
                if (_shouldTrace)
                {
                    ServiceClientTracing.Error(_invocationId, ex);
                }
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            // Create Result
            var _result = new AzureOperationHeaderResponse<PoolEnableAutoScaleHeaders>();
            _result.Request = _httpRequest;
            _result.Response = _httpResponse;
            if (_httpResponse.Headers.Contains("request-id"))
            {
                _result.RequestId = _httpResponse.Headers.GetValues("request-id").FirstOrDefault();
            }
            try
            {
                _result.Headers = _httpResponse.GetHeadersAsJson().ToObject<PoolEnableAutoScaleHeaders>(JsonSerializer.Create(this.Client.DeserializationSettings));
            }
            catch (JsonException ex)
            {
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw new SerializationException("Unable to deserialize the headers.", _httpResponse.GetHeadersAsJson().ToString(), ex);
            }
            if (_shouldTrace)
            {
                ServiceClientTracing.Exit(_invocationId, _result);
            }
            return _result;
        }

        /// <summary>
        /// Gets the result of evaluating an automatic scaling formula on the pool.
        /// </summary>
        /// <param name='poolId'>
        /// The id of the pool on which to evaluate the automatic scaling formula.
        /// </param>
        /// <param name='autoScaleFormula'>
        /// A formula for the desired number of compute nodes in the pool.
        /// </param>
        /// <param name='poolEvaluateAutoScaleOptions'>
        /// Additional parameters for the operation
        /// </param>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="BatchErrorException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public async Task<AzureOperationResponse<AutoScaleRun,PoolEvaluateAutoScaleHeaders>> EvaluateAutoScaleWithHttpMessagesAsync(string poolId, string autoScaleFormula, PoolEvaluateAutoScaleOptions poolEvaluateAutoScaleOptions = default(PoolEvaluateAutoScaleOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (poolId == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "poolId");
            }
            if (this.Client.ApiVersion == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
            }
            if (autoScaleFormula == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "autoScaleFormula");
            }
            int? timeout = default(int?);
            if (poolEvaluateAutoScaleOptions != null)
            {
                timeout = poolEvaluateAutoScaleOptions.Timeout;
            }
            string clientRequestId = default(string);
            if (poolEvaluateAutoScaleOptions != null)
            {
                clientRequestId = poolEvaluateAutoScaleOptions.ClientRequestId;
            }
            bool? returnClientRequestId = default(bool?);
            if (poolEvaluateAutoScaleOptions != null)
            {
                returnClientRequestId = poolEvaluateAutoScaleOptions.ReturnClientRequestId;
            }
            DateTime? ocpDate = default(DateTime?);
            if (poolEvaluateAutoScaleOptions != null)
            {
                ocpDate = poolEvaluateAutoScaleOptions.OcpDate;
            }
            PoolEvaluateAutoScaleParameter poolEvaluateAutoScaleParameter = new PoolEvaluateAutoScaleParameter();
            if (autoScaleFormula != null)
            {
                poolEvaluateAutoScaleParameter.AutoScaleFormula = autoScaleFormula;
            }
            // Tracing
            bool _shouldTrace = ServiceClientTracing.IsEnabled;
            string _invocationId = null;
            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
                tracingParameters.Add("poolId", poolId);
                tracingParameters.Add("timeout", timeout);
                tracingParameters.Add("clientRequestId", clientRequestId);
                tracingParameters.Add("returnClientRequestId", returnClientRequestId);
                tracingParameters.Add("ocpDate", ocpDate);
                tracingParameters.Add("poolEvaluateAutoScaleParameter", poolEvaluateAutoScaleParameter);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "EvaluateAutoScale", tracingParameters);
            }
            // Construct URL
            var _baseUrl = this.Client.BaseUri.AbsoluteUri;
            var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "pools/{poolId}/evaluateautoscale").ToString();
            _url = _url.Replace("{poolId}", Uri.EscapeDataString(poolId));
            List<string> _queryParameters = new List<string>();
            if (this.Client.ApiVersion != null)
            {
                _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
            }
            if (timeout != null)
            {
                _queryParameters.Add(string.Format("timeout={0}", Uri.EscapeDataString(SafeJsonConvert.SerializeObject(timeout, this.Client.SerializationSettings).Trim('"'))));
            }
            if (_queryParameters.Count > 0)
            {
                _url += "?" + string.Join("&", _queryParameters);
            }
            // Create HTTP transport objects
            HttpRequestMessage _httpRequest = new HttpRequestMessage();
            HttpResponseMessage _httpResponse = null;
            _httpRequest.Method = new HttpMethod("POST");
            _httpRequest.RequestUri = new Uri(_url);
            // Set Headers
            if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
            {
                _httpRequest.Headers.TryAddWithoutValidation("client-request-id", Guid.NewGuid().ToString());
            }
            if (this.Client.AcceptLanguage != null)
            {
                if (_httpRequest.Headers.Contains("accept-language"))
                {
                    _httpRequest.Headers.Remove("accept-language");
                }
                _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
            }
            if (clientRequestId != null)
            {
                if (_httpRequest.Headers.Contains("client-request-id"))
                {
                    _httpRequest.Headers.Remove("client-request-id");
                }
                _httpRequest.Headers.TryAddWithoutValidation("client-request-id", clientRequestId);
            }
            if (returnClientRequestId != null)
            {
                if (_httpRequest.Headers.Contains("return-client-request-id"))
                {
                    _httpRequest.Headers.Remove("return-client-request-id");
                }
                _httpRequest.Headers.TryAddWithoutValidation("return-client-request-id", SafeJsonConvert.SerializeObject(returnClientRequestId, this.Client.SerializationSettings).Trim('"'));
            }
            if (ocpDate != null)
            {
                if (_httpRequest.Headers.Contains("ocp-date"))
                {
                    _httpRequest.Headers.Remove("ocp-date");
                }
                _httpRequest.Headers.TryAddWithoutValidation("ocp-date", SafeJsonConvert.SerializeObject(ocpDate, new DateTimeRfc1123JsonConverter()).Trim('"'));
            }
            if (customHeaders != null)
            {
                foreach(var _header in customHeaders)
                {
                    if (_httpRequest.Headers.Contains(_header.Key))
                    {
                        _httpRequest.Headers.Remove(_header.Key);
                    }
                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
                }
            }

            // Serialize Request
            string _requestContent = null;
            if(poolEvaluateAutoScaleParameter != null)
            {
                _requestContent = SafeJsonConvert.SerializeObject(poolEvaluateAutoScaleParameter, this.Client.SerializationSettings);
                _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8);
                _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; odata=minimalmetadata; charset=utf-8");
            }
            // Set Credentials
            if (this.Client.Credentials != null)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            }
            // Send Request
            if (_shouldTrace)
            {
                ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            if (_shouldTrace)
            {
                ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
            }
            HttpStatusCode _statusCode = _httpResponse.StatusCode;
            cancellationToken.ThrowIfCancellationRequested();
            string _responseContent = null;
            if ((int)_statusCode != 200)
            {
                var ex = new BatchErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                try
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
                    BatchError _errorBody = SafeJsonConvert.DeserializeObject<BatchError>(_responseContent, this.Client.DeserializationSettings);
                    if (_errorBody != null)
                    {
                        ex.Body = _errorBody;
                    }
                }
                catch (JsonException)
                {
                    // Ignore the exception
                }
                ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
                ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
                if (_shouldTrace)
                {
                    ServiceClientTracing.Error(_invocationId, ex);
                }
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            // Create Result
            var _result = new AzureOperationResponse<AutoScaleRun,PoolEvaluateAutoScaleHeaders>();
            _result.Request = _httpRequest;
            _result.Response = _httpResponse;
            if (_httpResponse.Headers.Contains("request-id"))
            {
                _result.RequestId = _httpResponse.Headers.GetValues("request-id").FirstOrDefault();
            }
            // Deserialize Response
            if ((int)_statusCode == 200)
            {
                _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
                try
                {
                    _result.Body = SafeJsonConvert.DeserializeObject<AutoScaleRun>(_responseContent, this.Client.DeserializationSettings);
                }
                catch (JsonException ex)
                {
                    _httpRequest.Dispose();
                    if (_httpResponse != null)
                    {
                        _httpResponse.Dispose();
                    }
                    throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
                }
            }
            try
            {
                _result.Headers = _httpResponse.GetHeadersAsJson().ToObject<PoolEvaluateAutoScaleHeaders>(JsonSerializer.Create(this.Client.DeserializationSettings));
            }
            catch (JsonException ex)
            {
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw new SerializationException("Unable to deserialize the headers.", _httpResponse.GetHeadersAsJson().ToString(), ex);
            }
            if (_shouldTrace)
            {
                ServiceClientTracing.Exit(_invocationId, _result);
            }
            return _result;
        }

        /// <summary>
        /// Changes the number of compute nodes that are assigned to a pool.
        /// </summary>
        /// <param name='poolId'>
        /// The id of the pool to resize.
        /// </param>
        /// <param name='poolResizeParameter'>
        /// The parameters for the request.
        /// </param>
        /// <param name='poolResizeOptions'>
        /// Additional parameters for the operation
        /// </param>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="BatchErrorException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public async Task<AzureOperationHeaderResponse<PoolResizeHeaders>> ResizeWithHttpMessagesAsync(string poolId, PoolResizeParameter poolResizeParameter, PoolResizeOptions poolResizeOptions = default(PoolResizeOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (poolId == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "poolId");
            }
            if (poolResizeParameter == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "poolResizeParameter");
            }
            if (poolResizeParameter != null)
            {
                poolResizeParameter.Validate();
            }
            if (this.Client.ApiVersion == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
            }
            int? timeout = default(int?);
            if (poolResizeOptions != null)
            {
                timeout = poolResizeOptions.Timeout;
            }
            string clientRequestId = default(string);
            if (poolResizeOptions != null)
            {
                clientRequestId = poolResizeOptions.ClientRequestId;
            }
            bool? returnClientRequestId = default(bool?);
            if (poolResizeOptions != null)
            {
                returnClientRequestId = poolResizeOptions.ReturnClientRequestId;
            }
            DateTime? ocpDate = default(DateTime?);
            if (poolResizeOptions != null)
            {
                ocpDate = poolResizeOptions.OcpDate;
            }
            string ifMatch = default(string);
            if (poolResizeOptions != null)
            {
                ifMatch = poolResizeOptions.IfMatch;
            }
            string ifNoneMatch = default(string);
            if (poolResizeOptions != null)
            {
                ifNoneMatch = poolResizeOptions.IfNoneMatch;
            }
            DateTime? ifModifiedSince = default(DateTime?);
            if (poolResizeOptions != null)
            {
                ifModifiedSince = poolResizeOptions.IfModifiedSince;
            }
            DateTime? ifUnmodifiedSince = default(DateTime?);
            if (poolResizeOptions != null)
            {
                ifUnmodifiedSince = poolResizeOptions.IfUnmodifiedSince;
            }
            // Tracing
            bool _shouldTrace = ServiceClientTracing.IsEnabled;
            string _invocationId = null;
            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
                tracingParameters.Add("poolId", poolId);
                tracingParameters.Add("poolResizeParameter", poolResizeParameter);
                tracingParameters.Add("timeout", timeout);
                tracingParameters.Add("clientRequestId", clientRequestId);
                tracingParameters.Add("returnClientRequestId", returnClientRequestId);
                tracingParameters.Add("ocpDate", ocpDate);
                tracingParameters.Add("ifMatch", ifMatch);
                tracingParameters.Add("ifNoneMatch", ifNoneMatch);
                tracingParameters.Add("ifModifiedSince", ifModifiedSince);
                tracingParameters.Add("ifUnmodifiedSince", ifUnmodifiedSince);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "Resize", tracingParameters);
            }
            // Construct URL
            var _baseUrl = this.Client.BaseUri.AbsoluteUri;
            var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "pools/{poolId}/resize").ToString();
            _url = _url.Replace("{poolId}", Uri.EscapeDataString(poolId));
            List<string> _queryParameters = new List<string>();
            if (this.Client.ApiVersion != null)
            {
                _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
            }
            if (timeout != null)
            {
                _queryParameters.Add(string.Format("timeout={0}", Uri.EscapeDataString(SafeJsonConvert.SerializeObject(timeout, this.Client.SerializationSettings).Trim('"'))));
            }
            if (_queryParameters.Count > 0)
            {
                _url += "?" + string.Join("&", _queryParameters);
            }
            // Create HTTP transport objects
            HttpRequestMessage _httpRequest = new HttpRequestMessage();
            HttpResponseMessage _httpResponse = null;
            _httpRequest.Method = new HttpMethod("POST");
            _httpRequest.RequestUri = new Uri(_url);
            // Set Headers
            if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
            {
                _httpRequest.Headers.TryAddWithoutValidation("client-request-id", Guid.NewGuid().ToString());
            }
            if (this.Client.AcceptLanguage != null)
            {
                if (_httpRequest.Headers.Contains("accept-language"))
                {
                    _httpRequest.Headers.Remove("accept-language");
                }
                _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
            }
            if (clientRequestId != null)
            {
                if (_httpRequest.Headers.Contains("client-request-id"))
                {
                    _httpRequest.Headers.Remove("client-request-id");
                }
                _httpRequest.Headers.TryAddWithoutValidation("client-request-id", clientRequestId);
            }
            if (returnClientRequestId != null)
            {
                if (_httpRequest.Headers.Contains("return-client-request-id"))
                {
                    _httpRequest.Headers.Remove("return-client-request-id");
                }
                _httpRequest.Headers.TryAddWithoutValidation("return-client-request-id", SafeJsonConvert.SerializeObject(returnClientRequestId, this.Client.SerializationSettings).Trim('"'));
            }
            if (ocpDate != null)
            {
                if (_httpRequest.Headers.Contains("ocp-date"))
                {
                    _httpRequest.Headers.Remove("ocp-date");
                }
                _httpRequest.Headers.TryAddWithoutValidation("ocp-date", SafeJsonConvert.SerializeObject(ocpDate, new DateTimeRfc1123JsonConverter()).Trim('"'));
            }
            if (ifMatch != null)
            {
                if (_httpRequest.Headers.Contains("If-Match"))
                {
                    _httpRequest.Headers.Remove("If-Match");
                }
                _httpRequest.Headers.TryAddWithoutValidation("If-Match", ifMatch);
            }
            if (ifNoneMatch != null)
            {
                if (_httpRequest.Headers.Contains("If-None-Match"))
                {
                    _httpRequest.Headers.Remove("If-None-Match");
                }
                _httpRequest.Headers.TryAddWithoutValidation("If-None-Match", ifNoneMatch);
            }
            if (ifModifiedSince != null)
            {
                if (_httpRequest.Headers.Contains("If-Modified-Since"))
                {
                    _httpRequest.Headers.Remove("If-Modified-Since");
                }
                _httpRequest.Headers.TryAddWithoutValidation("If-Modified-Since", SafeJsonConvert.SerializeObject(ifModifiedSince, new DateTimeRfc1123JsonConverter()).Trim('"'));
            }
            if (ifUnmodifiedSince != null)
            {
                if (_httpRequest.Headers.Contains("If-Unmodified-Since"))
                {
                    _httpRequest.Headers.Remove("If-Unmodified-Since");
                }
                _httpRequest.Headers.TryAddWithoutValidation("If-Unmodified-Since", SafeJsonConvert.SerializeObject(ifUnmodifiedSince, new DateTimeRfc1123JsonConverter()).Trim('"'));
            }
            if (customHeaders != null)
            {
                foreach(var _header in customHeaders)
                {
                    if (_httpRequest.Headers.Contains(_header.Key))
                    {
                        _httpRequest.Headers.Remove(_header.Key);
                    }
                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
                }
            }

            // Serialize Request
            string _requestContent = null;
            if(poolResizeParameter != null)
            {
                _requestContent = SafeJsonConvert.SerializeObject(poolResizeParameter, this.Client.SerializationSettings);
                _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8);
                _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; odata=minimalmetadata; charset=utf-8");
            }
            // Set Credentials
            if (this.Client.Credentials != null)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            }
            // Send Request
            if (_shouldTrace)
            {
                ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            if (_shouldTrace)
            {
                ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
            }
            HttpStatusCode _statusCode = _httpResponse.StatusCode;
            cancellationToken.ThrowIfCancellationRequested();
            string _responseContent = null;
            if ((int)_statusCode != 202)
            {
                var ex = new BatchErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                try
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
                    BatchError _errorBody = SafeJsonConvert.DeserializeObject<BatchError>(_responseContent, this.Client.DeserializationSettings);
                    if (_errorBody != null)
                    {
                        ex.Body = _errorBody;
                    }
                }
                catch (JsonException)
                {
                    // Ignore the exception
                }
                ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
                ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
                if (_shouldTrace)
                {
                    ServiceClientTracing.Error(_invocationId, ex);
                }
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            // Create Result
            var _result = new AzureOperationHeaderResponse<PoolResizeHeaders>();
            _result.Request = _httpRequest;
            _result.Response = _httpResponse;
            if (_httpResponse.Headers.Contains("request-id"))
            {
                _result.RequestId = _httpResponse.Headers.GetValues("request-id").FirstOrDefault();
            }
            try
            {
                _result.Headers = _httpResponse.GetHeadersAsJson().ToObject<PoolResizeHeaders>(JsonSerializer.Create(this.Client.DeserializationSettings));
            }
            catch (JsonException ex)
            {
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw new SerializationException("Unable to deserialize the headers.", _httpResponse.GetHeadersAsJson().ToString(), ex);
            }
            if (_shouldTrace)
            {
                ServiceClientTracing.Exit(_invocationId, _result);
            }
            return _result;
        }

        /// <summary>
        /// Stops an ongoing resize operation on the pool.
        /// </summary>
        /// <remarks>
        /// This does not restore the pool to its previous state before the resize
        /// operation: it only stops any further changes being made, and the pool
        /// maintains its current state.
        /// </remarks>
        /// <param name='poolId'>
        /// The id of the pool whose resizing you want to stop.
        /// </param>
        /// <param name='poolStopResizeOptions'>
        /// Additional parameters for the operation
        /// </param>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="BatchErrorException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public async Task<AzureOperationHeaderResponse<PoolStopResizeHeaders>> StopResizeWithHttpMessagesAsync(string poolId, PoolStopResizeOptions poolStopResizeOptions = default(PoolStopResizeOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (poolId == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "poolId");
            }
            if (this.Client.ApiVersion == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
            }
            int? timeout = default(int?);
            if (poolStopResizeOptions != null)
            {
                timeout = poolStopResizeOptions.Timeout;
            }
            string clientRequestId = default(string);
            if (poolStopResizeOptions != null)
            {
                clientRequestId = poolStopResizeOptions.ClientRequestId;
            }
            bool? returnClientRequestId = default(bool?);
            if (poolStopResizeOptions != null)
            {
                returnClientRequestId = poolStopResizeOptions.ReturnClientRequestId;
            }
            DateTime? ocpDate = default(DateTime?);
            if (poolStopResizeOptions != null)
            {
                ocpDate = poolStopResizeOptions.OcpDate;
            }
            string ifMatch = default(string);
            if (poolStopResizeOptions != null)
            {
                ifMatch = poolStopResizeOptions.IfMatch;
            }
            string ifNoneMatch = default(string);
            if (poolStopResizeOptions != null)
            {
                ifNoneMatch = poolStopResizeOptions.IfNoneMatch;
            }
            DateTime? ifModifiedSince = default(DateTime?);
            if (poolStopResizeOptions != null)
            {
                ifModifiedSince = poolStopResizeOptions.IfModifiedSince;
            }
            DateTime? ifUnmodifiedSince = default(DateTime?);
            if (poolStopResizeOptions != null)
            {
                ifUnmodifiedSince = poolStopResizeOptions.IfUnmodifiedSince;
            }
            // Tracing
            bool _shouldTrace = ServiceClientTracing.IsEnabled;
            string _invocationId = null;
            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
                tracingParameters.Add("poolId", poolId);
                tracingParameters.Add("timeout", timeout);
                tracingParameters.Add("clientRequestId", clientRequestId);
                tracingParameters.Add("returnClientRequestId", returnClientRequestId);
                tracingParameters.Add("ocpDate", ocpDate);
                tracingParameters.Add("ifMatch", ifMatch);
                tracingParameters.Add("ifNoneMatch", ifNoneMatch);
                tracingParameters.Add("ifModifiedSince", ifModifiedSince);
                tracingParameters.Add("ifUnmodifiedSince", ifUnmodifiedSince);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "StopResize", tracingParameters);
            }
            // Construct URL
            var _baseUrl = this.Client.BaseUri.AbsoluteUri;
            var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "pools/{poolId}/stopresize").ToString();
            _url = _url.Replace("{poolId}", Uri.EscapeDataString(poolId));
            List<string> _queryParameters = new List<string>();
            if (this.Client.ApiVersion != null)
            {
                _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
            }
            if (timeout != null)
            {
                _queryParameters.Add(string.Format("timeout={0}", Uri.EscapeDataString(SafeJsonConvert.SerializeObject(timeout, this.Client.SerializationSettings).Trim('"'))));
            }
            if (_queryParameters.Count > 0)
            {
                _url += "?" + string.Join("&", _queryParameters);
            }
            // Create HTTP transport objects
            HttpRequestMessage _httpRequest = new HttpRequestMessage();
            HttpResponseMessage _httpResponse = null;
            _httpRequest.Method = new HttpMethod("POST");
            _httpRequest.RequestUri = new Uri(_url);
            // Set Headers
            if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
            {
                _httpRequest.Headers.TryAddWithoutValidation("client-request-id", Guid.NewGuid().ToString());
            }
            if (this.Client.AcceptLanguage != null)
            {
                if (_httpRequest.Headers.Contains("accept-language"))
                {
                    _httpRequest.Headers.Remove("accept-language");
                }
                _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
            }
            if (clientRequestId != null)
            {
                if (_httpRequest.Headers.Contains("client-request-id"))
                {
                    _httpRequest.Headers.Remove("client-request-id");
                }
                _httpRequest.Headers.TryAddWithoutValidation("client-request-id", clientRequestId);
            }
            if (returnClientRequestId != null)
            {
                if (_httpRequest.Headers.Contains("return-client-request-id"))
                {
                    _httpRequest.Headers.Remove("return-client-request-id");
                }
                _httpRequest.Headers.TryAddWithoutValidation("return-client-request-id", SafeJsonConvert.SerializeObject(returnClientRequestId, this.Client.SerializationSettings).Trim('"'));
            }
            if (ocpDate != null)
            {
                if (_httpRequest.Headers.Contains("ocp-date"))
                {
                    _httpRequest.Headers.Remove("ocp-date");
                }
                _httpRequest.Headers.TryAddWithoutValidation("ocp-date", SafeJsonConvert.SerializeObject(ocpDate, new DateTimeRfc1123JsonConverter()).Trim('"'));
            }
            if (ifMatch != null)
            {
                if (_httpRequest.Headers.Contains("If-Match"))
                {
                    _httpRequest.Headers.Remove("If-Match");
                }
                _httpRequest.Headers.TryAddWithoutValidation("If-Match", ifMatch);
            }
            if (ifNoneMatch != null)
            {
                if (_httpRequest.Headers.Contains("If-None-Match"))
                {
                    _httpRequest.Headers.Remove("If-None-Match");
                }
                _httpRequest.Headers.TryAddWithoutValidation("If-None-Match", ifNoneMatch);
            }
            if (ifModifiedSince != null)
            {
                if (_httpRequest.Headers.Contains("If-Modified-Since"))
                {
                    _httpRequest.Headers.Remove("If-Modified-Since");
                }
                _httpRequest.Headers.TryAddWithoutValidation("If-Modified-Since", SafeJsonConvert.SerializeObject(ifModifiedSince, new DateTimeRfc1123JsonConverter()).Trim('"'));
            }
            if (ifUnmodifiedSince != null)
            {
                if (_httpRequest.Headers.Contains("If-Unmodified-Since"))
                {
                    _httpRequest.Headers.Remove("If-Unmodified-Since");
                }
                _httpRequest.Headers.TryAddWithoutValidation("If-Unmodified-Since", SafeJsonConvert.SerializeObject(ifUnmodifiedSince, new DateTimeRfc1123JsonConverter()).Trim('"'));
            }
            if (customHeaders != null)
            {
                foreach(var _header in customHeaders)
                {
                    if (_httpRequest.Headers.Contains(_header.Key))
                    {
                        _httpRequest.Headers.Remove(_header.Key);
                    }
                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
                }
            }

            // Serialize Request
            string _requestContent = null;
            // Set Credentials
            if (this.Client.Credentials != null)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            }
            // Send Request
            if (_shouldTrace)
            {
                ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            if (_shouldTrace)
            {
                ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
            }
            HttpStatusCode _statusCode = _httpResponse.StatusCode;
            cancellationToken.ThrowIfCancellationRequested();
            string _responseContent = null;
            if ((int)_statusCode != 202)
            {
                var ex = new BatchErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                try
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
                    BatchError _errorBody = SafeJsonConvert.DeserializeObject<BatchError>(_responseContent, this.Client.DeserializationSettings);
                    if (_errorBody != null)
                    {
                        ex.Body = _errorBody;
                    }
                }
                catch (JsonException)
                {
                    // Ignore the exception
                }
                ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
                ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
                if (_shouldTrace)
                {
                    ServiceClientTracing.Error(_invocationId, ex);
                }
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            // Create Result
            var _result = new AzureOperationHeaderResponse<PoolStopResizeHeaders>();
            _result.Request = _httpRequest;
            _result.Response = _httpResponse;
            if (_httpResponse.Headers.Contains("request-id"))
            {
                _result.RequestId = _httpResponse.Headers.GetValues("request-id").FirstOrDefault();
            }
            try
            {
                _result.Headers = _httpResponse.GetHeadersAsJson().ToObject<PoolStopResizeHeaders>(JsonSerializer.Create(this.Client.DeserializationSettings));
            }
            catch (JsonException ex)
            {
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw new SerializationException("Unable to deserialize the headers.", _httpResponse.GetHeadersAsJson().ToString(), ex);
            }
            if (_shouldTrace)
            {
                ServiceClientTracing.Exit(_invocationId, _result);
            }
            return _result;
        }

        /// <summary>
        /// Updates the properties of a pool.
        /// </summary>
        /// <param name='poolId'>
        /// The id of the pool to update.
        /// </param>
        /// <param name='poolUpdatePropertiesParameter'>
        /// The parameters for the request.
        /// </param>
        /// <param name='poolUpdatePropertiesOptions'>
        /// Additional parameters for the operation
        /// </param>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="BatchErrorException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public async Task<AzureOperationHeaderResponse<PoolUpdatePropertiesHeaders>> UpdatePropertiesWithHttpMessagesAsync(string poolId, PoolUpdatePropertiesParameter poolUpdatePropertiesParameter, PoolUpdatePropertiesOptions poolUpdatePropertiesOptions = default(PoolUpdatePropertiesOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (poolId == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "poolId");
            }
            if (poolUpdatePropertiesParameter == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "poolUpdatePropertiesParameter");
            }
            if (poolUpdatePropertiesParameter != null)
            {
                poolUpdatePropertiesParameter.Validate();
            }
            if (this.Client.ApiVersion == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
            }
            int? timeout = default(int?);
            if (poolUpdatePropertiesOptions != null)
            {
                timeout = poolUpdatePropertiesOptions.Timeout;
            }
            string clientRequestId = default(string);
            if (poolUpdatePropertiesOptions != null)
            {
                clientRequestId = poolUpdatePropertiesOptions.ClientRequestId;
            }
            bool? returnClientRequestId = default(bool?);
            if (poolUpdatePropertiesOptions != null)
            {
                returnClientRequestId = poolUpdatePropertiesOptions.ReturnClientRequestId;
            }
            DateTime? ocpDate = default(DateTime?);
            if (poolUpdatePropertiesOptions != null)
            {
                ocpDate = poolUpdatePropertiesOptions.OcpDate;
            }
            // Tracing
            bool _shouldTrace = ServiceClientTracing.IsEnabled;
            string _invocationId = null;
            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
                tracingParameters.Add("poolId", poolId);
                tracingParameters.Add("poolUpdatePropertiesParameter", poolUpdatePropertiesParameter);
                tracingParameters.Add("timeout", timeout);
                tracingParameters.Add("clientRequestId", clientRequestId);
                tracingParameters.Add("returnClientRequestId", returnClientRequestId);
                tracingParameters.Add("ocpDate", ocpDate);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "UpdateProperties", tracingParameters);
            }
            // Construct URL
            var _baseUrl = this.Client.BaseUri.AbsoluteUri;
            var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "pools/{poolId}/updateproperties").ToString();
            _url = _url.Replace("{poolId}", Uri.EscapeDataString(poolId));
            List<string> _queryParameters = new List<string>();
            if (this.Client.ApiVersion != null)
            {
                _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
            }
            if (timeout != null)
            {
                _queryParameters.Add(string.Format("timeout={0}", Uri.EscapeDataString(SafeJsonConvert.SerializeObject(timeout, this.Client.SerializationSettings).Trim('"'))));
            }
            if (_queryParameters.Count > 0)
            {
                _url += "?" + string.Join("&", _queryParameters);
            }
            // Create HTTP transport objects
            HttpRequestMessage _httpRequest = new HttpRequestMessage();
            HttpResponseMessage _httpResponse = null;
            _httpRequest.Method = new HttpMethod("POST");
            _httpRequest.RequestUri = new Uri(_url);
            // Set Headers
            if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
            {
                _httpRequest.Headers.TryAddWithoutValidation("client-request-id", Guid.NewGuid().ToString());
            }
            if (this.Client.AcceptLanguage != null)
            {
                if (_httpRequest.Headers.Contains("accept-language"))
                {
                    _httpRequest.Headers.Remove("accept-language");
                }
                _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
            }
            if (clientRequestId != null)
            {
                if (_httpRequest.Headers.Contains("client-request-id"))
                {
                    _httpRequest.Headers.Remove("client-request-id");
                }
                _httpRequest.Headers.TryAddWithoutValidation("client-request-id", clientRequestId);
            }
            if (returnClientRequestId != null)
            {
                if (_httpRequest.Headers.Contains("return-client-request-id"))
                {
                    _httpRequest.Headers.Remove("return-client-request-id");
                }
                _httpRequest.Headers.TryAddWithoutValidation("return-client-request-id", SafeJsonConvert.SerializeObject(returnClientRequestId, this.Client.SerializationSettings).Trim('"'));
            }
            if (ocpDate != null)
            {
                if (_httpRequest.Headers.Contains("ocp-date"))
                {
                    _httpRequest.Headers.Remove("ocp-date");
                }
                _httpRequest.Headers.TryAddWithoutValidation("ocp-date", SafeJsonConvert.SerializeObject(ocpDate, new DateTimeRfc1123JsonConverter()).Trim('"'));
            }
            if (customHeaders != null)
            {
                foreach(var _header in customHeaders)
                {
                    if (_httpRequest.Headers.Contains(_header.Key))
                    {
                        _httpRequest.Headers.Remove(_header.Key);
                    }
                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
                }
            }

            // Serialize Request
            string _requestContent = null;
            if(poolUpdatePropertiesParameter != null)
            {
                _requestContent = SafeJsonConvert.SerializeObject(poolUpdatePropertiesParameter, this.Client.SerializationSettings);
                _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8);
                _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; odata=minimalmetadata; charset=utf-8");
            }
            // Set Credentials
            if (this.Client.Credentials != null)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            }
            // Send Request
            if (_shouldTrace)
            {
                ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            if (_shouldTrace)
            {
                ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
            }
            HttpStatusCode _statusCode = _httpResponse.StatusCode;
            cancellationToken.ThrowIfCancellationRequested();
            string _responseContent = null;
            if ((int)_statusCode != 204)
            {
                var ex = new BatchErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                try
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
                    BatchError _errorBody = SafeJsonConvert.DeserializeObject<BatchError>(_responseContent, this.Client.DeserializationSettings);
                    if (_errorBody != null)
                    {
                        ex.Body = _errorBody;
                    }
                }
                catch (JsonException)
                {
                    // Ignore the exception
                }
                ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
                ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
                if (_shouldTrace)
                {
                    ServiceClientTracing.Error(_invocationId, ex);
                }
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            // Create Result
            var _result = new AzureOperationHeaderResponse<PoolUpdatePropertiesHeaders>();
            _result.Request = _httpRequest;
            _result.Response = _httpResponse;
            if (_httpResponse.Headers.Contains("request-id"))
            {
                _result.RequestId = _httpResponse.Headers.GetValues("request-id").FirstOrDefault();
            }
            try
            {
                _result.Headers = _httpResponse.GetHeadersAsJson().ToObject<PoolUpdatePropertiesHeaders>(JsonSerializer.Create(this.Client.DeserializationSettings));
            }
            catch (JsonException ex)
            {
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw new SerializationException("Unable to deserialize the headers.", _httpResponse.GetHeadersAsJson().ToString(), ex);
            }
            if (_shouldTrace)
            {
                ServiceClientTracing.Exit(_invocationId, _result);
            }
            return _result;
        }

        /// <summary>
        /// Upgrades the operating system of the specified pool.
        /// </summary>
        /// <param name='poolId'>
        /// The id of the pool to upgrade.
        /// </param>
        /// <param name='targetOSVersion'>
        /// The Azure Guest OS version to be installed on the virtual machines in the
        /// pool.
        /// </param>
        /// <param name='poolUpgradeOSOptions'>
        /// Additional parameters for the operation
        /// </param>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="BatchErrorException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public async Task<AzureOperationHeaderResponse<PoolUpgradeOSHeaders>> UpgradeOSWithHttpMessagesAsync(string poolId, string targetOSVersion, PoolUpgradeOSOptions poolUpgradeOSOptions = default(PoolUpgradeOSOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (poolId == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "poolId");
            }
            if (this.Client.ApiVersion == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
            }
            if (targetOSVersion == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "targetOSVersion");
            }
            int? timeout = default(int?);
            if (poolUpgradeOSOptions != null)
            {
                timeout = poolUpgradeOSOptions.Timeout;
            }
            string clientRequestId = default(string);
            if (poolUpgradeOSOptions != null)
            {
                clientRequestId = poolUpgradeOSOptions.ClientRequestId;
            }
            bool? returnClientRequestId = default(bool?);
            if (poolUpgradeOSOptions != null)
            {
                returnClientRequestId = poolUpgradeOSOptions.ReturnClientRequestId;
            }
            DateTime? ocpDate = default(DateTime?);
            if (poolUpgradeOSOptions != null)
            {
                ocpDate = poolUpgradeOSOptions.OcpDate;
            }
            string ifMatch = default(string);
            if (poolUpgradeOSOptions != null)
            {
                ifMatch = poolUpgradeOSOptions.IfMatch;
            }
            string ifNoneMatch = default(string);
            if (poolUpgradeOSOptions != null)
            {
                ifNoneMatch = poolUpgradeOSOptions.IfNoneMatch;
            }
            DateTime? ifModifiedSince = default(DateTime?);
            if (poolUpgradeOSOptions != null)
            {
                ifModifiedSince = poolUpgradeOSOptions.IfModifiedSince;
            }
            DateTime? ifUnmodifiedSince = default(DateTime?);
            if (poolUpgradeOSOptions != null)
            {
                ifUnmodifiedSince = poolUpgradeOSOptions.IfUnmodifiedSince;
            }
            PoolUpgradeOSParameter poolUpgradeOSParameter = new PoolUpgradeOSParameter();
            if (targetOSVersion != null)
            {
                poolUpgradeOSParameter.TargetOSVersion = targetOSVersion;
            }
            // Tracing
            bool _shouldTrace = ServiceClientTracing.IsEnabled;
            string _invocationId = null;
            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
                tracingParameters.Add("poolId", poolId);
                tracingParameters.Add("timeout", timeout);
                tracingParameters.Add("clientRequestId", clientRequestId);
                tracingParameters.Add("returnClientRequestId", returnClientRequestId);
                tracingParameters.Add("ocpDate", ocpDate);
                tracingParameters.Add("ifMatch", ifMatch);
                tracingParameters.Add("ifNoneMatch", ifNoneMatch);
                tracingParameters.Add("ifModifiedSince", ifModifiedSince);
                tracingParameters.Add("ifUnmodifiedSince", ifUnmodifiedSince);
                tracingParameters.Add("poolUpgradeOSParameter", poolUpgradeOSParameter);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "UpgradeOS", tracingParameters);
            }
            // Construct URL
            var _baseUrl = this.Client.BaseUri.AbsoluteUri;
            var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "pools/{poolId}/upgradeos").ToString();
            _url = _url.Replace("{poolId}", Uri.EscapeDataString(poolId));
            List<string> _queryParameters = new List<string>();
            if (this.Client.ApiVersion != null)
            {
                _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
            }
            if (timeout != null)
            {
                _queryParameters.Add(string.Format("timeout={0}", Uri.EscapeDataString(SafeJsonConvert.SerializeObject(timeout, this.Client.SerializationSettings).Trim('"'))));
            }
            if (_queryParameters.Count > 0)
            {
                _url += "?" + string.Join("&", _queryParameters);
            }
            // Create HTTP transport objects
            HttpRequestMessage _httpRequest = new HttpRequestMessage();
            HttpResponseMessage _httpResponse = null;
            _httpRequest.Method = new HttpMethod("POST");
            _httpRequest.RequestUri = new Uri(_url);
            // Set Headers
            if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
            {
                _httpRequest.Headers.TryAddWithoutValidation("client-request-id", Guid.NewGuid().ToString());
            }
            if (this.Client.AcceptLanguage != null)
            {
                if (_httpRequest.Headers.Contains("accept-language"))
                {
                    _httpRequest.Headers.Remove("accept-language");
                }
                _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
            }
            if (clientRequestId != null)
            {
                if (_httpRequest.Headers.Contains("client-request-id"))
                {
                    _httpRequest.Headers.Remove("client-request-id");
                }
                _httpRequest.Headers.TryAddWithoutValidation("client-request-id", clientRequestId);
            }
            if (returnClientRequestId != null)
            {
                if (_httpRequest.Headers.Contains("return-client-request-id"))
                {
                    _httpRequest.Headers.Remove("return-client-request-id");
                }
                _httpRequest.Headers.TryAddWithoutValidation("return-client-request-id", SafeJsonConvert.SerializeObject(returnClientRequestId, this.Client.SerializationSettings).Trim('"'));
            }
            if (ocpDate != null)
            {
                if (_httpRequest.Headers.Contains("ocp-date"))
                {
                    _httpRequest.Headers.Remove("ocp-date");
                }
                _httpRequest.Headers.TryAddWithoutValidation("ocp-date", SafeJsonConvert.SerializeObject(ocpDate, new DateTimeRfc1123JsonConverter()).Trim('"'));
            }
            if (ifMatch != null)
            {
                if (_httpRequest.Headers.Contains("If-Match"))
                {
                    _httpRequest.Headers.Remove("If-Match");
                }
                _httpRequest.Headers.TryAddWithoutValidation("If-Match", ifMatch);
            }
            if (ifNoneMatch != null)
            {
                if (_httpRequest.Headers.Contains("If-None-Match"))
                {
                    _httpRequest.Headers.Remove("If-None-Match");
                }
                _httpRequest.Headers.TryAddWithoutValidation("If-None-Match", ifNoneMatch);
            }
            if (ifModifiedSince != null)
            {
                if (_httpRequest.Headers.Contains("If-Modified-Since"))
                {
                    _httpRequest.Headers.Remove("If-Modified-Since");
                }
                _httpRequest.Headers.TryAddWithoutValidation("If-Modified-Since", SafeJsonConvert.SerializeObject(ifModifiedSince, new DateTimeRfc1123JsonConverter()).Trim('"'));
            }
            if (ifUnmodifiedSince != null)
            {
                if (_httpRequest.Headers.Contains("If-Unmodified-Since"))
                {
                    _httpRequest.Headers.Remove("If-Unmodified-Since");
                }
                _httpRequest.Headers.TryAddWithoutValidation("If-Unmodified-Since", SafeJsonConvert.SerializeObject(ifUnmodifiedSince, new DateTimeRfc1123JsonConverter()).Trim('"'));
            }
            if (customHeaders != null)
            {
                foreach(var _header in customHeaders)
                {
                    if (_httpRequest.Headers.Contains(_header.Key))
                    {
                        _httpRequest.Headers.Remove(_header.Key);
                    }
                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
                }
            }

            // Serialize Request
            string _requestContent = null;
            if(poolUpgradeOSParameter != null)
            {
                _requestContent = SafeJsonConvert.SerializeObject(poolUpgradeOSParameter, this.Client.SerializationSettings);
                _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8);
                _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; odata=minimalmetadata; charset=utf-8");
            }
            // Set Credentials
            if (this.Client.Credentials != null)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            }
            // Send Request
            if (_shouldTrace)
            {
                ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            if (_shouldTrace)
            {
                ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
            }
            HttpStatusCode _statusCode = _httpResponse.StatusCode;
            cancellationToken.ThrowIfCancellationRequested();
            string _responseContent = null;
            if ((int)_statusCode != 202)
            {
                var ex = new BatchErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                try
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
                    BatchError _errorBody = SafeJsonConvert.DeserializeObject<BatchError>(_responseContent, this.Client.DeserializationSettings);
                    if (_errorBody != null)
                    {
                        ex.Body = _errorBody;
                    }
                }
                catch (JsonException)
                {
                    // Ignore the exception
                }
                ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
                ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
                if (_shouldTrace)
                {
                    ServiceClientTracing.Error(_invocationId, ex);
                }
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            // Create Result
            var _result = new AzureOperationHeaderResponse<PoolUpgradeOSHeaders>();
            _result.Request = _httpRequest;
            _result.Response = _httpResponse;
            if (_httpResponse.Headers.Contains("request-id"))
            {
                _result.RequestId = _httpResponse.Headers.GetValues("request-id").FirstOrDefault();
            }
            try
            {
                _result.Headers = _httpResponse.GetHeadersAsJson().ToObject<PoolUpgradeOSHeaders>(JsonSerializer.Create(this.Client.DeserializationSettings));
            }
            catch (JsonException ex)
            {
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw new SerializationException("Unable to deserialize the headers.", _httpResponse.GetHeadersAsJson().ToString(), ex);
            }
            if (_shouldTrace)
            {
                ServiceClientTracing.Exit(_invocationId, _result);
            }
            return _result;
        }

        /// <summary>
        /// Removes compute nodes from the specified pool.
        /// </summary>
        /// <param name='poolId'>
        /// The id of the pool from which you want to remove nodes.
        /// </param>
        /// <param name='nodeRemoveParameter'>
        /// The parameters for the request.
        /// </param>
        /// <param name='poolRemoveNodesOptions'>
        /// Additional parameters for the operation
        /// </param>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="BatchErrorException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public async Task<AzureOperationHeaderResponse<PoolRemoveNodesHeaders>> RemoveNodesWithHttpMessagesAsync(string poolId, NodeRemoveParameter nodeRemoveParameter, PoolRemoveNodesOptions poolRemoveNodesOptions = default(PoolRemoveNodesOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (poolId == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "poolId");
            }
            if (nodeRemoveParameter == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "nodeRemoveParameter");
            }
            if (nodeRemoveParameter != null)
            {
                nodeRemoveParameter.Validate();
            }
            if (this.Client.ApiVersion == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
            }
            int? timeout = default(int?);
            if (poolRemoveNodesOptions != null)
            {
                timeout = poolRemoveNodesOptions.Timeout;
            }
            string clientRequestId = default(string);
            if (poolRemoveNodesOptions != null)
            {
                clientRequestId = poolRemoveNodesOptions.ClientRequestId;
            }
            bool? returnClientRequestId = default(bool?);
            if (poolRemoveNodesOptions != null)
            {
                returnClientRequestId = poolRemoveNodesOptions.ReturnClientRequestId;
            }
            DateTime? ocpDate = default(DateTime?);
            if (poolRemoveNodesOptions != null)
            {
                ocpDate = poolRemoveNodesOptions.OcpDate;
            }
            string ifMatch = default(string);
            if (poolRemoveNodesOptions != null)
            {
                ifMatch = poolRemoveNodesOptions.IfMatch;
            }
            string ifNoneMatch = default(string);
            if (poolRemoveNodesOptions != null)
            {
                ifNoneMatch = poolRemoveNodesOptions.IfNoneMatch;
            }
            DateTime? ifModifiedSince = default(DateTime?);
            if (poolRemoveNodesOptions != null)
            {
                ifModifiedSince = poolRemoveNodesOptions.IfModifiedSince;
            }
            DateTime? ifUnmodifiedSince = default(DateTime?);
            if (poolRemoveNodesOptions != null)
            {
                ifUnmodifiedSince = poolRemoveNodesOptions.IfUnmodifiedSince;
            }
            // Tracing
            bool _shouldTrace = ServiceClientTracing.IsEnabled;
            string _invocationId = null;
            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
                tracingParameters.Add("poolId", poolId);
                tracingParameters.Add("nodeRemoveParameter", nodeRemoveParameter);
                tracingParameters.Add("timeout", timeout);
                tracingParameters.Add("clientRequestId", clientRequestId);
                tracingParameters.Add("returnClientRequestId", returnClientRequestId);
                tracingParameters.Add("ocpDate", ocpDate);
                tracingParameters.Add("ifMatch", ifMatch);
                tracingParameters.Add("ifNoneMatch", ifNoneMatch);
                tracingParameters.Add("ifModifiedSince", ifModifiedSince);
                tracingParameters.Add("ifUnmodifiedSince", ifUnmodifiedSince);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "RemoveNodes", tracingParameters);
            }
            // Construct URL
            var _baseUrl = this.Client.BaseUri.AbsoluteUri;
            var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "pools/{poolId}/removenodes").ToString();
            _url = _url.Replace("{poolId}", Uri.EscapeDataString(poolId));
            List<string> _queryParameters = new List<string>();
            if (this.Client.ApiVersion != null)
            {
                _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
            }
            if (timeout != null)
            {
                _queryParameters.Add(string.Format("timeout={0}", Uri.EscapeDataString(SafeJsonConvert.SerializeObject(timeout, this.Client.SerializationSettings).Trim('"'))));
            }
            if (_queryParameters.Count > 0)
            {
                _url += "?" + string.Join("&", _queryParameters);
            }
            // Create HTTP transport objects
            HttpRequestMessage _httpRequest = new HttpRequestMessage();
            HttpResponseMessage _httpResponse = null;
            _httpRequest.Method = new HttpMethod("POST");
            _httpRequest.RequestUri = new Uri(_url);
            // Set Headers
            if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
            {
                _httpRequest.Headers.TryAddWithoutValidation("client-request-id", Guid.NewGuid().ToString());
            }
            if (this.Client.AcceptLanguage != null)
            {
                if (_httpRequest.Headers.Contains("accept-language"))
                {
                    _httpRequest.Headers.Remove("accept-language");
                }
                _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
            }
            if (clientRequestId != null)
            {
                if (_httpRequest.Headers.Contains("client-request-id"))
                {
                    _httpRequest.Headers.Remove("client-request-id");
                }
                _httpRequest.Headers.TryAddWithoutValidation("client-request-id", clientRequestId);
            }
            if (returnClientRequestId != null)
            {
                if (_httpRequest.Headers.Contains("return-client-request-id"))
                {
                    _httpRequest.Headers.Remove("return-client-request-id");
                }
                _httpRequest.Headers.TryAddWithoutValidation("return-client-request-id", SafeJsonConvert.SerializeObject(returnClientRequestId, this.Client.SerializationSettings).Trim('"'));
            }
            if (ocpDate != null)
            {
                if (_httpRequest.Headers.Contains("ocp-date"))
                {
                    _httpRequest.Headers.Remove("ocp-date");
                }
                _httpRequest.Headers.TryAddWithoutValidation("ocp-date", SafeJsonConvert.SerializeObject(ocpDate, new DateTimeRfc1123JsonConverter()).Trim('"'));
            }
            if (ifMatch != null)
            {
                if (_httpRequest.Headers.Contains("If-Match"))
                {
                    _httpRequest.Headers.Remove("If-Match");
                }
                _httpRequest.Headers.TryAddWithoutValidation("If-Match", ifMatch);
            }
            if (ifNoneMatch != null)
            {
                if (_httpRequest.Headers.Contains("If-None-Match"))
                {
                    _httpRequest.Headers.Remove("If-None-Match");
                }
                _httpRequest.Headers.TryAddWithoutValidation("If-None-Match", ifNoneMatch);
            }
            if (ifModifiedSince != null)
            {
                if (_httpRequest.Headers.Contains("If-Modified-Since"))
                {
                    _httpRequest.Headers.Remove("If-Modified-Since");
                }
                _httpRequest.Headers.TryAddWithoutValidation("If-Modified-Since", SafeJsonConvert.SerializeObject(ifModifiedSince, new DateTimeRfc1123JsonConverter()).Trim('"'));
            }
            if (ifUnmodifiedSince != null)
            {
                if (_httpRequest.Headers.Contains("If-Unmodified-Since"))
                {
                    _httpRequest.Headers.Remove("If-Unmodified-Since");
                }
                _httpRequest.Headers.TryAddWithoutValidation("If-Unmodified-Since", SafeJsonConvert.SerializeObject(ifUnmodifiedSince, new DateTimeRfc1123JsonConverter()).Trim('"'));
            }
            if (customHeaders != null)
            {
                foreach(var _header in customHeaders)
                {
                    if (_httpRequest.Headers.Contains(_header.Key))
                    {
                        _httpRequest.Headers.Remove(_header.Key);
                    }
                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
                }
            }

            // Serialize Request
            string _requestContent = null;
            if(nodeRemoveParameter != null)
            {
                _requestContent = SafeJsonConvert.SerializeObject(nodeRemoveParameter, this.Client.SerializationSettings);
                _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8);
                _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; odata=minimalmetadata; charset=utf-8");
            }
            // Set Credentials
            if (this.Client.Credentials != null)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            }
            // Send Request
            if (_shouldTrace)
            {
                ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            if (_shouldTrace)
            {
                ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
            }
            HttpStatusCode _statusCode = _httpResponse.StatusCode;
            cancellationToken.ThrowIfCancellationRequested();
            string _responseContent = null;
            if ((int)_statusCode != 202)
            {
                var ex = new BatchErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                try
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
                    BatchError _errorBody = SafeJsonConvert.DeserializeObject<BatchError>(_responseContent, this.Client.DeserializationSettings);
                    if (_errorBody != null)
                    {
                        ex.Body = _errorBody;
                    }
                }
                catch (JsonException)
                {
                    // Ignore the exception
                }
                ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
                ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
                if (_shouldTrace)
                {
                    ServiceClientTracing.Error(_invocationId, ex);
                }
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            // Create Result
            var _result = new AzureOperationHeaderResponse<PoolRemoveNodesHeaders>();
            _result.Request = _httpRequest;
            _result.Response = _httpResponse;
            if (_httpResponse.Headers.Contains("request-id"))
            {
                _result.RequestId = _httpResponse.Headers.GetValues("request-id").FirstOrDefault();
            }
            try
            {
                _result.Headers = _httpResponse.GetHeadersAsJson().ToObject<PoolRemoveNodesHeaders>(JsonSerializer.Create(this.Client.DeserializationSettings));
            }
            catch (JsonException ex)
            {
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw new SerializationException("Unable to deserialize the headers.", _httpResponse.GetHeadersAsJson().ToString(), ex);
            }
            if (_shouldTrace)
            {
                ServiceClientTracing.Exit(_invocationId, _result);
            }
            return _result;
        }

        /// <summary>
        /// Lists the usage metrics, aggregated by pool across individual time
        /// intervals, for the specified account.
        /// </summary>
        /// <param name='nextPageLink'>
        /// The NextLink from the previous successful call to List operation.
        /// </param>
        /// <param name='poolListPoolUsageMetricsNextOptions'>
        /// Additional parameters for the operation
        /// </param>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="BatchErrorException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public async Task<AzureOperationResponse<IPage<PoolUsageMetrics>,PoolListPoolUsageMetricsHeaders>> ListPoolUsageMetricsNextWithHttpMessagesAsync(string nextPageLink, PoolListPoolUsageMetricsNextOptions poolListPoolUsageMetricsNextOptions = default(PoolListPoolUsageMetricsNextOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (nextPageLink == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
            }
            string clientRequestId = default(string);
            if (poolListPoolUsageMetricsNextOptions != null)
            {
                clientRequestId = poolListPoolUsageMetricsNextOptions.ClientRequestId;
            }
            bool? returnClientRequestId = default(bool?);
            if (poolListPoolUsageMetricsNextOptions != null)
            {
                returnClientRequestId = poolListPoolUsageMetricsNextOptions.ReturnClientRequestId;
            }
            DateTime? ocpDate = default(DateTime?);
            if (poolListPoolUsageMetricsNextOptions != null)
            {
                ocpDate = poolListPoolUsageMetricsNextOptions.OcpDate;
            }
            // Tracing
            bool _shouldTrace = ServiceClientTracing.IsEnabled;
            string _invocationId = null;
            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
                tracingParameters.Add("nextPageLink", nextPageLink);
                tracingParameters.Add("clientRequestId", clientRequestId);
                tracingParameters.Add("returnClientRequestId", returnClientRequestId);
                tracingParameters.Add("ocpDate", ocpDate);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "ListPoolUsageMetricsNext", tracingParameters);
            }
            // Construct URL
            string _url = "{nextLink}";
            _url = _url.Replace("{nextLink}", nextPageLink);
            List<string> _queryParameters = new List<string>();
            if (_queryParameters.Count > 0)
            {
                _url += "?" + string.Join("&", _queryParameters);
            }
            // Create HTTP transport objects
            HttpRequestMessage _httpRequest = new HttpRequestMessage();
            HttpResponseMessage _httpResponse = null;
            _httpRequest.Method = new HttpMethod("GET");
            _httpRequest.RequestUri = new Uri(_url);
            // Set Headers
            if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
            {
                _httpRequest.Headers.TryAddWithoutValidation("client-request-id", Guid.NewGuid().ToString());
            }
            if (this.Client.AcceptLanguage != null)
            {
                if (_httpRequest.Headers.Contains("accept-language"))
                {
                    _httpRequest.Headers.Remove("accept-language");
                }
                _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
            }
            if (clientRequestId != null)
            {
                if (_httpRequest.Headers.Contains("client-request-id"))
                {
                    _httpRequest.Headers.Remove("client-request-id");
                }
                _httpRequest.Headers.TryAddWithoutValidation("client-request-id", clientRequestId);
            }
            if (returnClientRequestId != null)
            {
                if (_httpRequest.Headers.Contains("return-client-request-id"))
                {
                    _httpRequest.Headers.Remove("return-client-request-id");
                }
                _httpRequest.Headers.TryAddWithoutValidation("return-client-request-id", SafeJsonConvert.SerializeObject(returnClientRequestId, this.Client.SerializationSettings).Trim('"'));
            }
            if (ocpDate != null)
            {
                if (_httpRequest.Headers.Contains("ocp-date"))
                {
                    _httpRequest.Headers.Remove("ocp-date");
                }
                _httpRequest.Headers.TryAddWithoutValidation("ocp-date", SafeJsonConvert.SerializeObject(ocpDate, new DateTimeRfc1123JsonConverter()).Trim('"'));
            }
            if (customHeaders != null)
            {
                foreach(var _header in customHeaders)
                {
                    if (_httpRequest.Headers.Contains(_header.Key))
                    {
                        _httpRequest.Headers.Remove(_header.Key);
                    }
                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
                }
            }

            // Serialize Request
            string _requestContent = null;
            // Set Credentials
            if (this.Client.Credentials != null)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            }
            // Send Request
            if (_shouldTrace)
            {
                ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            if (_shouldTrace)
            {
                ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
            }
            HttpStatusCode _statusCode = _httpResponse.StatusCode;
            cancellationToken.ThrowIfCancellationRequested();
            string _responseContent = null;
            if ((int)_statusCode != 200)
            {
                var ex = new BatchErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                try
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
                    BatchError _errorBody = SafeJsonConvert.DeserializeObject<BatchError>(_responseContent, this.Client.DeserializationSettings);
                    if (_errorBody != null)
                    {
                        ex.Body = _errorBody;
                    }
                }
                catch (JsonException)
                {
                    // Ignore the exception
                }
                ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
                ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
                if (_shouldTrace)
                {
                    ServiceClientTracing.Error(_invocationId, ex);
                }
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            // Create Result
            var _result = new AzureOperationResponse<IPage<PoolUsageMetrics>,PoolListPoolUsageMetricsHeaders>();
            _result.Request = _httpRequest;
            _result.Response = _httpResponse;
            if (_httpResponse.Headers.Contains("request-id"))
            {
                _result.RequestId = _httpResponse.Headers.GetValues("request-id").FirstOrDefault();
            }
            // Deserialize Response
            if ((int)_statusCode == 200)
            {
                _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
                try
                {
                    _result.Body = SafeJsonConvert.DeserializeObject<Page<PoolUsageMetrics>>(_responseContent, this.Client.DeserializationSettings);
                }
                catch (JsonException ex)
                {
                    _httpRequest.Dispose();
                    if (_httpResponse != null)
                    {
                        _httpResponse.Dispose();
                    }
                    throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
                }
            }
            try
            {
                _result.Headers = _httpResponse.GetHeadersAsJson().ToObject<PoolListPoolUsageMetricsHeaders>(JsonSerializer.Create(this.Client.DeserializationSettings));
            }
            catch (JsonException ex)
            {
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw new SerializationException("Unable to deserialize the headers.", _httpResponse.GetHeadersAsJson().ToString(), ex);
            }
            if (_shouldTrace)
            {
                ServiceClientTracing.Exit(_invocationId, _result);
            }
            return _result;
        }

        /// <summary>
        /// Lists all of the pools in the specified account.
        /// </summary>
        /// <param name='nextPageLink'>
        /// The NextLink from the previous successful call to List operation.
        /// </param>
        /// <param name='poolListNextOptions'>
        /// Additional parameters for the operation
        /// </param>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="BatchErrorException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public async Task<AzureOperationResponse<IPage<CloudPool>,PoolListHeaders>> ListNextWithHttpMessagesAsync(string nextPageLink, PoolListNextOptions poolListNextOptions = default(PoolListNextOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (nextPageLink == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
            }
            string clientRequestId = default(string);
            if (poolListNextOptions != null)
            {
                clientRequestId = poolListNextOptions.ClientRequestId;
            }
            bool? returnClientRequestId = default(bool?);
            if (poolListNextOptions != null)
            {
                returnClientRequestId = poolListNextOptions.ReturnClientRequestId;
            }
            DateTime? ocpDate = default(DateTime?);
            if (poolListNextOptions != null)
            {
                ocpDate = poolListNextOptions.OcpDate;
            }
            // Tracing
            bool _shouldTrace = ServiceClientTracing.IsEnabled;
            string _invocationId = null;
            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
                tracingParameters.Add("nextPageLink", nextPageLink);
                tracingParameters.Add("clientRequestId", clientRequestId);
                tracingParameters.Add("returnClientRequestId", returnClientRequestId);
                tracingParameters.Add("ocpDate", ocpDate);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters);
            }
            // Construct URL
            string _url = "{nextLink}";
            _url = _url.Replace("{nextLink}", nextPageLink);
            List<string> _queryParameters = new List<string>();
            if (_queryParameters.Count > 0)
            {
                _url += "?" + string.Join("&", _queryParameters);
            }
            // Create HTTP transport objects
            HttpRequestMessage _httpRequest = new HttpRequestMessage();
            HttpResponseMessage _httpResponse = null;
            _httpRequest.Method = new HttpMethod("GET");
            _httpRequest.RequestUri = new Uri(_url);
            // Set Headers
            if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
            {
                _httpRequest.Headers.TryAddWithoutValidation("client-request-id", Guid.NewGuid().ToString());
            }
            if (this.Client.AcceptLanguage != null)
            {
                if (_httpRequest.Headers.Contains("accept-language"))
                {
                    _httpRequest.Headers.Remove("accept-language");
                }
                _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
            }
            if (clientRequestId != null)
            {
                if (_httpRequest.Headers.Contains("client-request-id"))
                {
                    _httpRequest.Headers.Remove("client-request-id");
                }
                _httpRequest.Headers.TryAddWithoutValidation("client-request-id", clientRequestId);
            }
            if (returnClientRequestId != null)
            {
                if (_httpRequest.Headers.Contains("return-client-request-id"))
                {
                    _httpRequest.Headers.Remove("return-client-request-id");
                }
                _httpRequest.Headers.TryAddWithoutValidation("return-client-request-id", SafeJsonConvert.SerializeObject(returnClientRequestId, this.Client.SerializationSettings).Trim('"'));
            }
            if (ocpDate != null)
            {
                if (_httpRequest.Headers.Contains("ocp-date"))
                {
                    _httpRequest.Headers.Remove("ocp-date");
                }
                _httpRequest.Headers.TryAddWithoutValidation("ocp-date", SafeJsonConvert.SerializeObject(ocpDate, new DateTimeRfc1123JsonConverter()).Trim('"'));
            }
            if (customHeaders != null)
            {
                foreach(var _header in customHeaders)
                {
                    if (_httpRequest.Headers.Contains(_header.Key))
                    {
                        _httpRequest.Headers.Remove(_header.Key);
                    }
                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
                }
            }

            // Serialize Request
            string _requestContent = null;
            // Set Credentials
            if (this.Client.Credentials != null)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            }
            // Send Request
            if (_shouldTrace)
            {
                ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            if (_shouldTrace)
            {
                ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
            }
            HttpStatusCode _statusCode = _httpResponse.StatusCode;
            cancellationToken.ThrowIfCancellationRequested();
            string _responseContent = null;
            if ((int)_statusCode != 200)
            {
                var ex = new BatchErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                try
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
                    BatchError _errorBody = SafeJsonConvert.DeserializeObject<BatchError>(_responseContent, this.Client.DeserializationSettings);
                    if (_errorBody != null)
                    {
                        ex.Body = _errorBody;
                    }
                }
                catch (JsonException)
                {
                    // Ignore the exception
                }
                ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
                ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
                if (_shouldTrace)
                {
                    ServiceClientTracing.Error(_invocationId, ex);
                }
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            // Create Result
            var _result = new AzureOperationResponse<IPage<CloudPool>,PoolListHeaders>();
            _result.Request = _httpRequest;
            _result.Response = _httpResponse;
            if (_httpResponse.Headers.Contains("request-id"))
            {
                _result.RequestId = _httpResponse.Headers.GetValues("request-id").FirstOrDefault();
            }
            // Deserialize Response
            if ((int)_statusCode == 200)
            {
                _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
                try
                {
                    _result.Body = SafeJsonConvert.DeserializeObject<Page<CloudPool>>(_responseContent, this.Client.DeserializationSettings);
                }
                catch (JsonException ex)
                {
                    _httpRequest.Dispose();
                    if (_httpResponse != null)
                    {
                        _httpResponse.Dispose();
                    }
                    throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
                }
            }
            try
            {
                _result.Headers = _httpResponse.GetHeadersAsJson().ToObject<PoolListHeaders>(JsonSerializer.Create(this.Client.DeserializationSettings));
            }
            catch (JsonException ex)
            {
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw new SerializationException("Unable to deserialize the headers.", _httpResponse.GetHeadersAsJson().ToString(), ex);
            }
            if (_shouldTrace)
            {
                ServiceClientTracing.Exit(_invocationId, _result);
            }
            return _result;
        }

    }
}
