text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Hyak.Common;
using Hyak.Common.Internals;
using Microsoft.WindowsAzure.Management.RemoteApp;
using Microsoft.WindowsAzure.Management.RemoteApp.Models;
using Newtonsoft.Json.Linq;

namespace Microsoft.WindowsAzure.Management.RemoteApp
{
    /// <summary>
    /// RemoteApp collection operations.
    /// </summary>
    internal partial class CollectionOperations : IServiceOperations<RemoteAppManagementClient>, ICollectionOperations
    {
        /// <summary>
        /// Initializes a new instance of the CollectionOperations class.
        /// </summary>
        /// <param name='client'>
        /// Reference to the service client.
        /// </param>
        internal CollectionOperations(RemoteAppManagementClient client)
        {
            this._client = client;
        }

        private RemoteAppManagementClient _client;

        /// <summary>
        /// Gets a reference to the
        /// Microsoft.WindowsAzure.Management.RemoteApp.RemoteAppManagementClient.
        /// </summary>
        public RemoteAppManagementClient Client
        {
            get { return this._client; }
        }

        /// <summary>
        /// Creates a collection with the given details.
        /// </summary>
        /// <param name='populateOnly'>
        /// Required. A flag denoting if the request is to populate the
        /// creation details of the collection or update and deploy (true for
        /// populate only).
        /// </param>
        /// <param name='collectionDetails'>
        /// Required. Details for the collection to be created.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// The response containing the operation tracking id.
        /// </returns>
        public async Task<OperationResultWithTrackingId> CreateAsync(bool populateOnly, CollectionCreationDetails collectionDetails, CancellationToken cancellationToken)
        {
            // Validate
            if (collectionDetails == null)
            {
                throw new ArgumentNullException("collectionDetails");
            }
            if (collectionDetails.AdInfo != null)
            {
                if (collectionDetails.AdInfo.DomainName == null)
                {
                    throw new ArgumentNullException("collectionDetails.AdInfo.DomainName");
                }
                if (collectionDetails.AdInfo.Password == null)
                {
                    throw new ArgumentNullException("collectionDetails.AdInfo.Password");
                }
                if (collectionDetails.AdInfo.UserName == null)
                {
                    throw new ArgumentNullException("collectionDetails.AdInfo.UserName");
                }
            }
            if (collectionDetails.AllowedPrincipals != null)
            {
                foreach (SecurityPrincipal allowedPrincipalsParameterItem in collectionDetails.AllowedPrincipals)
                {
                    if (allowedPrincipalsParameterItem.Name == null)
                    {
                        throw new ArgumentNullException("collectionDetails.AllowedPrincipals.Name");
                    }
                }
            }
            if (collectionDetails.Name == null)
            {
                throw new ArgumentNullException("collectionDetails.Name");
            }
            if (collectionDetails.PlanName == null)
            {
                throw new ArgumentNullException("collectionDetails.PlanName");
            }
            if (collectionDetails.PublishedApplications != null)
            {
                foreach (PublishedApplicationDetails publishedApplicationsParameterItem in collectionDetails.PublishedApplications)
                {
                    if (publishedApplicationsParameterItem.Name == null)
                    {
                        throw new ArgumentNullException("collectionDetails.PublishedApplications.Name");
                    }
                }
            }

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

            // Construct URL
            string url = "";
            url = url + "/";
            if (this.Client.Credentials.SubscriptionId != null)
            {
                url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
            }
            url = url + "/services/";
            if (this.Client.RdfeNamespace != null)
            {
                url = url + Uri.EscapeDataString(this.Client.RdfeNamespace);
            }
            url = url + "/collections";
            List<string> queryParameters = new List<string>();
            queryParameters.Add("PopulateOnly=" + Uri.EscapeDataString(populateOnly.ToString().ToLower()));
            queryParameters.Add("api-version=2014-09-01");
            if (queryParameters.Count > 0)
            {
                url = url + "?" + string.Join("&", queryParameters);
            }
            string baseUrl = this.Client.BaseUri.AbsoluteUri;
            // Trim '/' character from the end of baseUrl and beginning of url.
            if (baseUrl[baseUrl.Length - 1] == '/')
            {
                baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
            }
            if (url[0] == '/')
            {
                url = url.Substring(1);
            }
            url = baseUrl + "/" + url;
            url = url.Replace(" ", "%20");

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

                // Set Headers
                httpRequest.Headers.Add("Accept", "application/json; charset=utf-8");
                httpRequest.Headers.Add("x-ms-version", "2014-08-01");

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

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

                JObject collectionCreationDetailsValue = new JObject();
                requestDoc = collectionCreationDetailsValue;

                collectionCreationDetailsValue["Name"] = collectionDetails.Name;

                if (collectionDetails.Description != null)
                {
                    collectionCreationDetailsValue["Description"] = collectionDetails.Description;
                }

                if (collectionDetails.TemplateImageName != null)
                {
                    collectionCreationDetailsValue["TemplateImageName"] = collectionDetails.TemplateImageName;
                }

                if (collectionDetails.VNetName != null)
                {
                    collectionCreationDetailsValue["VnetName"] = collectionDetails.VNetName;
                }

                if (collectionDetails.AdInfo != null)
                {
                    JObject adInfoValue = new JObject();
                    collectionCreationDetailsValue["AdInfo"] = adInfoValue;

                    adInfoValue["DomainName"] = collectionDetails.AdInfo.DomainName;

                    if (collectionDetails.AdInfo.OrganizationalUnit != null)
                    {
                        adInfoValue["OrganizationalUnit"] = collectionDetails.AdInfo.OrganizationalUnit;
                    }

                    adInfoValue["ServiceAccountUserName"] = collectionDetails.AdInfo.UserName;

                    adInfoValue["ServiceAccountPassword"] = collectionDetails.AdInfo.Password;
                }

                collectionCreationDetailsValue["BillingPlanName"] = collectionDetails.PlanName;

                if (collectionDetails.CustomRdpProperty != null)
                {
                    collectionCreationDetailsValue["CustomRdpProperty"] = collectionDetails.CustomRdpProperty;
                }

                collectionCreationDetailsValue["ReadyForPublishing"] = collectionDetails.ReadyForPublishing;

                collectionCreationDetailsValue["Mode"] = ((int)collectionDetails.Mode);

                if (collectionDetails.Region != null)
                {
                    collectionCreationDetailsValue["Region"] = collectionDetails.Region;
                }

                if (collectionDetails.PublishedApplications != null)
                {
                    if (collectionDetails.PublishedApplications is ILazyCollection == false || ((ILazyCollection)collectionDetails.PublishedApplications).IsInitialized)
                    {
                        JArray publishedApplicationsArray = new JArray();
                        foreach (PublishedApplicationDetails publishedApplicationsItem in collectionDetails.PublishedApplications)
                        {
                            JObject publishedApplicationDetailsValue = new JObject();
                            publishedApplicationsArray.Add(publishedApplicationDetailsValue);

                            publishedApplicationDetailsValue["AvailableToUsers"] = publishedApplicationsItem.AvailableToUsers;

                            if (publishedApplicationsItem.Alias != null)
                            {
                                publishedApplicationDetailsValue["Alias"] = publishedApplicationsItem.Alias;
                            }

                            if (publishedApplicationsItem.CommandLineArguments != null)
                            {
                                publishedApplicationDetailsValue["CommandLineArguments"] = publishedApplicationsItem.CommandLineArguments;
                            }

                            if (publishedApplicationsItem.IconUri != null)
                            {
                                publishedApplicationDetailsValue["IconUri"] = publishedApplicationsItem.IconUri;
                            }

                            publishedApplicationDetailsValue["Name"] = publishedApplicationsItem.Name;

                            publishedApplicationDetailsValue["Status"] = ((int)publishedApplicationsItem.Status);

                            if (publishedApplicationsItem.IconPngUris != null)
                            {
                                JObject iconPngUrisValue = new JObject();
                                publishedApplicationDetailsValue["IconPngUris"] = iconPngUrisValue;

                                if (publishedApplicationsItem.IconPngUris.IconPngUris != null)
                                {
                                    if (publishedApplicationsItem.IconPngUris.IconPngUris is ILazyCollection == false || ((ILazyCollection)publishedApplicationsItem.IconPngUris.IconPngUris).IsInitialized)
                                    {
                                        JArray iconPngUrisDictionary = new JArray();
                                        foreach (KeyValuePair<int, string> pair in publishedApplicationsItem.IconPngUris.IconPngUris)
                                        {
                                            int iconPngUrisKey = pair.Key;
                                            string iconPngUrisValue2 = pair.Value;
                                            JObject iconPngUrisItemObject = new JObject();
                                            iconPngUrisItemObject["Key"] = iconPngUrisKey.ToString();
                                            iconPngUrisItemObject["Value"] = iconPngUrisValue2;
                                            iconPngUrisDictionary.Add(iconPngUrisItemObject);
                                        }
                                        iconPngUrisValue["IconPngUris"] = iconPngUrisDictionary;
                                    }
                                }
                            }

                            if (publishedApplicationsItem.VirtualPath != null)
                            {
                                publishedApplicationDetailsValue["VirtualPath"] = publishedApplicationsItem.VirtualPath;
                            }
                        }
                        collectionCreationDetailsValue["PublishedApplications"] = publishedApplicationsArray;
                    }
                }

                if (collectionDetails.AllowedPrincipals != null)
                {
                    if (collectionDetails.AllowedPrincipals is ILazyCollection == false || ((ILazyCollection)collectionDetails.AllowedPrincipals).IsInitialized)
                    {
                        JArray allowedPrincipalsArray = new JArray();
                        foreach (SecurityPrincipal allowedPrincipalsItem in collectionDetails.AllowedPrincipals)
                        {
                            JObject securityPrincipalValue = new JObject();
                            allowedPrincipalsArray.Add(securityPrincipalValue);

                            securityPrincipalValue["SecurityPrincipalType"] = ((int)allowedPrincipalsItem.SecurityPrincipalType);

                            securityPrincipalValue["UserIdType"] = ((int)allowedPrincipalsItem.UserIdType);

                            securityPrincipalValue["Name"] = allowedPrincipalsItem.Name;

                            if (allowedPrincipalsItem.AadObjectId != null)
                            {
                                securityPrincipalValue["AadObjectId"] = allowedPrincipalsItem.AadObjectId;
                            }

                            if (allowedPrincipalsItem.Description != null)
                            {
                                securityPrincipalValue["Description"] = allowedPrincipalsItem.Description;
                            }
                        }
                        collectionCreationDetailsValue["AllowedPrincipals"] = allowedPrincipalsArray;
                    }
                }

                if (collectionDetails.DnsServers != null)
                {
                    if (collectionDetails.DnsServers is ILazyCollection == false || ((ILazyCollection)collectionDetails.DnsServers).IsInitialized)
                    {
                        JArray dnsServersArray = new JArray();
                        foreach (string dnsServersItem in collectionDetails.DnsServers)
                        {
                            dnsServersArray.Add(dnsServersItem);
                        }
                        collectionCreationDetailsValue["DnsServers"] = dnsServersArray;
                    }
                }

                if (collectionDetails.SubnetName != null)
                {
                    collectionCreationDetailsValue["SubnetName"] = collectionDetails.SubnetName;
                }

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

                // Send Request
                HttpResponseMessage httpResponse = null;
                try
                {
                    if (shouldTrace)
                    {
                        TracingAdapter.SendRequest(invocationId, httpRequest);
                    }
                    cancellationToken.ThrowIfCancellationRequested();
                    httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
                    if (shouldTrace)
                    {
                        TracingAdapter.ReceiveResponse(invocationId, httpResponse);
                    }
                    HttpStatusCode statusCode = httpResponse.StatusCode;
                    if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Accepted)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
                        if (shouldTrace)
                        {
                            TracingAdapter.Error(invocationId, ex);
                        }
                        throw ex;
                    }

                    // Create Result
                    OperationResultWithTrackingId result = null;
                    // Deserialize Response
                    result = new OperationResultWithTrackingId();
                    result.StatusCode = statusCode;
                    if (httpResponse.Headers.Contains("x-ms-request-id"))
                    {
                        result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
                    }
                    if (httpResponse.Headers.Contains("x-remoteapp-operation-tracking-id"))
                    {
                        result.TrackingId = httpResponse.Headers.GetValues("x-remoteapp-operation-tracking-id").FirstOrDefault();
                    }

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

        /// <summary>
        /// Deletes the given collection.
        /// </summary>
        /// <param name='collectionName'>
        /// Required. The name of the collection.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// The response containing the operation tracking id.
        /// </returns>
        public async Task<OperationResultWithTrackingId> DeleteAsync(string collectionName, CancellationToken cancellationToken)
        {
            // Validate
            if (collectionName == null)
            {
                throw new ArgumentNullException("collectionName");
            }

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

            // Construct URL
            string url = "";
            url = url + "/";
            if (this.Client.Credentials.SubscriptionId != null)
            {
                url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
            }
            url = url + "/services/";
            if (this.Client.RdfeNamespace != null)
            {
                url = url + Uri.EscapeDataString(this.Client.RdfeNamespace);
            }
            url = url + "/collections/";
            url = url + Uri.EscapeDataString(collectionName);
            List<string> queryParameters = new List<string>();
            queryParameters.Add("api-version=2014-09-01");
            if (queryParameters.Count > 0)
            {
                url = url + "?" + string.Join("&", queryParameters);
            }
            string baseUrl = this.Client.BaseUri.AbsoluteUri;
            // Trim '/' character from the end of baseUrl and beginning of url.
            if (baseUrl[baseUrl.Length - 1] == '/')
            {
                baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
            }
            if (url[0] == '/')
            {
                url = url.Substring(1);
            }
            url = baseUrl + "/" + url;
            url = url.Replace(" ", "%20");

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

                // Set Headers
                httpRequest.Headers.Add("x-ms-version", "2014-08-01");

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

                // Send Request
                HttpResponseMessage httpResponse = null;
                try
                {
                    if (shouldTrace)
                    {
                        TracingAdapter.SendRequest(invocationId, httpRequest);
                    }
                    cancellationToken.ThrowIfCancellationRequested();
                    httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
                    if (shouldTrace)
                    {
                        TracingAdapter.ReceiveResponse(invocationId, httpResponse);
                    }
                    HttpStatusCode statusCode = httpResponse.StatusCode;
                    if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Accepted)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
                        if (shouldTrace)
                        {
                            TracingAdapter.Error(invocationId, ex);
                        }
                        throw ex;
                    }

                    // Create Result
                    OperationResultWithTrackingId result = null;
                    // Deserialize Response
                    result = new OperationResultWithTrackingId();
                    result.StatusCode = statusCode;
                    if (httpResponse.Headers.Contains("x-ms-request-id"))
                    {
                        result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
                    }
                    if (httpResponse.Headers.Contains("x-remoteapp-operation-tracking-id"))
                    {
                        result.TrackingId = httpResponse.Headers.GetValues("x-remoteapp-operation-tracking-id").FirstOrDefault();
                    }

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

        /// <summary>
        /// Disconnects the session associated with the user UPN
        /// </summary>
        /// <param name='collectionName'>
        /// Required. The RemoteApp collection name where the session exists.
        /// </param>
        /// <param name='sessionParameter'>
        /// Required. The session command parameter to disconnect a session.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// The response containing the operation tracking id.
        /// </returns>
        public async Task<OperationResultWithTrackingId> DisconnectSessionAsync(string collectionName, SessionCommandParameter sessionParameter, CancellationToken cancellationToken)
        {
            // Validate
            if (collectionName == null)
            {
                throw new ArgumentNullException("collectionName");
            }
            if (sessionParameter == null)
            {
                throw new ArgumentNullException("sessionParameter");
            }
            if (sessionParameter.UserUpn == null)
            {
                throw new ArgumentNullException("sessionParameter.UserUpn");
            }

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

            // Construct URL
            string url = "";
            url = url + "/";
            if (this.Client.Credentials.SubscriptionId != null)
            {
                url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
            }
            url = url + "/services/";
            if (this.Client.RdfeNamespace != null)
            {
                url = url + Uri.EscapeDataString(this.Client.RdfeNamespace);
            }
            url = url + "/collections/";
            url = url + Uri.EscapeDataString(collectionName);
            url = url + "/sessions/disconnect";
            List<string> queryParameters = new List<string>();
            queryParameters.Add("api-version=2014-09-01");
            if (queryParameters.Count > 0)
            {
                url = url + "?" + string.Join("&", queryParameters);
            }
            string baseUrl = this.Client.BaseUri.AbsoluteUri;
            // Trim '/' character from the end of baseUrl and beginning of url.
            if (baseUrl[baseUrl.Length - 1] == '/')
            {
                baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
            }
            if (url[0] == '/')
            {
                url = url.Substring(1);
            }
            url = baseUrl + "/" + url;
            url = url.Replace(" ", "%20");

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

                // Set Headers
                httpRequest.Headers.Add("Accept", "application/json; charset=utf-8");
                httpRequest.Headers.Add("x-ms-version", "2014-08-01");

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

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

                JObject sessionCommandParameterValue = new JObject();
                requestDoc = sessionCommandParameterValue;

                sessionCommandParameterValue["UserUpn"] = sessionParameter.UserUpn;

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

                // Send Request
                HttpResponseMessage httpResponse = null;
                try
                {
                    if (shouldTrace)
                    {
                        TracingAdapter.SendRequest(invocationId, httpRequest);
                    }
                    cancellationToken.ThrowIfCancellationRequested();
                    httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
                    if (shouldTrace)
                    {
                        TracingAdapter.ReceiveResponse(invocationId, httpResponse);
                    }
                    HttpStatusCode statusCode = httpResponse.StatusCode;
                    if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Accepted)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
                        if (shouldTrace)
                        {
                            TracingAdapter.Error(invocationId, ex);
                        }
                        throw ex;
                    }

                    // Create Result
                    OperationResultWithTrackingId result = null;
                    // Deserialize Response
                    result = new OperationResultWithTrackingId();
                    result.StatusCode = statusCode;
                    if (httpResponse.Headers.Contains("x-ms-request-id"))
                    {
                        result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
                    }
                    if (httpResponse.Headers.Contains("x-remoteapp-operation-tracking-id"))
                    {
                        result.TrackingId = httpResponse.Headers.GetValues("x-remoteapp-operation-tracking-id").FirstOrDefault();
                    }

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

        /// <summary>
        /// Returns the result for a given collection
        /// </summary>
        /// <param name='collectionName'>
        /// Required. The name of the collection.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// The response for the GetServiceList operation.
        /// </returns>
        public async Task<CollectionResult> GetAsync(string collectionName, CancellationToken cancellationToken)
        {
            // Validate
            if (collectionName == null)
            {
                throw new ArgumentNullException("collectionName");
            }

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

            // Construct URL
            string url = "";
            url = url + "/";
            if (this.Client.Credentials.SubscriptionId != null)
            {
                url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
            }
            url = url + "/services/";
            if (this.Client.RdfeNamespace != null)
            {
                url = url + Uri.EscapeDataString(this.Client.RdfeNamespace);
            }
            url = url + "/collections/";
            url = url + Uri.EscapeDataString(collectionName);
            List<string> queryParameters = new List<string>();
            queryParameters.Add("api-version=2014-09-01");
            if (queryParameters.Count > 0)
            {
                url = url + "?" + string.Join("&", queryParameters);
            }
            string baseUrl = this.Client.BaseUri.AbsoluteUri;
            // Trim '/' character from the end of baseUrl and beginning of url.
            if (baseUrl[baseUrl.Length - 1] == '/')
            {
                baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
            }
            if (url[0] == '/')
            {
                url = url.Substring(1);
            }
            url = baseUrl + "/" + url;
            url = url.Replace(" ", "%20");

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

                // Set Headers
                httpRequest.Headers.Add("Accept", "application/json; charset=utf-8");
                httpRequest.Headers.Add("x-ms-version", "2014-08-01");

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

                // Send Request
                HttpResponseMessage httpResponse = null;
                try
                {
                    if (shouldTrace)
                    {
                        TracingAdapter.SendRequest(invocationId, httpRequest);
                    }
                    cancellationToken.ThrowIfCancellationRequested();
                    httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
                    if (shouldTrace)
                    {
                        TracingAdapter.ReceiveResponse(invocationId, httpResponse);
                    }
                    HttpStatusCode statusCode = httpResponse.StatusCode;
                    if (statusCode != HttpStatusCode.OK)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
                        if (shouldTrace)
                        {
                            TracingAdapter.Error(invocationId, ex);
                        }
                        throw ex;
                    }

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

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

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

                            JToken descriptionValue = responseDoc["Description"];
                            if (descriptionValue != null && descriptionValue.Type != JTokenType.Null)
                            {
                                string descriptionInstance = ((string)descriptionValue);
                                collectionInstance.Description = descriptionInstance;
                            }

                            JToken templateImageNameValue = responseDoc["TemplateImageName"];
                            if (templateImageNameValue != null && templateImageNameValue.Type != JTokenType.Null)
                            {
                                string templateImageNameInstance = ((string)templateImageNameValue);
                                collectionInstance.TemplateImageName = templateImageNameInstance;
                            }

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

                            JToken lastErrorCodeValue = responseDoc["LastErrorCode"];
                            if (lastErrorCodeValue != null && lastErrorCodeValue.Type != JTokenType.Null)
                            {
                                string lastErrorCodeInstance = ((string)lastErrorCodeValue);
                                collectionInstance.LastErrorCode = lastErrorCodeInstance;
                            }

                            JToken vnetNameValue = responseDoc["VnetName"];
                            if (vnetNameValue != null && vnetNameValue.Type != JTokenType.Null)
                            {
                                string vnetNameInstance = ((string)vnetNameValue);
                                collectionInstance.VNetName = vnetNameInstance;
                            }

                            JToken adInfoValue = responseDoc["AdInfo"];
                            if (adInfoValue != null && adInfoValue.Type != JTokenType.Null)
                            {
                                ActiveDirectoryConfig adInfoInstance = new ActiveDirectoryConfig();
                                collectionInstance.AdInfo = adInfoInstance;

                                JToken domainNameValue = adInfoValue["DomainName"];
                                if (domainNameValue != null && domainNameValue.Type != JTokenType.Null)
                                {
                                    string domainNameInstance = ((string)domainNameValue);
                                    adInfoInstance.DomainName = domainNameInstance;
                                }

                                JToken organizationalUnitValue = adInfoValue["OrganizationalUnit"];
                                if (organizationalUnitValue != null && organizationalUnitValue.Type != JTokenType.Null)
                                {
                                    string organizationalUnitInstance = ((string)organizationalUnitValue);
                                    adInfoInstance.OrganizationalUnit = organizationalUnitInstance;
                                }

                                JToken serviceAccountUserNameValue = adInfoValue["ServiceAccountUserName"];
                                if (serviceAccountUserNameValue != null && serviceAccountUserNameValue.Type != JTokenType.Null)
                                {
                                    string serviceAccountUserNameInstance = ((string)serviceAccountUserNameValue);
                                    adInfoInstance.UserName = serviceAccountUserNameInstance;
                                }

                                JToken serviceAccountPasswordValue = adInfoValue["ServiceAccountPassword"];
                                if (serviceAccountPasswordValue != null && serviceAccountPasswordValue.Type != JTokenType.Null)
                                {
                                    string serviceAccountPasswordInstance = ((string)serviceAccountPasswordValue);
                                    adInfoInstance.Password = serviceAccountPasswordInstance;
                                }
                            }

                            JToken billingPlanNameValue = responseDoc["BillingPlanName"];
                            if (billingPlanNameValue != null && billingPlanNameValue.Type != JTokenType.Null)
                            {
                                string billingPlanNameInstance = ((string)billingPlanNameValue);
                                collectionInstance.PlanName = billingPlanNameInstance;
                            }

                            JToken customRdpPropertyValue = responseDoc["CustomRdpProperty"];
                            if (customRdpPropertyValue != null && customRdpPropertyValue.Type != JTokenType.Null)
                            {
                                string customRdpPropertyInstance = ((string)customRdpPropertyValue);
                                collectionInstance.CustomRdpProperty = customRdpPropertyInstance;
                            }

                            JToken readyForPublishingValue = responseDoc["ReadyForPublishing"];
                            if (readyForPublishingValue != null && readyForPublishingValue.Type != JTokenType.Null)
                            {
                                bool readyForPublishingInstance = ((bool)readyForPublishingValue);
                                collectionInstance.ReadyForPublishing = readyForPublishingInstance;
                            }

                            JToken lastModifiedTimeUtcValue = responseDoc["LastModifiedTimeUtc"];
                            if (lastModifiedTimeUtcValue != null && lastModifiedTimeUtcValue.Type != JTokenType.Null)
                            {
                                DateTime lastModifiedTimeUtcInstance = ((DateTime)lastModifiedTimeUtcValue);
                                collectionInstance.LastModifiedTimeUtc = lastModifiedTimeUtcInstance;
                            }

                            JToken modeValue = responseDoc["Mode"];
                            if (modeValue != null && modeValue.Type != JTokenType.Null)
                            {
                                CollectionMode modeInstance = ((CollectionMode)(((int)modeValue)));
                                collectionInstance.Mode = modeInstance;
                            }

                            JToken regionValue = responseDoc["Region"];
                            if (regionValue != null && regionValue.Type != JTokenType.Null)
                            {
                                string regionInstance = ((string)regionValue);
                                collectionInstance.Region = regionInstance;
                            }

                            JToken maxSessionsValue = responseDoc["MaxSessions"];
                            if (maxSessionsValue != null && maxSessionsValue.Type != JTokenType.Null)
                            {
                                int maxSessionsInstance = ((int)maxSessionsValue);
                                collectionInstance.MaxSessions = maxSessionsInstance;
                            }

                            JToken sessionWarningThresholdValue = responseDoc["SessionWarningThreshold"];
                            if (sessionWarningThresholdValue != null && sessionWarningThresholdValue.Type != JTokenType.Null)
                            {
                                int sessionWarningThresholdInstance = ((int)sessionWarningThresholdValue);
                                collectionInstance.SessionWarningThreshold = sessionWarningThresholdInstance;
                            }

                            JToken typeValue = responseDoc["Type"];
                            if (typeValue != null && typeValue.Type != JTokenType.Null)
                            {
                                CollectionType typeInstance = ((CollectionType)(((int)typeValue)));
                                collectionInstance.Type = typeInstance;
                            }

                            JToken officeTypeValue = responseDoc["OfficeType"];
                            if (officeTypeValue != null && officeTypeValue.Type != JTokenType.Null)
                            {
                                OfficeType officeTypeInstance = ((OfficeType)(((int)officeTypeValue)));
                                collectionInstance.OfficeType = officeTypeInstance;
                            }

                            JToken trialOnlyValue = responseDoc["TrialOnly"];
                            if (trialOnlyValue != null && trialOnlyValue.Type != JTokenType.Null)
                            {
                                bool trialOnlyInstance = ((bool)trialOnlyValue);
                                collectionInstance.TrialOnly = trialOnlyInstance;
                            }

                            JToken dnsServersArray = responseDoc["DnsServers"];
                            if (dnsServersArray != null && dnsServersArray.Type != JTokenType.Null)
                            {
                                foreach (JToken dnsServersValue in ((JArray)dnsServersArray))
                                {
                                    collectionInstance.DnsServers.Add(((string)dnsServersValue));
                                }
                            }

                            JToken subnetNameValue = responseDoc["SubnetName"];
                            if (subnetNameValue != null && subnetNameValue.Type != JTokenType.Null)
                            {
                                string subnetNameInstance = ((string)subnetNameValue);
                                collectionInstance.SubnetName = subnetNameInstance;
                            }
                        }

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

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

        /// <summary>
        /// Returns the specified Active directory's configuration.
        /// </summary>
        /// <param name='collectionName'>
        /// Required. Name of the collection
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// Similar in structure to the VNet class but used to return one of
        /// these in GET requests.
        /// </returns>
        public async Task<ActiveDirectoryConfigResult> GetAdAsync(string collectionName, CancellationToken cancellationToken)
        {
            // Validate
            if (collectionName == null)
            {
                throw new ArgumentNullException("collectionName");
            }

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

            // Construct URL
            string url = "";
            url = url + "/";
            if (this.Client.Credentials.SubscriptionId != null)
            {
                url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
            }
            url = url + "/services/";
            if (this.Client.RdfeNamespace != null)
            {
                url = url + Uri.EscapeDataString(this.Client.RdfeNamespace);
            }
            url = url + "/collections/";
            url = url + Uri.EscapeDataString(collectionName);
            url = url + "/ad";
            List<string> queryParameters = new List<string>();
            queryParameters.Add("api-version=2014-09-01");
            if (queryParameters.Count > 0)
            {
                url = url + "?" + string.Join("&", queryParameters);
            }
            string baseUrl = this.Client.BaseUri.AbsoluteUri;
            // Trim '/' character from the end of baseUrl and beginning of url.
            if (baseUrl[baseUrl.Length - 1] == '/')
            {
                baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
            }
            if (url[0] == '/')
            {
                url = url.Substring(1);
            }
            url = baseUrl + "/" + url;
            url = url.Replace(" ", "%20");

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

                // Set Headers
                httpRequest.Headers.Add("Accept", "application/json; charset=utf-8");
                httpRequest.Headers.Add("x-ms-version", "2014-08-01");

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

                // Send Request
                HttpResponseMessage httpResponse = null;
                try
                {
                    if (shouldTrace)
                    {
                        TracingAdapter.SendRequest(invocationId, httpRequest);
                    }
                    cancellationToken.ThrowIfCancellationRequested();
                    httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
                    if (shouldTrace)
                    {
                        TracingAdapter.ReceiveResponse(invocationId, httpResponse);
                    }
                    HttpStatusCode statusCode = httpResponse.StatusCode;
                    if (statusCode != HttpStatusCode.OK)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
                        if (shouldTrace)
                        {
                            TracingAdapter.Error(invocationId, ex);
                        }
                        throw ex;
                    }

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

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

                            JToken domainNameValue = responseDoc["DomainName"];
                            if (domainNameValue != null && domainNameValue.Type != JTokenType.Null)
                            {
                                string domainNameInstance = ((string)domainNameValue);
                                activeDirectoryConfigInstance.DomainName = domainNameInstance;
                            }

                            JToken organizationalUnitValue = responseDoc["OrganizationalUnit"];
                            if (organizationalUnitValue != null && organizationalUnitValue.Type != JTokenType.Null)
                            {
                                string organizationalUnitInstance = ((string)organizationalUnitValue);
                                activeDirectoryConfigInstance.OrganizationalUnit = organizationalUnitInstance;
                            }

                            JToken serviceAccountUserNameValue = responseDoc["ServiceAccountUserName"];
                            if (serviceAccountUserNameValue != null && serviceAccountUserNameValue.Type != JTokenType.Null)
                            {
                                string serviceAccountUserNameInstance = ((string)serviceAccountUserNameValue);
                                activeDirectoryConfigInstance.UserName = serviceAccountUserNameInstance;
                            }

                            JToken serviceAccountPasswordValue = responseDoc["ServiceAccountPassword"];
                            if (serviceAccountPasswordValue != null && serviceAccountPasswordValue.Type != JTokenType.Null)
                            {
                                string serviceAccountPasswordInstance = ((string)serviceAccountPasswordValue);
                                activeDirectoryConfigInstance.Password = serviceAccountPasswordInstance;
                            }
                        }

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

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

        /// <summary>
        /// Gets the summary of collection usage for the requested period.
        /// </summary>
        /// <param name='collectionName'>
        /// Required. The collection name.
        /// </param>
        /// <param name='year'>
        /// Required. The billing year in YYYY format.
        /// </param>
        /// <param name='month'>
        /// Required. The billing month in range of 01 through 12 inclusive.
        /// </param>
        /// <param name='locale'>
        /// Required. The locale value which will be applied to the generated
        /// usage report.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// The collection usage billing details.
        /// </returns>
        public async Task<CollectionUsageDetailsResult> GetUsageDetailsAsync(string collectionName, string year, string month, string locale, CancellationToken cancellationToken)
        {
            // Validate
            if (collectionName == null)
            {
                throw new ArgumentNullException("collectionName");
            }
            if (year == null)
            {
                throw new ArgumentNullException("year");
            }
            if (month == null)
            {
                throw new ArgumentNullException("month");
            }
            if (locale == null)
            {
                throw new ArgumentNullException("locale");
            }

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

            // Construct URL
            string url = "";
            url = url + "/";
            if (this.Client.Credentials.SubscriptionId != null)
            {
                url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
            }
            url = url + "/services/";
            if (this.Client.RdfeNamespace != null)
            {
                url = url + Uri.EscapeDataString(this.Client.RdfeNamespace);
            }
            url = url + "/collections/";
            url = url + Uri.EscapeDataString(collectionName);
            url = url + "/billingusagealldetails/";
            url = url + Uri.EscapeDataString(year);
            url = url + "/";
            url = url + Uri.EscapeDataString(month);
            List<string> queryParameters = new List<string>();
            queryParameters.Add("locale=" + Uri.EscapeDataString(locale));
            queryParameters.Add("api-version=2014-09-01");
            if (queryParameters.Count > 0)
            {
                url = url + "?" + string.Join("&", queryParameters);
            }
            string baseUrl = this.Client.BaseUri.AbsoluteUri;
            // Trim '/' character from the end of baseUrl and beginning of url.
            if (baseUrl[baseUrl.Length - 1] == '/')
            {
                baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
            }
            if (url[0] == '/')
            {
                url = url.Substring(1);
            }
            url = baseUrl + "/" + url;
            url = url.Replace(" ", "%20");

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

                // Set Headers
                httpRequest.Headers.Add("Accept", "application/json; charset=utf-8");
                httpRequest.Headers.Add("x-ms-version", "2014-08-01");

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

                // Send Request
                HttpResponseMessage httpResponse = null;
                try
                {
                    if (shouldTrace)
                    {
                        TracingAdapter.SendRequest(invocationId, httpRequest);
                    }
                    cancellationToken.ThrowIfCancellationRequested();
                    httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
                    if (shouldTrace)
                    {
                        TracingAdapter.ReceiveResponse(invocationId, httpResponse);
                    }
                    HttpStatusCode statusCode = httpResponse.StatusCode;
                    if (statusCode != HttpStatusCode.OK)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
                        if (shouldTrace)
                        {
                            TracingAdapter.Error(invocationId, ex);
                        }
                        throw ex;
                    }

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

                        if (responseDoc != null && responseDoc.Type != JTokenType.Null)
                        {
                            CollectionUsageDetails usageDetailsInstance = new CollectionUsageDetails();
                            result.UsageDetails = usageDetailsInstance;

                            JToken resultIdValue = responseDoc["ResultId"];
                            if (resultIdValue != null && resultIdValue.Type != JTokenType.Null)
                            {
                                string resultIdInstance = ((string)resultIdValue);
                                usageDetailsInstance.OperationTrackingId = resultIdInstance;
                            }

                            JToken extraDataValue = responseDoc["ExtraData"];
                            if (extraDataValue != null && extraDataValue.Type != JTokenType.Null)
                            {
                                string extraDataInstance = ((string)extraDataValue);
                                usageDetailsInstance.SasUri = extraDataInstance;
                            }
                        }

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

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

        /// <summary>
        /// Gets the summary of collection usage for the requested period.
        /// </summary>
        /// <param name='collectionName'>
        /// Required. The collection name.
        /// </param>
        /// <param name='year'>
        /// Required. The billing year in YYYY format.
        /// </param>
        /// <param name='month'>
        /// Required. The billing month in range of 01 through 12 inclusive.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// The collection usage billing summary.
        /// </returns>
        public async Task<CollectionUsageSummaryListResult> GetUsageSummaryAsync(string collectionName, string year, string month, CancellationToken cancellationToken)
        {
            // Validate
            if (collectionName == null)
            {
                throw new ArgumentNullException("collectionName");
            }
            if (year == null)
            {
                throw new ArgumentNullException("year");
            }
            if (month == null)
            {
                throw new ArgumentNullException("month");
            }

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

            // Construct URL
            string url = "";
            url = url + "/";
            if (this.Client.Credentials.SubscriptionId != null)
            {
                url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
            }
            url = url + "/services/";
            if (this.Client.RdfeNamespace != null)
            {
                url = url + Uri.EscapeDataString(this.Client.RdfeNamespace);
            }
            url = url + "/collections/";
            url = url + Uri.EscapeDataString(collectionName);
            url = url + "/billingusagesummaryallusers/";
            url = url + Uri.EscapeDataString(year);
            url = url + "/";
            url = url + Uri.EscapeDataString(month);
            List<string> queryParameters = new List<string>();
            queryParameters.Add("api-version=2014-09-01");
            if (queryParameters.Count > 0)
            {
                url = url + "?" + string.Join("&", queryParameters);
            }
            string baseUrl = this.Client.BaseUri.AbsoluteUri;
            // Trim '/' character from the end of baseUrl and beginning of url.
            if (baseUrl[baseUrl.Length - 1] == '/')
            {
                baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
            }
            if (url[0] == '/')
            {
                url = url.Substring(1);
            }
            url = baseUrl + "/" + url;
            url = url.Replace(" ", "%20");

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

                // Set Headers
                httpRequest.Headers.Add("Accept", "application/json; charset=utf-8");
                httpRequest.Headers.Add("x-ms-version", "2014-08-01");

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

                // Send Request
                HttpResponseMessage httpResponse = null;
                try
                {
                    if (shouldTrace)
                    {
                        TracingAdapter.SendRequest(invocationId, httpRequest);
                    }
                    cancellationToken.ThrowIfCancellationRequested();
                    httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
                    if (shouldTrace)
                    {
                        TracingAdapter.ReceiveResponse(invocationId, httpResponse);
                    }
                    HttpStatusCode statusCode = httpResponse.StatusCode;
                    if (statusCode != HttpStatusCode.OK)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
                        if (shouldTrace)
                        {
                            TracingAdapter.Error(invocationId, ex);
                        }
                        throw ex;
                    }

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

                        if (responseDoc != null && responseDoc.Type != JTokenType.Null)
                        {
                            JToken usageSummaryListArray = responseDoc;
                            if (usageSummaryListArray != null && usageSummaryListArray.Type != JTokenType.Null)
                            {
                                foreach (JToken usageSummaryListValue in ((JArray)usageSummaryListArray))
                                {
                                    BillingUsageSummary billingUsageSummaryInstance = new BillingUsageSummary();
                                    result.UsageSummaryList.Add(billingUsageSummaryInstance);

                                    JToken userNameValue = usageSummaryListValue["UserName"];
                                    if (userNameValue != null && userNameValue.Type != JTokenType.Null)
                                    {
                                        string userNameInstance = ((string)userNameValue);
                                        billingUsageSummaryInstance.UserName = userNameInstance;
                                    }

                                    JToken includedUsageValue = usageSummaryListValue["IncludedUsage"];
                                    if (includedUsageValue != null && includedUsageValue.Type != JTokenType.Null)
                                    {
                                        double includedUsageInstance = ((double)includedUsageValue);
                                        billingUsageSummaryInstance.IncludedUsage = includedUsageInstance;
                                    }

                                    JToken overageUsageValue = usageSummaryListValue["OverageUsage"];
                                    if (overageUsageValue != null && overageUsageValue.Type != JTokenType.Null)
                                    {
                                        double overageUsageInstance = ((double)overageUsageValue);
                                        billingUsageSummaryInstance.OverageUsage = overageUsageInstance;
                                    }

                                    JToken waivedUsageValue = usageSummaryListValue["WaivedUsage"];
                                    if (waivedUsageValue != null && waivedUsageValue.Type != JTokenType.Null)
                                    {
                                        double waivedUsageInstance = ((double)waivedUsageValue);
                                        billingUsageSummaryInstance.WaivedUsage = waivedUsageInstance;
                                    }

                                    JToken totalUsageValue = usageSummaryListValue["TotalUsage"];
                                    if (totalUsageValue != null && totalUsageValue.Type != JTokenType.Null)
                                    {
                                        double totalUsageInstance = ((double)totalUsageValue);
                                        billingUsageSummaryInstance.TotalUsage = totalUsageInstance;
                                    }
                                }
                            }
                        }

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

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

        /// <summary>
        /// Returns the list of all collection currently available for the
        /// subscription Id
        /// </summary>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// The response for the get collections list operation.
        /// </returns>
        public async Task<CollectionListResult> ListAsync(CancellationToken cancellationToken)
        {
            // Validate

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

            // Construct URL
            string url = "";
            url = url + "/";
            if (this.Client.Credentials.SubscriptionId != null)
            {
                url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
            }
            url = url + "/services/";
            if (this.Client.RdfeNamespace != null)
            {
                url = url + Uri.EscapeDataString(this.Client.RdfeNamespace);
            }
            url = url + "/collections";
            List<string> queryParameters = new List<string>();
            queryParameters.Add("api-version=2014-09-01");
            if (queryParameters.Count > 0)
            {
                url = url + "?" + string.Join("&", queryParameters);
            }
            string baseUrl = this.Client.BaseUri.AbsoluteUri;
            // Trim '/' character from the end of baseUrl and beginning of url.
            if (baseUrl[baseUrl.Length - 1] == '/')
            {
                baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
            }
            if (url[0] == '/')
            {
                url = url.Substring(1);
            }
            url = baseUrl + "/" + url;
            url = url.Replace(" ", "%20");

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

                // Set Headers
                httpRequest.Headers.Add("Accept", "application/json; charset=utf-8");
                httpRequest.Headers.Add("x-ms-version", "2014-08-01");

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

                // Send Request
                HttpResponseMessage httpResponse = null;
                try
                {
                    if (shouldTrace)
                    {
                        TracingAdapter.SendRequest(invocationId, httpRequest);
                    }
                    cancellationToken.ThrowIfCancellationRequested();
                    httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
                    if (shouldTrace)
                    {
                        TracingAdapter.ReceiveResponse(invocationId, httpResponse);
                    }
                    HttpStatusCode statusCode = httpResponse.StatusCode;
                    if (statusCode != HttpStatusCode.OK)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
                        if (shouldTrace)
                        {
                            TracingAdapter.Error(invocationId, ex);
                        }
                        throw ex;
                    }

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

                        if (responseDoc != null && responseDoc.Type != JTokenType.Null)
                        {
                            JToken collectionsArray = responseDoc;
                            if (collectionsArray != null && collectionsArray.Type != JTokenType.Null)
                            {
                                foreach (JToken collectionsValue in ((JArray)collectionsArray))
                                {
                                    Collection collectionInstance = new Collection();
                                    result.Collections.Add(collectionInstance);

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

                                    JToken descriptionValue = collectionsValue["Description"];
                                    if (descriptionValue != null && descriptionValue.Type != JTokenType.Null)
                                    {
                                        string descriptionInstance = ((string)descriptionValue);
                                        collectionInstance.Description = descriptionInstance;
                                    }

                                    JToken templateImageNameValue = collectionsValue["TemplateImageName"];
                                    if (templateImageNameValue != null && templateImageNameValue.Type != JTokenType.Null)
                                    {
                                        string templateImageNameInstance = ((string)templateImageNameValue);
                                        collectionInstance.TemplateImageName = templateImageNameInstance;
                                    }

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

                                    JToken lastErrorCodeValue = collectionsValue["LastErrorCode"];
                                    if (lastErrorCodeValue != null && lastErrorCodeValue.Type != JTokenType.Null)
                                    {
                                        string lastErrorCodeInstance = ((string)lastErrorCodeValue);
                                        collectionInstance.LastErrorCode = lastErrorCodeInstance;
                                    }

                                    JToken vnetNameValue = collectionsValue["VnetName"];
                                    if (vnetNameValue != null && vnetNameValue.Type != JTokenType.Null)
                                    {
                                        string vnetNameInstance = ((string)vnetNameValue);
                                        collectionInstance.VNetName = vnetNameInstance;
                                    }

                                    JToken adInfoValue = collectionsValue["AdInfo"];
                                    if (adInfoValue != null && adInfoValue.Type != JTokenType.Null)
                                    {
                                        ActiveDirectoryConfig adInfoInstance = new ActiveDirectoryConfig();
                                        collectionInstance.AdInfo = adInfoInstance;

                                        JToken domainNameValue = adInfoValue["DomainName"];
                                        if (domainNameValue != null && domainNameValue.Type != JTokenType.Null)
                                        {
                                            string domainNameInstance = ((string)domainNameValue);
                                            adInfoInstance.DomainName = domainNameInstance;
                                        }

                                        JToken organizationalUnitValue = adInfoValue["OrganizationalUnit"];
                                        if (organizationalUnitValue != null && organizationalUnitValue.Type != JTokenType.Null)
                                        {
                                            string organizationalUnitInstance = ((string)organizationalUnitValue);
                                            adInfoInstance.OrganizationalUnit = organizationalUnitInstance;
                                        }

                                        JToken serviceAccountUserNameValue = adInfoValue["ServiceAccountUserName"];
                                        if (serviceAccountUserNameValue != null && serviceAccountUserNameValue.Type != JTokenType.Null)
                                        {
                                            string serviceAccountUserNameInstance = ((string)serviceAccountUserNameValue);
                                            adInfoInstance.UserName = serviceAccountUserNameInstance;
                                        }

                                        JToken serviceAccountPasswordValue = adInfoValue["ServiceAccountPassword"];
                                        if (serviceAccountPasswordValue != null && serviceAccountPasswordValue.Type != JTokenType.Null)
                                        {
                                            string serviceAccountPasswordInstance = ((string)serviceAccountPasswordValue);
                                            adInfoInstance.Password = serviceAccountPasswordInstance;
                                        }
                                    }

                                    JToken billingPlanNameValue = collectionsValue["BillingPlanName"];
                                    if (billingPlanNameValue != null && billingPlanNameValue.Type != JTokenType.Null)
                                    {
                                        string billingPlanNameInstance = ((string)billingPlanNameValue);
                                        collectionInstance.PlanName = billingPlanNameInstance;
                                    }

                                    JToken customRdpPropertyValue = collectionsValue["CustomRdpProperty"];
                                    if (customRdpPropertyValue != null && customRdpPropertyValue.Type != JTokenType.Null)
                                    {
                                        string customRdpPropertyInstance = ((string)customRdpPropertyValue);
                                        collectionInstance.CustomRdpProperty = customRdpPropertyInstance;
                                    }

                                    JToken readyForPublishingValue = collectionsValue["ReadyForPublishing"];
                                    if (readyForPublishingValue != null && readyForPublishingValue.Type != JTokenType.Null)
                                    {
                                        bool readyForPublishingInstance = ((bool)readyForPublishingValue);
                                        collectionInstance.ReadyForPublishing = readyForPublishingInstance;
                                    }

                                    JToken lastModifiedTimeUtcValue = collectionsValue["LastModifiedTimeUtc"];
                                    if (lastModifiedTimeUtcValue != null && lastModifiedTimeUtcValue.Type != JTokenType.Null)
                                    {
                                        DateTime lastModifiedTimeUtcInstance = ((DateTime)lastModifiedTimeUtcValue);
                                        collectionInstance.LastModifiedTimeUtc = lastModifiedTimeUtcInstance;
                                    }

                                    JToken modeValue = collectionsValue["Mode"];
                                    if (modeValue != null && modeValue.Type != JTokenType.Null)
                                    {
                                        CollectionMode modeInstance = ((CollectionMode)(((int)modeValue)));
                                        collectionInstance.Mode = modeInstance;
                                    }

                                    JToken regionValue = collectionsValue["Region"];
                                    if (regionValue != null && regionValue.Type != JTokenType.Null)
                                    {
                                        string regionInstance = ((string)regionValue);
                                        collectionInstance.Region = regionInstance;
                                    }

                                    JToken maxSessionsValue = collectionsValue["MaxSessions"];
                                    if (maxSessionsValue != null && maxSessionsValue.Type != JTokenType.Null)
                                    {
                                        int maxSessionsInstance = ((int)maxSessionsValue);
                                        collectionInstance.MaxSessions = maxSessionsInstance;
                                    }

                                    JToken sessionWarningThresholdValue = collectionsValue["SessionWarningThreshold"];
                                    if (sessionWarningThresholdValue != null && sessionWarningThresholdValue.Type != JTokenType.Null)
                                    {
                                        int sessionWarningThresholdInstance = ((int)sessionWarningThresholdValue);
                                        collectionInstance.SessionWarningThreshold = sessionWarningThresholdInstance;
                                    }

                                    JToken typeValue = collectionsValue["Type"];
                                    if (typeValue != null && typeValue.Type != JTokenType.Null)
                                    {
                                        CollectionType typeInstance = ((CollectionType)(((int)typeValue)));
                                        collectionInstance.Type = typeInstance;
                                    }

                                    JToken officeTypeValue = collectionsValue["OfficeType"];
                                    if (officeTypeValue != null && officeTypeValue.Type != JTokenType.Null)
                                    {
                                        OfficeType officeTypeInstance = ((OfficeType)(((int)officeTypeValue)));
                                        collectionInstance.OfficeType = officeTypeInstance;
                                    }

                                    JToken trialOnlyValue = collectionsValue["TrialOnly"];
                                    if (trialOnlyValue != null && trialOnlyValue.Type != JTokenType.Null)
                                    {
                                        bool trialOnlyInstance = ((bool)trialOnlyValue);
                                        collectionInstance.TrialOnly = trialOnlyInstance;
                                    }

                                    JToken dnsServersArray = collectionsValue["DnsServers"];
                                    if (dnsServersArray != null && dnsServersArray.Type != JTokenType.Null)
                                    {
                                        foreach (JToken dnsServersValue in ((JArray)dnsServersArray))
                                        {
                                            collectionInstance.DnsServers.Add(((string)dnsServersValue));
                                        }
                                    }

                                    JToken subnetNameValue = collectionsValue["SubnetName"];
                                    if (subnetNameValue != null && subnetNameValue.Type != JTokenType.Null)
                                    {
                                        string subnetNameInstance = ((string)subnetNameValue);
                                        collectionInstance.SubnetName = subnetNameInstance;
                                    }
                                }
                            }
                        }

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

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

        /// <summary>
        /// Gets the list of all sessions in the collection.
        /// </summary>
        /// <param name='collectionName'>
        /// Required. The RemoteApp collection name where the sessions exists.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// List of user sessions in a given collection.
        /// </returns>
        public async Task<CollectionSessionListResult> ListSessionsAsync(string collectionName, CancellationToken cancellationToken)
        {
            // Validate
            if (collectionName == null)
            {
                throw new ArgumentNullException("collectionName");
            }

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

            // Construct URL
            string url = "";
            url = url + "/";
            if (this.Client.Credentials.SubscriptionId != null)
            {
                url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
            }
            url = url + "/services/";
            if (this.Client.RdfeNamespace != null)
            {
                url = url + Uri.EscapeDataString(this.Client.RdfeNamespace);
            }
            url = url + "/collections/";
            url = url + Uri.EscapeDataString(collectionName);
            url = url + "/sessions";
            List<string> queryParameters = new List<string>();
            queryParameters.Add("api-version=2014-09-01");
            if (queryParameters.Count > 0)
            {
                url = url + "?" + string.Join("&", queryParameters);
            }
            string baseUrl = this.Client.BaseUri.AbsoluteUri;
            // Trim '/' character from the end of baseUrl and beginning of url.
            if (baseUrl[baseUrl.Length - 1] == '/')
            {
                baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
            }
            if (url[0] == '/')
            {
                url = url.Substring(1);
            }
            url = baseUrl + "/" + url;
            url = url.Replace(" ", "%20");

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

                // Set Headers
                httpRequest.Headers.Add("Accept", "application/json; charset=utf-8");
                httpRequest.Headers.Add("x-ms-version", "2014-08-01");

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

                // Send Request
                HttpResponseMessage httpResponse = null;
                try
                {
                    if (shouldTrace)
                    {
                        TracingAdapter.SendRequest(invocationId, httpRequest);
                    }
                    cancellationToken.ThrowIfCancellationRequested();
                    httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
                    if (shouldTrace)
                    {
                        TracingAdapter.ReceiveResponse(invocationId, httpResponse);
                    }
                    HttpStatusCode statusCode = httpResponse.StatusCode;
                    if (statusCode != HttpStatusCode.OK)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
                        if (shouldTrace)
                        {
                            TracingAdapter.Error(invocationId, ex);
                        }
                        throw ex;
                    }

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

                        if (responseDoc != null && responseDoc.Type != JTokenType.Null)
                        {
                            JToken sessionsArray = responseDoc;
                            if (sessionsArray != null && sessionsArray.Type != JTokenType.Null)
                            {
                                foreach (JToken sessionsValue in ((JArray)sessionsArray))
                                {
                                    RemoteAppSession remoteAppSessionInstance = new RemoteAppSession();
                                    result.Sessions.Add(remoteAppSessionInstance);

                                    JToken logonTimeUtcValue = sessionsValue["LogonTimeUtc"];
                                    if (logonTimeUtcValue != null && logonTimeUtcValue.Type != JTokenType.Null)
                                    {
                                        DateTime logonTimeUtcInstance = ((DateTime)logonTimeUtcValue);
                                        remoteAppSessionInstance.LogonTimeUtc = logonTimeUtcInstance;
                                    }

                                    JToken userUpnValue = sessionsValue["UserUpn"];
                                    if (userUpnValue != null && userUpnValue.Type != JTokenType.Null)
                                    {
                                        string userUpnInstance = ((string)userUpnValue);
                                        remoteAppSessionInstance.UserUpn = userUpnInstance;
                                    }

                                    JToken stateValue = sessionsValue["State"];
                                    if (stateValue != null && stateValue.Type != JTokenType.Null)
                                    {
                                        SessionState stateInstance = ((SessionState)Enum.Parse(typeof(SessionState), ((string)stateValue), true));
                                        remoteAppSessionInstance.State = stateInstance;
                                    }
                                }
                            }
                        }

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

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

        /// <summary>
        /// Gets the list of all virtual machines in the collection.
        /// </summary>
        /// <param name='collectionName'>
        /// Required. The RemoteApp collection name where vms exist.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// List of virtual machines in a given collection.
        /// </returns>
        public async Task<CollectionVmsListResult> ListVmsAsync(string collectionName, CancellationToken cancellationToken)
        {
            // Validate
            if (collectionName == null)
            {
                throw new ArgumentNullException("collectionName");
            }

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

            // Construct URL
            string url = "";
            url = url + "/";
            if (this.Client.Credentials.SubscriptionId != null)
            {
                url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
            }
            url = url + "/services/";
            if (this.Client.RdfeNamespace != null)
            {
                url = url + Uri.EscapeDataString(this.Client.RdfeNamespace);
            }
            url = url + "/collections/";
            url = url + Uri.EscapeDataString(collectionName);
            url = url + "/vms";
            List<string> queryParameters = new List<string>();
            queryParameters.Add("api-version=2014-09-01");
            if (queryParameters.Count > 0)
            {
                url = url + "?" + string.Join("&", queryParameters);
            }
            string baseUrl = this.Client.BaseUri.AbsoluteUri;
            // Trim '/' character from the end of baseUrl and beginning of url.
            if (baseUrl[baseUrl.Length - 1] == '/')
            {
                baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
            }
            if (url[0] == '/')
            {
                url = url.Substring(1);
            }
            url = baseUrl + "/" + url;
            url = url.Replace(" ", "%20");

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

                // Set Headers
                httpRequest.Headers.Add("Accept", "application/json; charset=utf-8");
                httpRequest.Headers.Add("x-ms-version", "2014-08-01");

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

                // Send Request
                HttpResponseMessage httpResponse = null;
                try
                {
                    if (shouldTrace)
                    {
                        TracingAdapter.SendRequest(invocationId, httpRequest);
                    }
                    cancellationToken.ThrowIfCancellationRequested();
                    httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
                    if (shouldTrace)
                    {
                        TracingAdapter.ReceiveResponse(invocationId, httpResponse);
                    }
                    HttpStatusCode statusCode = httpResponse.StatusCode;
                    if (statusCode != HttpStatusCode.OK)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
                        if (shouldTrace)
                        {
                            TracingAdapter.Error(invocationId, ex);
                        }
                        throw ex;
                    }

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

                        if (responseDoc != null && responseDoc.Type != JTokenType.Null)
                        {
                            JToken vmsArray = responseDoc;
                            if (vmsArray != null && vmsArray.Type != JTokenType.Null)
                            {
                                foreach (JToken vmsValue in ((JArray)vmsArray))
                                {
                                    RemoteAppVm remoteAppVmInstance = new RemoteAppVm();
                                    result.Vms.Add(remoteAppVmInstance);

                                    JToken virtualMachineNameValue = vmsValue["VirtualMachineName"];
                                    if (virtualMachineNameValue != null && virtualMachineNameValue.Type != JTokenType.Null)
                                    {
                                        string virtualMachineNameInstance = ((string)virtualMachineNameValue);
                                        remoteAppVmInstance.VirtualMachineName = virtualMachineNameInstance;
                                    }

                                    JToken loggedOnUserUpnArray = vmsValue["LoggedOnUserUpn"];
                                    if (loggedOnUserUpnArray != null && loggedOnUserUpnArray.Type != JTokenType.Null)
                                    {
                                        foreach (JToken loggedOnUserUpnValue in ((JArray)loggedOnUserUpnArray))
                                        {
                                            remoteAppVmInstance.LoggedOnUserUpns.Add(((string)loggedOnUserUpnValue));
                                        }
                                    }
                                }
                            }
                        }

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

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

        /// <summary>
        /// Logs off the session associated with the user UPN
        /// </summary>
        /// <param name='collectionName'>
        /// Required. The RemoteApp collection name where the session exists.
        /// </param>
        /// <param name='sessionParameter'>
        /// Required. The session command parameter to logoff a session.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// The response containing the operation tracking id.
        /// </returns>
        public async Task<OperationResultWithTrackingId> LogoffSessionAsync(string collectionName, SessionCommandParameter sessionParameter, CancellationToken cancellationToken)
        {
            // Validate
            if (collectionName == null)
            {
                throw new ArgumentNullException("collectionName");
            }
            if (sessionParameter == null)
            {
                throw new ArgumentNullException("sessionParameter");
            }
            if (sessionParameter.UserUpn == null)
            {
                throw new ArgumentNullException("sessionParameter.UserUpn");
            }

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

            // Construct URL
            string url = "";
            url = url + "/";
            if (this.Client.Credentials.SubscriptionId != null)
            {
                url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
            }
            url = url + "/services/";
            if (this.Client.RdfeNamespace != null)
            {
                url = url + Uri.EscapeDataString(this.Client.RdfeNamespace);
            }
            url = url + "/collections/";
            url = url + Uri.EscapeDataString(collectionName);
            url = url + "/sessions/logoff";
            List<string> queryParameters = new List<string>();
            queryParameters.Add("api-version=2014-09-01");
            if (queryParameters.Count > 0)
            {
                url = url + "?" + string.Join("&", queryParameters);
            }
            string baseUrl = this.Client.BaseUri.AbsoluteUri;
            // Trim '/' character from the end of baseUrl and beginning of url.
            if (baseUrl[baseUrl.Length - 1] == '/')
            {
                baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
            }
            if (url[0] == '/')
            {
                url = url.Substring(1);
            }
            url = baseUrl + "/" + url;
            url = url.Replace(" ", "%20");

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

                // Set Headers
                httpRequest.Headers.Add("Accept", "application/json; charset=utf-8");
                httpRequest.Headers.Add("x-ms-version", "2014-08-01");

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

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

                JObject sessionCommandParameterValue = new JObject();
                requestDoc = sessionCommandParameterValue;

                sessionCommandParameterValue["UserUpn"] = sessionParameter.UserUpn;

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

                // Send Request
                HttpResponseMessage httpResponse = null;
                try
                {
                    if (shouldTrace)
                    {
                        TracingAdapter.SendRequest(invocationId, httpRequest);
                    }
                    cancellationToken.ThrowIfCancellationRequested();
                    httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
                    if (shouldTrace)
                    {
                        TracingAdapter.ReceiveResponse(invocationId, httpResponse);
                    }
                    HttpStatusCode statusCode = httpResponse.StatusCode;
                    if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Accepted)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
                        if (shouldTrace)
                        {
                            TracingAdapter.Error(invocationId, ex);
                        }
                        throw ex;
                    }

                    // Create Result
                    OperationResultWithTrackingId result = null;
                    // Deserialize Response
                    result = new OperationResultWithTrackingId();
                    result.StatusCode = statusCode;
                    if (httpResponse.Headers.Contains("x-ms-request-id"))
                    {
                        result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
                    }
                    if (httpResponse.Headers.Contains("x-remoteapp-operation-tracking-id"))
                    {
                        result.TrackingId = httpResponse.Headers.GetValues("x-remoteapp-operation-tracking-id").FirstOrDefault();
                    }

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

        /// <summary>
        /// Gets a list of all regions where collection can be created for the
        /// subscription.
        /// </summary>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// The list of locations.
        /// </returns>
        public async Task<RegionListResult> RegionListAsync(CancellationToken cancellationToken)
        {
            // Validate

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

            // Construct URL
            string url = "";
            url = url + "/";
            if (this.Client.Credentials.SubscriptionId != null)
            {
                url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
            }
            url = url + "/services/";
            if (this.Client.RdfeNamespace != null)
            {
                url = url + Uri.EscapeDataString(this.Client.RdfeNamespace);
            }
            url = url + "/collections/locations";
            List<string> queryParameters = new List<string>();
            queryParameters.Add("api-version=2014-09-01");
            if (queryParameters.Count > 0)
            {
                url = url + "?" + string.Join("&", queryParameters);
            }
            string baseUrl = this.Client.BaseUri.AbsoluteUri;
            // Trim '/' character from the end of baseUrl and beginning of url.
            if (baseUrl[baseUrl.Length - 1] == '/')
            {
                baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
            }
            if (url[0] == '/')
            {
                url = url.Substring(1);
            }
            url = baseUrl + "/" + url;
            url = url.Replace(" ", "%20");

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

                // Set Headers
                httpRequest.Headers.Add("Accept", "application/json; charset=utf-8");
                httpRequest.Headers.Add("x-ms-version", "2014-08-01");

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

                // Send Request
                HttpResponseMessage httpResponse = null;
                try
                {
                    if (shouldTrace)
                    {
                        TracingAdapter.SendRequest(invocationId, httpRequest);
                    }
                    cancellationToken.ThrowIfCancellationRequested();
                    httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
                    if (shouldTrace)
                    {
                        TracingAdapter.ReceiveResponse(invocationId, httpResponse);
                    }
                    HttpStatusCode statusCode = httpResponse.StatusCode;
                    if (statusCode != HttpStatusCode.OK)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
                        if (shouldTrace)
                        {
                            TracingAdapter.Error(invocationId, ex);
                        }
                        throw ex;
                    }

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

                        if (responseDoc != null && responseDoc.Type != JTokenType.Null)
                        {
                            JToken regionsArray = responseDoc;
                            if (regionsArray != null && regionsArray.Type != JTokenType.Null)
                            {
                                foreach (JToken regionsValue in ((JArray)regionsArray))
                                {
                                    Region regionInstance = new Region();
                                    result.Regions.Add(regionInstance);

                                    JToken displayNameValue = regionsValue["DisplayName"];
                                    if (displayNameValue != null && displayNameValue.Type != JTokenType.Null)
                                    {
                                        string displayNameInstance = ((string)displayNameValue);
                                        regionInstance.DisplayName = displayNameInstance;
                                    }

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

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

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

        /// <summary>
        /// Restarts VM associated with a collection.
        /// </summary>
        /// <param name='collectionName'>
        /// Required. The RemoteApp collection name containing the VM to be
        /// restarted.
        /// </param>
        /// <param name='details'>
        /// Required. The details of VM to be restarted.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// The response containing the operation tracking id.
        /// </returns>
        public async Task<OperationResultWithTrackingId> RestartVmAsync(string collectionName, RestartVmCommandParameter details, CancellationToken cancellationToken)
        {
            // Validate
            if (collectionName == null)
            {
                throw new ArgumentNullException("collectionName");
            }
            if (details == null)
            {
                throw new ArgumentNullException("details");
            }
            if (details.VirtualMachineName == null)
            {
                throw new ArgumentNullException("details.VirtualMachineName");
            }

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

            // Construct URL
            string url = "";
            url = url + "/";
            if (this.Client.Credentials.SubscriptionId != null)
            {
                url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
            }
            url = url + "/services/";
            if (this.Client.RdfeNamespace != null)
            {
                url = url + Uri.EscapeDataString(this.Client.RdfeNamespace);
            }
            url = url + "/collections/";
            url = url + Uri.EscapeDataString(collectionName);
            url = url + "/vms/restart";
            List<string> queryParameters = new List<string>();
            queryParameters.Add("api-version=2014-09-01");
            if (queryParameters.Count > 0)
            {
                url = url + "?" + string.Join("&", queryParameters);
            }
            string baseUrl = this.Client.BaseUri.AbsoluteUri;
            // Trim '/' character from the end of baseUrl and beginning of url.
            if (baseUrl[baseUrl.Length - 1] == '/')
            {
                baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
            }
            if (url[0] == '/')
            {
                url = url.Substring(1);
            }
            url = baseUrl + "/" + url;
            url = url.Replace(" ", "%20");

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

                // Set Headers
                httpRequest.Headers.Add("Accept", "application/json; charset=utf-8");
                httpRequest.Headers.Add("x-ms-version", "2014-08-01");

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

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

                JObject restartVmCommandParameterValue = new JObject();
                requestDoc = restartVmCommandParameterValue;

                restartVmCommandParameterValue["VirtualMachineName"] = details.VirtualMachineName;

                if (details.LogoffMessage != null)
                {
                    restartVmCommandParameterValue["LogoffMessage"] = details.LogoffMessage;
                }

                restartVmCommandParameterValue["LogoffWaitTimeInSeconds"] = details.LogoffWaitTimeInSeconds;

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

                // Send Request
                HttpResponseMessage httpResponse = null;
                try
                {
                    if (shouldTrace)
                    {
                        TracingAdapter.SendRequest(invocationId, httpRequest);
                    }
                    cancellationToken.ThrowIfCancellationRequested();
                    httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
                    if (shouldTrace)
                    {
                        TracingAdapter.ReceiveResponse(invocationId, httpResponse);
                    }
                    HttpStatusCode statusCode = httpResponse.StatusCode;
                    if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Accepted)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
                        if (shouldTrace)
                        {
                            TracingAdapter.Error(invocationId, ex);
                        }
                        throw ex;
                    }

                    // Create Result
                    OperationResultWithTrackingId result = null;
                    // Deserialize Response
                    result = new OperationResultWithTrackingId();
                    result.StatusCode = statusCode;
                    if (httpResponse.Headers.Contains("x-ms-request-id"))
                    {
                        result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
                    }
                    if (httpResponse.Headers.Contains("x-remoteapp-operation-tracking-id"))
                    {
                        result.TrackingId = httpResponse.Headers.GetValues("x-remoteapp-operation-tracking-id").FirstOrDefault();
                    }

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

        /// <summary>
        /// Sends message to the session associated with the user UPN
        /// </summary>
        /// <param name='collectionName'>
        /// Required. The RemoteApp collection name where the session exists.
        /// </param>
        /// <param name='sessionMessageParameter'>
        /// Required. The session command parameter to send message to a
        /// session.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// The response containing the operation tracking id.
        /// </returns>
        public async Task<OperationResultWithTrackingId> SendMessageToSessionAsync(string collectionName, SessionSendMessageCommandParameter sessionMessageParameter, CancellationToken cancellationToken)
        {
            // Validate
            if (collectionName == null)
            {
                throw new ArgumentNullException("collectionName");
            }
            if (sessionMessageParameter == null)
            {
                throw new ArgumentNullException("sessionMessageParameter");
            }
            if (sessionMessageParameter.Message == null)
            {
                throw new ArgumentNullException("sessionMessageParameter.Message");
            }
            if (sessionMessageParameter.UserUpn == null)
            {
                throw new ArgumentNullException("sessionMessageParameter.UserUpn");
            }

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

            // Construct URL
            string url = "";
            url = url + "/";
            if (this.Client.Credentials.SubscriptionId != null)
            {
                url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
            }
            url = url + "/services/";
            if (this.Client.RdfeNamespace != null)
            {
                url = url + Uri.EscapeDataString(this.Client.RdfeNamespace);
            }
            url = url + "/collections/";
            url = url + Uri.EscapeDataString(collectionName);
            url = url + "/sessions/sendMessage";
            List<string> queryParameters = new List<string>();
            queryParameters.Add("api-version=2014-09-01");
            if (queryParameters.Count > 0)
            {
                url = url + "?" + string.Join("&", queryParameters);
            }
            string baseUrl = this.Client.BaseUri.AbsoluteUri;
            // Trim '/' character from the end of baseUrl and beginning of url.
            if (baseUrl[baseUrl.Length - 1] == '/')
            {
                baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
            }
            if (url[0] == '/')
            {
                url = url.Substring(1);
            }
            url = baseUrl + "/" + url;
            url = url.Replace(" ", "%20");

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

                // Set Headers
                httpRequest.Headers.Add("Accept", "application/json; charset=utf-8");
                httpRequest.Headers.Add("x-ms-version", "2014-08-01");

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

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

                JObject sessionSendMessageCommandParameterValue = new JObject();
                requestDoc = sessionSendMessageCommandParameterValue;

                sessionSendMessageCommandParameterValue["UserUpn"] = sessionMessageParameter.UserUpn;

                sessionSendMessageCommandParameterValue["Message"] = sessionMessageParameter.Message;

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

                // Send Request
                HttpResponseMessage httpResponse = null;
                try
                {
                    if (shouldTrace)
                    {
                        TracingAdapter.SendRequest(invocationId, httpRequest);
                    }
                    cancellationToken.ThrowIfCancellationRequested();
                    httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
                    if (shouldTrace)
                    {
                        TracingAdapter.ReceiveResponse(invocationId, httpResponse);
                    }
                    HttpStatusCode statusCode = httpResponse.StatusCode;
                    if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Accepted)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
                        if (shouldTrace)
                        {
                            TracingAdapter.Error(invocationId, ex);
                        }
                        throw ex;
                    }

                    // Create Result
                    OperationResultWithTrackingId result = null;
                    // Deserialize Response
                    result = new OperationResultWithTrackingId();
                    result.StatusCode = statusCode;
                    if (httpResponse.Headers.Contains("x-ms-request-id"))
                    {
                        result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
                    }
                    if (httpResponse.Headers.Contains("x-remoteapp-operation-tracking-id"))
                    {
                        result.TrackingId = httpResponse.Headers.GetValues("x-remoteapp-operation-tracking-id").FirstOrDefault();
                    }

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

        /// <summary>
        /// Sets a new information to the collection with given id.
        /// </summary>
        /// <param name='collectionName'>
        /// Required. The name of the collection.
        /// </param>
        /// <param name='forceRedeploy'>
        /// Required. A flag denoting if the request is to re-deploy the
        /// collection after it is updated.
        /// </param>
        /// <param name='populateOnly'>
        /// Required. A flag denoting if the request is to populate the
        /// collection details(true for populate only).
        /// </param>
        /// <param name='collectionDetails'>
        /// Required. Details for the collection to be updated.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// The response containing the operation tracking id.
        /// </returns>
        public async Task<OperationResultWithTrackingId> SetAsync(string collectionName, bool forceRedeploy, bool populateOnly, CollectionUpdateDetails collectionDetails, CancellationToken cancellationToken)
        {
            // Validate
            if (collectionName == null)
            {
                throw new ArgumentNullException("collectionName");
            }
            if (collectionDetails == null)
            {
                throw new ArgumentNullException("collectionDetails");
            }
            if (collectionDetails.AdInfo != null)
            {
                if (collectionDetails.AdInfo.DomainName == null)
                {
                    throw new ArgumentNullException("collectionDetails.AdInfo.DomainName");
                }
                if (collectionDetails.AdInfo.Password == null)
                {
                    throw new ArgumentNullException("collectionDetails.AdInfo.Password");
                }
                if (collectionDetails.AdInfo.UserName == null)
                {
                    throw new ArgumentNullException("collectionDetails.AdInfo.UserName");
                }
            }

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

            // Construct URL
            string url = "";
            url = url + "/";
            if (this.Client.Credentials.SubscriptionId != null)
            {
                url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
            }
            url = url + "/services/";
            if (this.Client.RdfeNamespace != null)
            {
                url = url + Uri.EscapeDataString(this.Client.RdfeNamespace);
            }
            url = url + "/collections/";
            url = url + Uri.EscapeDataString(collectionName);
            List<string> queryParameters = new List<string>();
            queryParameters.Add("ForceRedeploy=" + Uri.EscapeDataString(forceRedeploy.ToString().ToLower()));
            queryParameters.Add("PopulateOnly=" + Uri.EscapeDataString(populateOnly.ToString().ToLower()));
            queryParameters.Add("api-version=2014-09-01");
            if (queryParameters.Count > 0)
            {
                url = url + "?" + string.Join("&", queryParameters);
            }
            string baseUrl = this.Client.BaseUri.AbsoluteUri;
            // Trim '/' character from the end of baseUrl and beginning of url.
            if (baseUrl[baseUrl.Length - 1] == '/')
            {
                baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
            }
            if (url[0] == '/')
            {
                url = url.Substring(1);
            }
            url = baseUrl + "/" + url;
            url = url.Replace(" ", "%20");

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

                // Set Headers
                httpRequest.Headers.Add("x-ms-version", "2014-08-01");

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

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

                JObject collectionUpdateDetailsValue = new JObject();
                requestDoc = collectionUpdateDetailsValue;

                if (collectionDetails.Description != null)
                {
                    collectionUpdateDetailsValue["Description"] = collectionDetails.Description;
                }

                if (collectionDetails.TemplateImageName != null)
                {
                    collectionUpdateDetailsValue["TemplateImageName"] = collectionDetails.TemplateImageName;
                }

                if (collectionDetails.AdInfo != null)
                {
                    JObject adInfoValue = new JObject();
                    collectionUpdateDetailsValue["AdInfo"] = adInfoValue;

                    adInfoValue["DomainName"] = collectionDetails.AdInfo.DomainName;

                    if (collectionDetails.AdInfo.OrganizationalUnit != null)
                    {
                        adInfoValue["OrganizationalUnit"] = collectionDetails.AdInfo.OrganizationalUnit;
                    }

                    adInfoValue["ServiceAccountUserName"] = collectionDetails.AdInfo.UserName;

                    adInfoValue["ServiceAccountPassword"] = collectionDetails.AdInfo.Password;
                }

                if (collectionDetails.PlanName != null)
                {
                    collectionUpdateDetailsValue["BillingPlanName"] = collectionDetails.PlanName;
                }

                if (collectionDetails.CustomRdpProperty != null)
                {
                    collectionUpdateDetailsValue["CustomRdpProperty"] = collectionDetails.CustomRdpProperty;
                }

                collectionUpdateDetailsValue["WaitBeforeShutdownInMinutes"] = collectionDetails.WaitBeforeShutdownInMinutes;

                if (collectionDetails.SubnetName != null)
                {
                    collectionUpdateDetailsValue["SubnetName"] = collectionDetails.SubnetName;
                }

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

                // Send Request
                HttpResponseMessage httpResponse = null;
                try
                {
                    if (shouldTrace)
                    {
                        TracingAdapter.SendRequest(invocationId, httpRequest);
                    }
                    cancellationToken.ThrowIfCancellationRequested();
                    httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
                    if (shouldTrace)
                    {
                        TracingAdapter.ReceiveResponse(invocationId, httpResponse);
                    }
                    HttpStatusCode statusCode = httpResponse.StatusCode;
                    if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Accepted)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
                        if (shouldTrace)
                        {
                            TracingAdapter.Error(invocationId, ex);
                        }
                        throw ex;
                    }

                    // Create Result
                    OperationResultWithTrackingId result = null;
                    // Deserialize Response
                    result = new OperationResultWithTrackingId();
                    result.StatusCode = statusCode;
                    if (httpResponse.Headers.Contains("x-ms-request-id"))
                    {
                        result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
                    }
                    if (httpResponse.Headers.Contains("x-remoteapp-operation-tracking-id"))
                    {
                        result.TrackingId = httpResponse.Headers.GetValues("x-remoteapp-operation-tracking-id").FirstOrDefault();
                    }

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

        /// <summary>
        /// Updates the specified Active directory's configuration.
        /// </summary>
        /// <param name='collectionName'>
        /// Required. Name of the collection
        /// </param>
        /// <param name='activeDirectoryConfigDetails'>
        /// Required. AD config
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// The response containing the operation tracking id.
        /// </returns>
        public async Task<OperationResultWithTrackingId> SetAdAsync(string collectionName, ActiveDirectoryConfigParameter activeDirectoryConfigDetails, CancellationToken cancellationToken)
        {
            // Validate
            if (collectionName == null)
            {
                throw new ArgumentNullException("collectionName");
            }
            if (activeDirectoryConfigDetails == null)
            {
                throw new ArgumentNullException("activeDirectoryConfigDetails");
            }
            if (activeDirectoryConfigDetails.DomainName == null)
            {
                throw new ArgumentNullException("activeDirectoryConfigDetails.DomainName");
            }
            if (activeDirectoryConfigDetails.Password == null)
            {
                throw new ArgumentNullException("activeDirectoryConfigDetails.Password");
            }
            if (activeDirectoryConfigDetails.UserName == null)
            {
                throw new ArgumentNullException("activeDirectoryConfigDetails.UserName");
            }

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

            // Construct URL
            string url = "";
            url = url + "/";
            if (this.Client.Credentials.SubscriptionId != null)
            {
                url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
            }
            url = url + "/services/";
            if (this.Client.RdfeNamespace != null)
            {
                url = url + Uri.EscapeDataString(this.Client.RdfeNamespace);
            }
            url = url + "/collections/";
            url = url + Uri.EscapeDataString(collectionName);
            url = url + "/ad";
            List<string> queryParameters = new List<string>();
            queryParameters.Add("api-version=2014-09-01");
            if (queryParameters.Count > 0)
            {
                url = url + "?" + string.Join("&", queryParameters);
            }
            string baseUrl = this.Client.BaseUri.AbsoluteUri;
            // Trim '/' character from the end of baseUrl and beginning of url.
            if (baseUrl[baseUrl.Length - 1] == '/')
            {
                baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
            }
            if (url[0] == '/')
            {
                url = url.Substring(1);
            }
            url = baseUrl + "/" + url;
            url = url.Replace(" ", "%20");

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

                // Set Headers
                httpRequest.Headers.Add("x-ms-version", "2014-08-01");

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

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

                JObject activeDirectoryConfigParameterValue = new JObject();
                requestDoc = activeDirectoryConfigParameterValue;

                activeDirectoryConfigParameterValue["DomainName"] = activeDirectoryConfigDetails.DomainName;

                if (activeDirectoryConfigDetails.OrganizationalUnit != null)
                {
                    activeDirectoryConfigParameterValue["OrganizationalUnit"] = activeDirectoryConfigDetails.OrganizationalUnit;
                }

                activeDirectoryConfigParameterValue["ServiceAccountUserName"] = activeDirectoryConfigDetails.UserName;

                activeDirectoryConfigParameterValue["ServiceAccountPassword"] = activeDirectoryConfigDetails.Password;

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

                // Send Request
                HttpResponseMessage httpResponse = null;
                try
                {
                    if (shouldTrace)
                    {
                        TracingAdapter.SendRequest(invocationId, httpRequest);
                    }
                    cancellationToken.ThrowIfCancellationRequested();
                    httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
                    if (shouldTrace)
                    {
                        TracingAdapter.ReceiveResponse(invocationId, httpResponse);
                    }
                    HttpStatusCode statusCode = httpResponse.StatusCode;
                    if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Accepted)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
                        if (shouldTrace)
                        {
                            TracingAdapter.Error(invocationId, ex);
                        }
                        throw ex;
                    }

                    // Create Result
                    OperationResultWithTrackingId result = null;
                    // Deserialize Response
                    result = new OperationResultWithTrackingId();
                    result.StatusCode = statusCode;
                    if (httpResponse.Headers.Contains("x-ms-request-id"))
                    {
                        result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
                    }
                    if (httpResponse.Headers.Contains("x-remoteapp-operation-tracking-id"))
                    {
                        result.TrackingId = httpResponse.Headers.GetValues("x-remoteapp-operation-tracking-id").FirstOrDefault();
                    }

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