Ejemplo n.º 1
0
        /// <summary>
        /// The Check Static IP operation retrieves the details for the
        /// availability of static IP addresses for the given virtual network.
        /// </summary>
        /// <param name='networkName'>
        /// Required. The name of the virtual network.
        /// </param>
        /// <param name='ipAddress'>
        /// Required. The address of the static IP.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// A response that indicates the availability of a static IP address,
        /// and if not, provides a list of suggestions.
        /// </returns>
        public async Task <NetworkStaticIPAvailabilityResponse> CheckAsync(string networkName, string ipAddress, CancellationToken cancellationToken)
        {
            // Validate
            if (networkName == null)
            {
                throw new ArgumentNullException("networkName");
            }
            if (ipAddress == null)
            {
                throw new ArgumentNullException("ipAddress");
            }

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

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

            // Construct URL
            string url = "";

            url = url + "/";
            if (this.Client.Credentials.SubscriptionId != null)
            {
                url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
            }
            url = url + "/services/networking/";
            url = url + Uri.EscapeDataString(networkName);
            List <string> queryParameters = new List <string>();

            queryParameters.Add("op=checkavailability");
            queryParameters.Add("address=" + Uri.EscapeDataString(ipAddress));
            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("x-ms-version", "2015-04-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
                    NetworkStaticIPAvailabilityResponse result = null;
                    // Deserialize Response
                    if (statusCode == HttpStatusCode.OK)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                        result = new NetworkStaticIPAvailabilityResponse();
                        XDocument responseDoc = XDocument.Parse(responseContent);

                        XElement addressAvailabilityResponseElement = responseDoc.Element(XName.Get("AddressAvailabilityResponse", "http://schemas.microsoft.com/windowsazure"));
                        if (addressAvailabilityResponseElement != null)
                        {
                            XElement isAvailableElement = addressAvailabilityResponseElement.Element(XName.Get("IsAvailable", "http://schemas.microsoft.com/windowsazure"));
                            if (isAvailableElement != null)
                            {
                                bool isAvailableInstance = bool.Parse(isAvailableElement.Value);
                                result.IsAvailable = isAvailableInstance;
                            }

                            XElement availableAddressesSequenceElement = addressAvailabilityResponseElement.Element(XName.Get("AvailableAddresses", "http://schemas.microsoft.com/windowsazure"));
                            if (availableAddressesSequenceElement != null)
                            {
                                foreach (XElement availableAddressesElement in availableAddressesSequenceElement.Elements(XName.Get("AvailableAddress", "http://schemas.microsoft.com/windowsazure")))
                                {
                                    result.AvailableAddresses.Add(availableAddressesElement.Value);
                                }
                            }
                        }
                    }
                    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();
                }
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Create or update a transformation for a stream analytics job.
        /// </summary>
        /// <param name='resourceGroupName'>
        /// Required. The resource group name of the stream analytics job.
        /// </param>
        /// <param name='jobName'>
        /// Required. The name of the stream analytics job.
        /// </param>
        /// <param name='parameters'>
        /// Required. The parameters required to create or update a
        /// transformation for the stream analytics job.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// The response of the transformation create operation.
        /// </returns>
        public async Task <TransformationCreateOrUpdateResponse> CreateOrUpdateAsync(string resourceGroupName, string jobName, TransformationCreateOrUpdateParameters parameters, CancellationToken cancellationToken)
        {
            // Validate
            if (resourceGroupName == null)
            {
                throw new ArgumentNullException("resourceGroupName");
            }
            if (jobName == null)
            {
                throw new ArgumentNullException("jobName");
            }
            if (parameters == null)
            {
                throw new ArgumentNullException("parameters");
            }
            if (parameters.Transformation != null)
            {
                if (parameters.Transformation.Name == null)
                {
                    throw new ArgumentNullException("parameters.Transformation.Name");
                }
                if (parameters.Transformation.Properties == null)
                {
                    throw new ArgumentNullException("parameters.Transformation.Properties");
                }
                if (parameters.Transformation.Properties.Query == null)
                {
                    throw new ArgumentNullException("parameters.Transformation.Properties.Query");
                }
            }

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

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

            // Construct URL
            string url = "/subscriptions/" + (this.Client.Credentials.SubscriptionId == null ? "" : Uri.EscapeDataString(this.Client.Credentials.SubscriptionId)) + "/resourcegroups/" + Uri.EscapeDataString(resourceGroupName) + "/providers/Microsoft.StreamAnalytics/streamingjobs/" + Uri.EscapeDataString(jobName) + "/transformations/" + (parameters.Transformation.Name == null ? "" : Uri.EscapeDataString(parameters.Transformation.Name)) + "?";

            url = url + "api-version=2014-12-01-preview";
            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-client-request-id", Guid.NewGuid().ToString());

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

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

                JObject transformationCreateOrUpdateParametersValue = new JObject();
                requestDoc = transformationCreateOrUpdateParametersValue;

                if (parameters.Transformation != null)
                {
                    transformationCreateOrUpdateParametersValue["name"] = parameters.Transformation.Name;

                    JObject propertiesValue = new JObject();
                    transformationCreateOrUpdateParametersValue["properties"] = propertiesValue;

                    if (parameters.Transformation.Properties.Etag != null)
                    {
                        propertiesValue["etag"] = parameters.Transformation.Properties.Etag;
                    }

                    if (parameters.Transformation.Properties.StreamingUnits != null)
                    {
                        propertiesValue["streamingUnits"] = parameters.Transformation.Properties.StreamingUnits.Value;
                    }

                    propertiesValue["query"] = parameters.Transformation.Properties.Query;
                }

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

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

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

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

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

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

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

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

                                JToken etagValue = propertiesValue2["etag"];
                                if (etagValue != null && etagValue.Type != JTokenType.Null)
                                {
                                    string etagInstance = ((string)etagValue);
                                    propertiesInstance.Etag = etagInstance;
                                }

                                JToken streamingUnitsValue = propertiesValue2["streamingUnits"];
                                if (streamingUnitsValue != null && streamingUnitsValue.Type != JTokenType.Null)
                                {
                                    int streamingUnitsInstance = ((int)streamingUnitsValue);
                                    propertiesInstance.StreamingUnits = streamingUnitsInstance;
                                }

                                JToken queryValue = propertiesValue2["query"];
                                if (queryValue != null && queryValue.Type != JTokenType.Null)
                                {
                                    string queryInstance = ((string)queryValue);
                                    propertiesInstance.Query = queryInstance;
                                }
                            }
                        }
                    }
                    result.StatusCode = statusCode;
                    if (httpResponse.Headers.Contains("Date"))
                    {
                        result.Date = DateTime.Parse(httpResponse.Headers.GetValues("Date").FirstOrDefault(), CultureInfo.InvariantCulture);
                    }
                    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();
                }
            }
        }
        public SubscriptionCloudCredentials GetSubscriptionCloudCredentials(AzureContext context, AzureEnvironment.Endpoint targetEndpoint)
        {
            if (context.Subscription == null)
            {
                var exceptionMessage = targetEndpoint == AzureEnvironment.Endpoint.ServiceManagement
                    ? Resources.InvalidDefaultSubscription
                    : Resources.NoSubscriptionInContext;
                throw new ApplicationException(exceptionMessage);
            }

            if (context.Account == null)
            {
                var exceptionMessage = targetEndpoint == AzureEnvironment.Endpoint.ServiceManagement
                    ? Resources.AccountNotFound
                    : Resources.ArmAccountNotFound;
                throw new ArgumentException(exceptionMessage);
            }

            if (context.Account.Type == AzureAccount.AccountType.Certificate)
            {
                var certificate = AzureSession.DataStore.GetCertificate(context.Account.Id);
                return(new CertificateCloudCredentials(context.Subscription.Id.ToString(), certificate));
            }

            if (context.Account.Type == AzureAccount.AccountType.AccessToken)
            {
                return(new TokenCloudCredentials(context.Subscription.Id.ToString(), context.Account.GetProperty(AzureAccount.Property.AccessToken)));
            }

            string tenant = null;

            if (context.Subscription != null && context.Account != null)
            {
                tenant = context.Subscription.GetPropertyAsArray(AzureSubscription.Property.Tenants)
                         .Intersect(context.Account.GetPropertyAsArray(AzureAccount.Property.Tenants))
                         .FirstOrDefault();
            }

            if (tenant == null && context.Tenant != null && context.Tenant.Id != Guid.Empty)
            {
                tenant = context.Tenant.Id.ToString();
            }

            if (tenant == null)
            {
                var exceptionMessage = targetEndpoint == AzureEnvironment.Endpoint.ServiceManagement
                    ? Resources.TenantNotFound
                    : Resources.NoTenantInContext;
                throw new ArgumentException(exceptionMessage);
            }

            try
            {
                TracingAdapter.Information(Resources.UPNAuthenticationTrace,
                                           context.Account.Id, context.Environment.Name, tenant);
                var tokenCache = AzureSession.TokenCache;
                if (context.TokenCache != null && context.TokenCache.Length > 0)
                {
                    tokenCache = new TokenCache(context.TokenCache);
                }

                var token = Authenticate(context.Account, context.Environment,
                                         tenant, null, ShowDialog.Never, tokenCache, context.Environment.GetTokenAudience(targetEndpoint));

                if (context.TokenCache != null && context.TokenCache.Length > 0)
                {
                    context.TokenCache = tokenCache.Serialize();
                }

                TracingAdapter.Information(Resources.UPNAuthenticationTokenTrace,
                                           token.LoginType, token.TenantId, token.UserId);
                return(new AccessTokenCredential(context.Subscription.Id, token));
            }
            catch (Exception ex)
            {
                TracingAdapter.Information(Resources.AdalAuthException, ex.Message);
                var exceptionMessage = targetEndpoint == AzureEnvironment.Endpoint.ServiceManagement
                    ? Resources.InvalidSubscriptionState
                    : Resources.InvalidArmContext;
                throw new ArgumentException(exceptionMessage, ex);
            }
        }
        /// <summary>
        /// The Get Operation Status operation returns the status of the
        /// specified operation. After calling an asynchronous operation, you
        /// can call Get Operation Status to determine whether the operation
        /// has succeeded, failed, or is still in progress.
        /// </summary>
        /// <param name='operationStatusLink'>
        /// Required. Location value returned by the Begin operation.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// A standard service response for long running operations.
        /// </returns>
        public async Task <LongRunningOperationResultResponse> GetOperationResultStatusAsync(string operationStatusLink, CancellationToken cancellationToken)
        {
            // Validate
            if (operationStatusLink == null)
            {
                throw new ArgumentNullException("operationStatusLink");
            }

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

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

            // Construct URL
            string url = "";

            url = url + operationStatusLink;
            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("x-ms-version", "2013-06-01");

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

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

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

                    // Create Result
                    LongRunningOperationResultResponse result = null;
                    // Deserialize Response
                    result            = new LongRunningOperationResultResponse();
                    result.StatusCode = statusCode;
                    if (httpResponse.Headers.Contains("x-ms-request-id"))
                    {
                        result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
                    }
                    if (statusCode == HttpStatusCode.NotFound)
                    {
                        result.Status = OperationStatus.Failed;
                    }
                    if (statusCode == HttpStatusCode.BadRequest)
                    {
                        result.Status = OperationStatus.Failed;
                    }
                    if (statusCode == HttpStatusCode.OK)
                    {
                        result.Status = OperationStatus.Succeeded;
                    }
                    if (statusCode == HttpStatusCode.NoContent)
                    {
                        result.Status = OperationStatus.Succeeded;
                    }
                    if (statusCode == HttpStatusCode.Created)
                    {
                        result.Status = OperationStatus.Succeeded;
                    }

                    if (shouldTrace)
                    {
                        TracingAdapter.Exit(invocationId, result);
                    }
                    return(result);
                }
                finally
                {
                    if (httpResponse != null)
                    {
                        httpResponse.Dispose();
                    }
                }
            }
            finally
            {
                if (httpRequest != null)
                {
                    httpRequest.Dispose();
                }
            }
        }
        /// <summary>
        /// Gets a list of the subscriptionIds.
        /// </summary>
        /// <param name='nextLink'>
        /// Required. NextLink from the previous successful call to List
        /// operation.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// Subscription list operation response.
        /// </returns>
        public async Task <SubscriptionListResult> ListNextAsync(string nextLink, CancellationToken cancellationToken)
        {
            // Validate
            if (nextLink == null)
            {
                throw new ArgumentNullException("nextLink");
            }

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

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

            // Construct URL
            string url = "";

            url = url + nextLink;
            url = url.Replace(" ", "%20");

            // Create HTTP transport objects
            HttpRequestMessage httpRequest = null;

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

                // Set Headers

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

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

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

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

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

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

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

                                    JToken subscriptionIdValue = valueValue["subscriptionId"];
                                    if (subscriptionIdValue != null && subscriptionIdValue.Type != JTokenType.Null)
                                    {
                                        string subscriptionIdInstance = ((string)subscriptionIdValue);
                                        subscriptionInstance.SubscriptionId = subscriptionIdInstance;
                                    }

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

                                    JToken stateValue = valueValue["state"];
                                    if (stateValue != null && stateValue.Type != JTokenType.Null)
                                    {
                                        string stateInstance = ((string)stateValue);
                                        subscriptionInstance.State = stateInstance;
                                    }

                                    JToken subscriptionPoliciesValue = valueValue["subscriptionPolicies"];
                                    if (subscriptionPoliciesValue != null && subscriptionPoliciesValue.Type != JTokenType.Null)
                                    {
                                        SubscriptionPolicies subscriptionPoliciesInstance = new SubscriptionPolicies();
                                        subscriptionInstance.SubscriptionPolicies = subscriptionPoliciesInstance;

                                        JToken locationPlacementIdValue = subscriptionPoliciesValue["locationPlacementId"];
                                        if (locationPlacementIdValue != null && locationPlacementIdValue.Type != JTokenType.Null)
                                        {
                                            string locationPlacementIdInstance = ((string)locationPlacementIdValue);
                                            subscriptionPoliciesInstance.LocationPlacementId = locationPlacementIdInstance;
                                        }

                                        JToken quotaIdValue = subscriptionPoliciesValue["quotaId"];
                                        if (quotaIdValue != null && quotaIdValue.Type != JTokenType.Null)
                                        {
                                            string quotaIdInstance = ((string)quotaIdValue);
                                            subscriptionPoliciesInstance.QuotaId = quotaIdInstance;
                                        }
                                    }
                                }
                            }

                            JToken nextLinkValue = responseDoc["nextLink"];
                            if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null)
                            {
                                string nextLinkInstance = ((string)nextLinkValue);
                                result.NextLink = nextLinkInstance;
                            }
                        }
                    }
                    result.StatusCode = statusCode;
                    if (httpResponse.Headers.Contains("x-ms-request-id"))
                    {
                        result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
                    }

                    if (shouldTrace)
                    {
                        TracingAdapter.Exit(invocationId, result);
                    }
                    return(result);
                }
                finally
                {
                    if (httpResponse != null)
                    {
                        httpResponse.Dispose();
                    }
                }
            }
            finally
            {
                if (httpRequest != null)
                {
                    httpRequest.Dispose();
                }
            }
        }
        public ServiceClientCredentials GetServiceClientCredentials(IAzureContext context, string targetEndpoint)
        {
            if (context.Account == null)
            {
                throw new AzPSArgumentException(Resources.ArmAccountNotFound, "context.Account", ErrorKind.UserError);
            }
            switch (context.Account.Type)
            {
            case AzureAccount.AccountType.Certificate:
                throw new NotSupportedException(AzureAccount.AccountType.Certificate.ToString());

            case AzureAccount.AccountType.AccessToken:
                return(new RenewingTokenCredential(new ExternalAccessToken(GetEndpointToken(context.Account, targetEndpoint), () => GetEndpointToken(context.Account, targetEndpoint))));
            }


            string tenant = null;

            if (context.Subscription != null && context.Account != null)
            {
                tenant = context.Subscription.GetPropertyAsArray(AzureSubscription.Property.Tenants)
                         .Intersect(context.Account.GetPropertyAsArray(AzureAccount.Property.Tenants))
                         .FirstOrDefault();
            }

            if (tenant == null && context.Tenant != null && new Guid(context.Tenant.Id) != Guid.Empty)
            {
                tenant = context.Tenant.Id.ToString();
            }

            if (tenant == null)
            {
                throw new ArgumentException(Resources.NoTenantInContext);
            }

            try
            {
                TracingAdapter.Information(Resources.UPNAuthenticationTrace,
                                           context.Account.Id, context.Environment.Name, tenant);

                IAccessToken token = null;
                switch (context.Account.Type)
                {
                case AzureAccount.AccountType.ManagedService:
                case AzureAccount.AccountType.User:
                case AzureAccount.AccountType.ServicePrincipal:
                    token = Authenticate(context.Account, context.Environment, tenant, null, ShowDialog.Never, null, context.Environment.GetTokenAudience(targetEndpoint));
                    break;

                default:
                    throw new NotSupportedException(context.Account.Type.ToString());
                }

                TracingAdapter.Information(Resources.UPNAuthenticationTokenTrace,
                                           token.LoginType, token.TenantId, token.UserId);
                return(new RenewingTokenCredential(token));
            }
            catch (Exception ex)
            {
                TracingAdapter.Information(Resources.AdalAuthException, ex.Message);
                throw new ArgumentException(Resources.InvalidArmContext, ex);
            }
        }
        /// <summary>
        /// List all API associated products.
        /// </summary>
        /// <param name='nextLink'>
        /// Required. NextLink from the previous successful call to List
        /// operation.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// List Products operation response details.
        /// </returns>
        public async Task <ProductListResponse> ListNextAsync(string nextLink, CancellationToken cancellationToken)
        {
            // Validate
            if (nextLink == null)
            {
                throw new ArgumentNullException("nextLink");
            }

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

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

            // Construct URL
            string url = "";

            url = url + nextLink;
            url = url.Replace(" ", "%20");

            // Create HTTP transport objects
            HttpRequestMessage httpRequest = null;

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

                // Set Headers

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

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

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

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

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

                        if (responseDoc != null && responseDoc.Type != JTokenType.Null)
                        {
                            ProductPaged resultInstance = new ProductPaged();
                            result.Result = resultInstance;

                            JToken valueArray = responseDoc["value"];
                            if (valueArray != null && valueArray.Type != JTokenType.Null)
                            {
                                foreach (JToken valueValue in ((JArray)valueArray))
                                {
                                    ProductContract productContractInstance = new ProductContract();
                                    resultInstance.Values.Add(productContractInstance);

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

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

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

                                    JToken termsValue = valueValue["terms"];
                                    if (termsValue != null && termsValue.Type != JTokenType.Null)
                                    {
                                        string termsInstance = ((string)termsValue);
                                        productContractInstance.Terms = termsInstance;
                                    }

                                    JToken subscriptionRequiredValue = valueValue["subscriptionRequired"];
                                    if (subscriptionRequiredValue != null && subscriptionRequiredValue.Type != JTokenType.Null)
                                    {
                                        bool subscriptionRequiredInstance = ((bool)subscriptionRequiredValue);
                                        productContractInstance.SubscriptionRequired = subscriptionRequiredInstance;
                                    }

                                    JToken approvalRequiredValue = valueValue["approvalRequired"];
                                    if (approvalRequiredValue != null && approvalRequiredValue.Type != JTokenType.Null)
                                    {
                                        bool approvalRequiredInstance = ((bool)approvalRequiredValue);
                                        productContractInstance.ApprovalRequired = approvalRequiredInstance;
                                    }

                                    JToken subscriptionsLimitValue = valueValue["subscriptionsLimit"];
                                    if (subscriptionsLimitValue != null && subscriptionsLimitValue.Type != JTokenType.Null)
                                    {
                                        int subscriptionsLimitInstance = ((int)subscriptionsLimitValue);
                                        productContractInstance.SubscriptionsLimit = subscriptionsLimitInstance;
                                    }

                                    JToken stateValue = valueValue["state"];
                                    if (stateValue != null && stateValue.Type != JTokenType.Null)
                                    {
                                        ProductStateContract stateInstance = ((ProductStateContract)Enum.Parse(typeof(ProductStateContract), ((string)stateValue), true));
                                        productContractInstance.State = stateInstance;
                                    }
                                }
                            }

                            JToken countValue = responseDoc["count"];
                            if (countValue != null && countValue.Type != JTokenType.Null)
                            {
                                long countInstance = ((long)countValue);
                                resultInstance.TotalCount = countInstance;
                            }

                            JToken nextLinkValue = responseDoc["nextLink"];
                            if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null)
                            {
                                string nextLinkInstance = ((string)nextLinkValue);
                                resultInstance.NextLink = nextLinkInstance;
                            }
                        }
                    }
                    result.StatusCode = statusCode;
                    if (httpResponse.Headers.Contains("x-ms-request-id"))
                    {
                        result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
                    }

                    if (shouldTrace)
                    {
                        TracingAdapter.Exit(invocationId, result);
                    }
                    return(result);
                }
                finally
                {
                    if (httpResponse != null)
                    {
                        httpResponse.Dispose();
                    }
                }
            }
            finally
            {
                if (httpRequest != null)
                {
                    httpRequest.Dispose();
                }
            }
        }
Ejemplo n.º 8
0
        /// <summary>
        /// The Get Operation Status operation returns the status of the
        /// specified operation. After calling an asynchronous operation, you
        /// can call Get Operation Status to determine whether the operation
        /// has succeeded, failed, or is still in progress.
        /// </summary>
        /// <param name='operationStatusLink'>
        /// Required. Location value returned by the Begin operation.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// The azure async operation response.
        /// </returns>
        public async Task <OperationResource> GetLongRunningOperationStatusAsync(string operationStatusLink, CancellationToken cancellationToken)
        {
            // Validate
            if (operationStatusLink == null)
            {
                throw new ArgumentNullException("operationStatusLink");
            }

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

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

            // Construct URL
            string url = "";

            url = url + operationStatusLink;
            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("User-Agent", "ARM SDK v1.0.7-preview");
                httpRequest.Headers.Add("x-ms-version", "2015-03-01-preview");

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

                // Send Request
                HttpResponseMessage httpResponse = null;
                try
                {
                    if (shouldTrace)
                    {
                        TracingAdapter.SendRequest(invocationId, httpRequest);
                    }
                    cancellationToken.ThrowIfCancellationRequested();
                    httpResponse = await this.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
                    OperationResource result = null;
                    // Deserialize Response
                    if (statusCode == HttpStatusCode.OK)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

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

                        if (responseDoc != null && responseDoc.Type != JTokenType.Null)
                        {
                            JToken statusValue = responseDoc["status"];
                            if (statusValue != null && statusValue.Type != JTokenType.Null)
                            {
                                AsyncOperationState statusInstance = ((AsyncOperationState)Enum.Parse(typeof(AsyncOperationState), ((string)statusValue), true));
                                result.State = statusInstance;
                            }

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

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

                                JToken messageValue = errorValue["message"];
                                if (messageValue != null && messageValue.Type != JTokenType.Null)
                                {
                                    string messageInstance = ((string)messageValue);
                                    errorInstance.Message = messageInstance;
                                }
                            }
                        }
                    }
                    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();
                }
            }
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Get role definition by name (GUID).
        /// </summary>
        /// <param name='roleDefinitionName'>
        /// Required. Role definition name (GUID).
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// Role definition get operation result.
        /// </returns>
        public async Task <RoleDefinitionGetResult> GetAsync(Guid roleDefinitionName, 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>();
                tracingParameters.Add("roleDefinitionName", roleDefinitionName);
                TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters);
            }

            // Construct URL
            string url = "";

            url = url + "/subscriptions/";
            if (this.Client.Credentials.SubscriptionId != null)
            {
                url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
            }
            url = url + "/providers/Microsoft.Authorization/roleDefinitions/";
            url = url + Uri.EscapeDataString(roleDefinitionName.ToString());
            List <string> queryParameters = new List <string>();

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

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

            // Create HTTP transport objects
            HttpRequestMessage httpRequest = null;

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

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

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

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

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

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

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

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

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

                                JToken roleNameValue = propertiesValue["roleName"];
                                if (roleNameValue != null && roleNameValue.Type != JTokenType.Null)
                                {
                                    string roleNameInstance = ((string)roleNameValue);
                                    propertiesInstance.RoleName = roleNameInstance;
                                }

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

                                JToken scopeValue = propertiesValue["scope"];
                                if (scopeValue != null && scopeValue.Type != JTokenType.Null)
                                {
                                    string scopeInstance = ((string)scopeValue);
                                    propertiesInstance.Scope = scopeInstance;
                                }

                                JToken typeValue2 = propertiesValue["type"];
                                if (typeValue2 != null && typeValue2.Type != JTokenType.Null)
                                {
                                    string typeInstance2 = ((string)typeValue2);
                                    propertiesInstance.Type = typeInstance2;
                                }

                                JToken permissionsArray = propertiesValue["permissions"];
                                if (permissionsArray != null && permissionsArray.Type != JTokenType.Null)
                                {
                                    foreach (JToken permissionsValue in ((JArray)permissionsArray))
                                    {
                                        Permission permissionInstance = new Permission();
                                        propertiesInstance.Permissions.Add(permissionInstance);

                                        JToken actionsArray = permissionsValue["actions"];
                                        if (actionsArray != null && actionsArray.Type != JTokenType.Null)
                                        {
                                            foreach (JToken actionsValue in ((JArray)actionsArray))
                                            {
                                                permissionInstance.Actions.Add(((string)actionsValue));
                                            }
                                        }

                                        JToken notActionsArray = permissionsValue["notActions"];
                                        if (notActionsArray != null && notActionsArray.Type != JTokenType.Null)
                                        {
                                            foreach (JToken notActionsValue in ((JArray)notActionsArray))
                                            {
                                                permissionInstance.NotActions.Add(((string)notActionsValue));
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    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();
                }
            }
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Update tenant settings.
        /// </summary>
        /// <param name='resourceGroupName'>
        /// Required. The name of the resource group.
        /// </param>
        /// <param name='serviceName'>
        /// Required. The name of the Api Management service.
        /// </param>
        /// <param name='parameters'>
        /// Required. Parameters.
        /// </param>
        /// <param name='etag'>
        /// Required. ETag.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// A standard service response including an HTTP status code and
        /// request ID.
        /// </returns>
        public async Task <AzureOperationResponse> UpdateAsync(string resourceGroupName, string serviceName, AccessInformationUpdateParameters parameters, string etag, CancellationToken cancellationToken)
        {
            // Validate
            if (resourceGroupName == null)
            {
                throw new ArgumentNullException("resourceGroupName");
            }
            if (serviceName == null)
            {
                throw new ArgumentNullException("serviceName");
            }
            if (parameters == null)
            {
                throw new ArgumentNullException("parameters");
            }
            if (etag == null)
            {
                throw new ArgumentNullException("etag");
            }

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

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

            // Construct URL
            string url = "";

            url = url + "/subscriptions/";
            if (this.Client.Credentials.SubscriptionId != null)
            {
                url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
            }
            url = url + "/resourceGroups/";
            url = url + Uri.EscapeDataString(resourceGroupName);
            url = url + "/providers/";
            url = url + "Microsoft.ApiManagement";
            url = url + "/service/";
            url = url + Uri.EscapeDataString(serviceName);
            url = url + "/tenant/access";
            List <string> queryParameters = new List <string>();

            queryParameters.Add("api-version=2016-07-07");
            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     = new HttpMethod("PATCH");
                httpRequest.RequestUri = new Uri(url);

                // Set Headers
                httpRequest.Headers.TryAddWithoutValidation("If-Match", etag);

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

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

                JObject accessInformationUpdateParametersValue = new JObject();
                requestDoc = accessInformationUpdateParametersValue;

                accessInformationUpdateParametersValue["enabled"] = parameters.Enabled;

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

                // 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.NoContent)
                    {
                        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
                    AzureOperationResponse result = null;
                    // Deserialize Response
                    result            = new AzureOperationResponse();
                    result.StatusCode = statusCode;
                    if (httpResponse.Headers.Contains("x-ms-request-id"))
                    {
                        result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
                    }

                    if (shouldTrace)
                    {
                        TracingAdapter.Exit(invocationId, result);
                    }
                    return(result);
                }
                finally
                {
                    if (httpResponse != null)
                    {
                        httpResponse.Dispose();
                    }
                }
            }
            finally
            {
                if (httpRequest != null)
                {
                    httpRequest.Dispose();
                }
            }
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Get tenant settings.
        /// </summary>
        /// <param name='resourceGroupName'>
        /// Required. The name of the resource group.
        /// </param>
        /// <param name='serviceName'>
        /// Required. The name of the Api Management service.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// Get Tenant Access Information operation response details.
        /// </returns>
        public async Task <AccessInformationGetResponse> GetAsync(string resourceGroupName, string serviceName, CancellationToken cancellationToken)
        {
            // Validate
            if (resourceGroupName == null)
            {
                throw new ArgumentNullException("resourceGroupName");
            }
            if (serviceName == null)
            {
                throw new ArgumentNullException("serviceName");
            }

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

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

            // Construct URL
            string url = "";

            url = url + "/subscriptions/";
            if (this.Client.Credentials.SubscriptionId != null)
            {
                url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
            }
            url = url + "/resourceGroups/";
            url = url + Uri.EscapeDataString(resourceGroupName);
            url = url + "/providers/";
            url = url + "Microsoft.ApiManagement";
            url = url + "/service/";
            url = url + Uri.EscapeDataString(serviceName);
            url = url + "/tenant/access";
            List <string> queryParameters = new List <string>();

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

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

            // Create HTTP transport objects
            HttpRequestMessage httpRequest = null;

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

                // Set Headers

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

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

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

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

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

                        if (responseDoc != null && responseDoc.Type != JTokenType.Null)
                        {
                            AccessInformationContract valueInstance = new AccessInformationContract();
                            result.Value = valueInstance;

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

                            JToken primaryKeyValue = responseDoc["primaryKey"];
                            if (primaryKeyValue != null && primaryKeyValue.Type != JTokenType.Null)
                            {
                                string primaryKeyInstance = ((string)primaryKeyValue);
                                valueInstance.PrimaryKey = primaryKeyInstance;
                            }

                            JToken secondaryKeyValue = responseDoc["secondaryKey"];
                            if (secondaryKeyValue != null && secondaryKeyValue.Type != JTokenType.Null)
                            {
                                string secondaryKeyInstance = ((string)secondaryKeyValue);
                                valueInstance.SecondaryKey = secondaryKeyInstance;
                            }

                            JToken enabledValue = responseDoc["enabled"];
                            if (enabledValue != null && enabledValue.Type != JTokenType.Null)
                            {
                                bool enabledInstance = ((bool)enabledValue);
                                valueInstance.Enabled = enabledInstance;
                            }
                        }
                    }
                    result.StatusCode = statusCode;
                    if (httpResponse.Headers.Contains("ETag"))
                    {
                        result.ETag = httpResponse.Headers.GetValues("ETag").FirstOrDefault();
                    }
                    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>
        /// The Create Cloud Service operation creates a Windows Azure cloud
        /// service in a Windows Azure subscription.
        /// </summary>
        /// <param name='parameters'>
        /// Required. Parameters used to specify how the Create procedure will
        /// function.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// The response body contains the status of the specified asynchronous
        /// operation, indicating whether it has succeeded, is inprogress, or
        /// has failed. Note that this status is distinct from the HTTP status
        /// code returned for the Get Operation Status operation itself.  If
        /// the asynchronous operation succeeded, the response body includes
        /// the HTTP status code for the successful request.  If the
        /// asynchronous operation failed, the response body includes the HTTP
        /// status code for the failed request, and also includes error
        /// information regarding the failure.
        /// </returns>
        public async Task <OperationStatusResponse> BeginCreatingAsync(CloudServiceCreateParameters parameters, CancellationToken cancellationToken)
        {
            // Validate
            if (parameters == null)
            {
                throw new ArgumentNullException("parameters");
            }
            if (parameters.Description == null)
            {
                throw new ArgumentNullException("parameters.Description");
            }
            if (parameters.GeoRegion == null)
            {
                throw new ArgumentNullException("parameters.GeoRegion");
            }
            if (parameters.Label == null)
            {
                throw new ArgumentNullException("parameters.Label");
            }
            if (parameters.Name == null)
            {
                throw new ArgumentNullException("parameters.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("parameters", parameters);
                TracingAdapter.Enter(invocationId, this, "BeginCreatingAsync", tracingParameters);
            }

            // Construct URL
            string url     = "/" + (this.Client.Credentials.SubscriptionId == null ? "" : Uri.EscapeDataString(this.Client.Credentials.SubscriptionId)) + "/CloudServices/" + Uri.EscapeDataString(parameters.Name) + "/";
            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", "2013-06-01");

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

                // Serialize Request
                string    requestContent = null;
                XDocument requestDoc     = new XDocument();

                XElement cloudServiceElement = new XElement(XName.Get("CloudService", "http://schemas.microsoft.com/windowsazure"));
                requestDoc.Add(cloudServiceElement);

                XElement nameElement = new XElement(XName.Get("Name", "http://schemas.microsoft.com/windowsazure"));
                nameElement.Value = parameters.Name;
                cloudServiceElement.Add(nameElement);

                XElement labelElement = new XElement(XName.Get("Label", "http://schemas.microsoft.com/windowsazure"));
                labelElement.Value = parameters.Label;
                cloudServiceElement.Add(labelElement);

                XElement descriptionElement = new XElement(XName.Get("Description", "http://schemas.microsoft.com/windowsazure"));
                descriptionElement.Value = parameters.Description;
                cloudServiceElement.Add(descriptionElement);

                XElement geoRegionElement = new XElement(XName.Get("GeoRegion", "http://schemas.microsoft.com/windowsazure"));
                geoRegionElement.Value = parameters.GeoRegion;
                cloudServiceElement.Add(geoRegionElement);

                requestContent      = requestDoc.ToString();
                httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
                httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/xml");

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

                    if (shouldTrace)
                    {
                        TracingAdapter.ReceiveResponse(invocationId, httpResponse);
                    }
                    HttpStatusCode statusCode = httpResponse.StatusCode;
                    if (statusCode != HttpStatusCode.Accepted)
                    {
                        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
                    OperationStatusResponse result = null;
                    // Deserialize Response
                    result            = new OperationStatusResponse();
                    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>
        /// The List Cloud Services operation enumerates Windows Azure Store
        /// entries that are provisioned for a subscription.
        /// </summary>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// The response structure for the Cloud Service List operation.
        /// </returns>
        public async Task <CloudServiceListResponse> 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     = "/" + (this.Client.Credentials.SubscriptionId == null ? "" : Uri.EscapeDataString(this.Client.Credentials.SubscriptionId)) + "/CloudServices/";
            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("x-ms-version", "2013-06-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
                    CloudServiceListResponse result = null;
                    // Deserialize Response
                    if (statusCode == HttpStatusCode.OK)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                        result = new CloudServiceListResponse();
                        XDocument responseDoc = XDocument.Parse(responseContent);

                        XElement cloudServicesSequenceElement = responseDoc.Element(XName.Get("CloudServices", "http://schemas.microsoft.com/windowsazure"));
                        if (cloudServicesSequenceElement != null)
                        {
                            foreach (XElement cloudServicesElement in cloudServicesSequenceElement.Elements(XName.Get("CloudService", "http://schemas.microsoft.com/windowsazure")))
                            {
                                CloudServiceListResponse.CloudService cloudServiceInstance = new CloudServiceListResponse.CloudService();
                                result.CloudServices.Add(cloudServiceInstance);

                                XElement nameElement = cloudServicesElement.Element(XName.Get("Name", "http://schemas.microsoft.com/windowsazure"));
                                if (nameElement != null)
                                {
                                    string nameInstance = nameElement.Value;
                                    cloudServiceInstance.Name = nameInstance;
                                }

                                XElement labelElement = cloudServicesElement.Element(XName.Get("Label", "http://schemas.microsoft.com/windowsazure"));
                                if (labelElement != null)
                                {
                                    string labelInstance = TypeConversion.FromBase64String(labelElement.Value);
                                    cloudServiceInstance.Label = labelInstance;
                                }

                                XElement descriptionElement = cloudServicesElement.Element(XName.Get("Description", "http://schemas.microsoft.com/windowsazure"));
                                if (descriptionElement != null)
                                {
                                    string descriptionInstance = descriptionElement.Value;
                                    cloudServiceInstance.Description = descriptionInstance;
                                }

                                XElement geoRegionElement = cloudServicesElement.Element(XName.Get("GeoRegion", "http://schemas.microsoft.com/windowsazure"));
                                if (geoRegionElement != null)
                                {
                                    string geoRegionInstance = geoRegionElement.Value;
                                    cloudServiceInstance.GeoRegion = geoRegionInstance;
                                }

                                XElement resourcesSequenceElement = cloudServicesElement.Element(XName.Get("Resources", "http://schemas.microsoft.com/windowsazure"));
                                if (resourcesSequenceElement != null)
                                {
                                    foreach (XElement resourcesElement in resourcesSequenceElement.Elements(XName.Get("Resource", "http://schemas.microsoft.com/windowsazure")))
                                    {
                                        CloudServiceListResponse.CloudService.AddOnResource resourceInstance = new CloudServiceListResponse.CloudService.AddOnResource();
                                        cloudServiceInstance.Resources.Add(resourceInstance);

                                        XElement resourceProviderNamespaceElement = resourcesElement.Element(XName.Get("ResourceProviderNamespace", "http://schemas.microsoft.com/windowsazure"));
                                        if (resourceProviderNamespaceElement != null)
                                        {
                                            string resourceProviderNamespaceInstance = resourceProviderNamespaceElement.Value;
                                            resourceInstance.Namespace = resourceProviderNamespaceInstance;
                                        }

                                        XElement typeElement = resourcesElement.Element(XName.Get("Type", "http://schemas.microsoft.com/windowsazure"));
                                        if (typeElement != null)
                                        {
                                            string typeInstance = typeElement.Value;
                                            resourceInstance.Type = typeInstance;
                                        }

                                        XElement nameElement2 = resourcesElement.Element(XName.Get("Name", "http://schemas.microsoft.com/windowsazure"));
                                        if (nameElement2 != null)
                                        {
                                            string nameInstance2 = nameElement2.Value;
                                            resourceInstance.Name = nameInstance2;
                                        }

                                        XElement planElement = resourcesElement.Element(XName.Get("Plan", "http://schemas.microsoft.com/windowsazure"));
                                        if (planElement != null)
                                        {
                                            string planInstance = planElement.Value;
                                            resourceInstance.Plan = planInstance;
                                        }

                                        XElement schemaVersionElement = resourcesElement.Element(XName.Get("SchemaVersion", "http://schemas.microsoft.com/windowsazure"));
                                        if (schemaVersionElement != null)
                                        {
                                            string schemaVersionInstance = schemaVersionElement.Value;
                                            resourceInstance.SchemaVersion = schemaVersionInstance;
                                        }

                                        XElement eTagElement = resourcesElement.Element(XName.Get("ETag", "http://schemas.microsoft.com/windowsazure"));
                                        if (eTagElement != null)
                                        {
                                            string eTagInstance = eTagElement.Value;
                                            resourceInstance.ETag = eTagInstance;
                                        }

                                        XElement stateElement = resourcesElement.Element(XName.Get("State", "http://schemas.microsoft.com/windowsazure"));
                                        if (stateElement != null)
                                        {
                                            string stateInstance = stateElement.Value;
                                            resourceInstance.State = stateInstance;
                                        }

                                        XElement usageMetersSequenceElement = resourcesElement.Element(XName.Get("UsageMeters", "http://schemas.microsoft.com/windowsazure"));
                                        if (usageMetersSequenceElement != null)
                                        {
                                            foreach (XElement usageMetersElement in usageMetersSequenceElement.Elements(XName.Get("UsageMeter", "http://schemas.microsoft.com/windowsazure")))
                                            {
                                                CloudServiceListResponse.CloudService.AddOnResource.UsageLimit usageMeterInstance = new CloudServiceListResponse.CloudService.AddOnResource.UsageLimit();
                                                resourceInstance.UsageLimits.Add(usageMeterInstance);

                                                XElement nameElement3 = usageMetersElement.Element(XName.Get("Name", "http://schemas.microsoft.com/windowsazure"));
                                                if (nameElement3 != null)
                                                {
                                                    string nameInstance3 = nameElement3.Value;
                                                    usageMeterInstance.Name = nameInstance3;
                                                }

                                                XElement unitElement = usageMetersElement.Element(XName.Get("Unit", "http://schemas.microsoft.com/windowsazure"));
                                                if (unitElement != null)
                                                {
                                                    string unitInstance = unitElement.Value;
                                                    usageMeterInstance.Unit = unitInstance;
                                                }

                                                XElement includedElement = usageMetersElement.Element(XName.Get("Included", "http://schemas.microsoft.com/windowsazure"));
                                                if (includedElement != null)
                                                {
                                                    long includedInstance = long.Parse(includedElement.Value, CultureInfo.InvariantCulture);
                                                    usageMeterInstance.AmountIncluded = includedInstance;
                                                }

                                                XElement usedElement = usageMetersElement.Element(XName.Get("Used", "http://schemas.microsoft.com/windowsazure"));
                                                if (usedElement != null)
                                                {
                                                    long usedInstance = long.Parse(usedElement.Value, CultureInfo.InvariantCulture);
                                                    usageMeterInstance.AmountUsed = usedInstance;
                                                }
                                            }
                                        }

                                        XElement outputItemsSequenceElement = resourcesElement.Element(XName.Get("OutputItems", "http://schemas.microsoft.com/windowsazure"));
                                        if (outputItemsSequenceElement != null)
                                        {
                                            foreach (XElement outputItemsElement in outputItemsSequenceElement.Elements(XName.Get("OutputItem", "http://schemas.microsoft.com/windowsazure")))
                                            {
                                                string outputItemsKey   = outputItemsElement.Element(XName.Get("Key", "http://schemas.microsoft.com/windowsazure")).Value;
                                                string outputItemsValue = outputItemsElement.Element(XName.Get("Value", "http://schemas.microsoft.com/windowsazure")).Value;
                                                resourceInstance.OutputItems.Add(outputItemsKey, outputItemsValue);
                                            }
                                        }

                                        XElement operationStatusElement = resourcesElement.Element(XName.Get("OperationStatus", "http://schemas.microsoft.com/windowsazure"));
                                        if (operationStatusElement != null)
                                        {
                                            CloudServiceListResponse.CloudService.AddOnResource.OperationStatus operationStatusInstance = new CloudServiceListResponse.CloudService.AddOnResource.OperationStatus();
                                            resourceInstance.Status = operationStatusInstance;

                                            XElement typeElement2 = operationStatusElement.Element(XName.Get("Type", "http://schemas.microsoft.com/windowsazure"));
                                            if (typeElement2 != null)
                                            {
                                                string typeInstance2 = typeElement2.Value;
                                                operationStatusInstance.Type = typeInstance2;
                                            }

                                            XElement resultElement = operationStatusElement.Element(XName.Get("Result", "http://schemas.microsoft.com/windowsazure"));
                                            if (resultElement != null)
                                            {
                                                string resultInstance = resultElement.Value;
                                                operationStatusInstance.Result = resultInstance;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    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>
        /// The Create Cloud Service operation creates a Windows Azure cloud
        /// service in a Windows Azure subscription.
        /// </summary>
        /// <param name='parameters'>
        /// Required. Parameters used to specify how the Create procedure will
        /// function.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// The response body contains the status of the specified asynchronous
        /// operation, indicating whether it has succeeded, is inprogress, or
        /// has failed. Note that this status is distinct from the HTTP status
        /// code returned for the Get Operation Status operation itself.  If
        /// the asynchronous operation succeeded, the response body includes
        /// the HTTP status code for the successful request.  If the
        /// asynchronous operation failed, the response body includes the HTTP
        /// status code for the failed request, and also includes error
        /// information regarding the failure.
        /// </returns>
        public async Task <OperationStatusResponse> CreateAsync(CloudServiceCreateParameters parameters, CancellationToken cancellationToken)
        {
            StoreManagementClient client = this.Client;
            bool   shouldTrace           = TracingAdapter.IsEnabled;
            string invocationId          = null;

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

            cancellationToken.ThrowIfCancellationRequested();
            OperationStatusResponse response = await client.CloudServices.BeginCreatingAsync(parameters, cancellationToken).ConfigureAwait(false);

            if (response.Status == OperationStatus.Succeeded)
            {
                return(response);
            }
            cancellationToken.ThrowIfCancellationRequested();
            OperationStatusResponse result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false);

            int delayInSeconds = 30;

            if (client.LongRunningOperationInitialTimeout >= 0)
            {
                delayInSeconds = client.LongRunningOperationInitialTimeout;
            }
            while ((result.Status != OperationStatus.InProgress) == false)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false);

                cancellationToken.ThrowIfCancellationRequested();
                result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false);

                delayInSeconds = 30;
                if (client.LongRunningOperationRetryTimeout >= 0)
                {
                    delayInSeconds = client.LongRunningOperationRetryTimeout;
                }
            }

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

            if (result.Status != OperationStatus.Succeeded)
            {
                if (result.Error != null)
                {
                    CloudException ex = new CloudException(result.Error.Code + " : " + result.Error.Message);
                    ex.Error         = new CloudError();
                    ex.Error.Code    = result.Error.Code;
                    ex.Error.Message = result.Error.Message;
                    if (shouldTrace)
                    {
                        TracingAdapter.Error(invocationId, ex);
                    }
                    throw ex;
                }
                else
                {
                    CloudException ex = new CloudException("");
                    if (shouldTrace)
                    {
                        TracingAdapter.Error(invocationId, ex);
                    }
                    throw ex;
                }
            }

            return(result);
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Query aggregated Azure subscription consumption data for a date
        /// range.  (see
        /// https://msdn.microsoft.com/library/azure/1ea5b323-54bb-423d-916f-190de96c6a3c
        /// for more information)
        /// </summary>
        /// <param name='reportedStartTime'>
        /// Required. The start of the time range to retrieve data for.
        /// </param>
        /// <param name='reportedEndTime'>
        /// Required. The end of the time range to retrieve data for.
        /// </param>
        /// <param name='aggregationGranularity'>
        /// Required. Value is either daily (default) or hourly to tell the API
        /// how to return the results grouped by day or hour.
        /// </param>
        /// <param name='showDetails'>
        /// Required. When set to true (default), the aggregates are broken
        /// down into the instance metadata which is more granular.
        /// </param>
        /// <param name='continuationToken'>
        /// Optional. Retrieved from previous calls, this is the bookmark used
        /// for progress when the responses are paged.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// The Get UsageAggregates operation response.
        /// </returns>
        public async Task <UsageAggregationGetResponse> GetAsync(DateTime reportedStartTime, DateTime reportedEndTime, AggregationGranularity aggregationGranularity, bool showDetails, string continuationToken, 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>();
                tracingParameters.Add("reportedStartTime", reportedStartTime);
                tracingParameters.Add("reportedEndTime", reportedEndTime);
                tracingParameters.Add("aggregationGranularity", aggregationGranularity);
                tracingParameters.Add("showDetails", showDetails);
                tracingParameters.Add("continuationToken", continuationToken);
                TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters);
            }

            // Construct URL
            string url = "";

            url = url + "subscriptions/";
            if (this.Client.Credentials.SubscriptionId != null)
            {
                url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
            }
            url = url + "/providers/Microsoft.Commerce/UsageAggregates";
            List <string> queryParameters = new List <string>();

            queryParameters.Add("api-version=2015-06-01-preview");
            queryParameters.Add("reportedstartTime=" + Uri.EscapeDataString(reportedStartTime.ToString()));
            queryParameters.Add("reportedEndTime=" + Uri.EscapeDataString(reportedEndTime.ToString()) + ",");
            queryParameters.Add("showDetails=" + Uri.EscapeDataString(showDetails.ToString().ToLower()));
            queryParameters.Add("aggregationGranularity=" + Uri.EscapeDataString(UsageAggregationManagementClient.AggregationGranularityToString(aggregationGranularity)));
            if (continuationToken != null)
            {
                queryParameters.Add("continuationToken=" + Uri.EscapeDataString(continuationToken));
            }
            if (queryParameters.Count > 0)
            {
                url = url + "?" + string.Join("&", queryParameters);
            }
            string baseUrl = this.Client.BaseUri.AbsoluteUri;

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

            // Create HTTP transport objects
            HttpRequestMessage httpRequest = null;

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

                // Set Headers

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

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

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

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

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

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

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

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

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

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

                                        JToken meterIdValue = propertiesValue["meterId"];
                                        if (meterIdValue != null && meterIdValue.Type != JTokenType.Null)
                                        {
                                            Guid meterIdInstance = Guid.Parse(((string)meterIdValue));
                                            propertiesInstance.MeterId = meterIdInstance;
                                        }

                                        JToken usageStartTimeValue = propertiesValue["usageStartTime"];
                                        if (usageStartTimeValue != null && usageStartTimeValue.Type != JTokenType.Null)
                                        {
                                            DateTime usageStartTimeInstance = ((DateTime)usageStartTimeValue);
                                            propertiesInstance.UsageStartTime = usageStartTimeInstance.ToUniversalTime();
                                        }

                                        JToken usageEndTimeValue = propertiesValue["usageEndTime"];
                                        if (usageEndTimeValue != null && usageEndTimeValue.Type != JTokenType.Null)
                                        {
                                            DateTime usageEndTimeInstance = ((DateTime)usageEndTimeValue);
                                            propertiesInstance.UsageEndTime = usageEndTimeInstance.ToUniversalTime();
                                        }

                                        JToken quantityValue = propertiesValue["quantity"];
                                        if (quantityValue != null && quantityValue.Type != JTokenType.Null)
                                        {
                                            decimal quantityInstance = ((decimal)quantityValue);
                                            propertiesInstance.Quantity = quantityInstance;
                                        }

                                        JToken unitValue = propertiesValue["unit"];
                                        if (unitValue != null && unitValue.Type != JTokenType.Null)
                                        {
                                            string unitInstance = ((string)unitValue);
                                            propertiesInstance.Unit = unitInstance;
                                        }

                                        JToken meterNameValue = propertiesValue["meterName"];
                                        if (meterNameValue != null && meterNameValue.Type != JTokenType.Null)
                                        {
                                            string meterNameInstance = ((string)meterNameValue);
                                            propertiesInstance.MeterName = meterNameInstance;
                                        }

                                        JToken meterCategoryValue = propertiesValue["meterCategory"];
                                        if (meterCategoryValue != null && meterCategoryValue.Type != JTokenType.Null)
                                        {
                                            string meterCategoryInstance = ((string)meterCategoryValue);
                                            propertiesInstance.MeterCategory = meterCategoryInstance;
                                        }

                                        JToken meterSubCategoryValue = propertiesValue["meterSubCategory"];
                                        if (meterSubCategoryValue != null && meterSubCategoryValue.Type != JTokenType.Null)
                                        {
                                            string meterSubCategoryInstance = ((string)meterSubCategoryValue);
                                            propertiesInstance.MeterSubCategory = meterSubCategoryInstance;
                                        }

                                        JToken meterRegionValue = propertiesValue["meterRegion"];
                                        if (meterRegionValue != null && meterRegionValue.Type != JTokenType.Null)
                                        {
                                            string meterRegionInstance = ((string)meterRegionValue);
                                            propertiesInstance.MeterRegion = meterRegionInstance;
                                        }

                                        JToken infoFieldsValue = propertiesValue["infoFields"];
                                        if (infoFieldsValue != null && infoFieldsValue.Type != JTokenType.Null)
                                        {
                                            InfoField infoFieldsInstance = new InfoField();
                                            propertiesInstance.InfoFields = infoFieldsInstance;

                                            JToken projectValue = infoFieldsValue["project"];
                                            if (projectValue != null && projectValue.Type != JTokenType.Null)
                                            {
                                                string projectInstance = ((string)projectValue);
                                                infoFieldsInstance.Project = projectInstance;
                                            }
                                        }

                                        JToken instanceDataValue = propertiesValue["instanceData"];
                                        if (instanceDataValue != null && instanceDataValue.Type != JTokenType.Null)
                                        {
                                            string instanceDataInstance = ((string)instanceDataValue);
                                            propertiesInstance.InstanceData = instanceDataInstance;
                                        }
                                    }
                                }
                            }

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

                                if (!string.IsNullOrWhiteSpace(nextLinkInstance))
                                {
                                    string key           = "continuationToken=";
                                    int    startLocation = nextLinkInstance.IndexOf(key, StringComparison.OrdinalIgnoreCase);
                                    if (startLocation >= 0)
                                    {
                                        startLocation = startLocation + key.Length;
                                        int    length = nextLinkInstance.Length - startLocation;
                                        string token  = nextLinkInstance.Substring(startLocation, length);
                                        result.ContinuationToken = Uri.UnescapeDataString(token);
                                    }
                                }
                            }
                        }
                    }
                    result.StatusCode = statusCode;

                    if (shouldTrace)
                    {
                        TracingAdapter.Exit(invocationId, result);
                    }
                    return(result);
                }
                finally
                {
                    if (httpResponse != null)
                    {
                        httpResponse.Dispose();
                    }
                }
            }
            finally
            {
                if (httpRequest != null)
                {
                    httpRequest.Dispose();
                }
            }
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Checks whether a domain name in the cloudapp.net zone is available
        /// for use.
        /// </summary>
        /// <param name='location'>
        /// Required. The location of the domain name
        /// </param>
        /// <param name='domainNameLabel'>
        /// Required. The domain name to be verified. It must conform to the
        /// following regular expression: ^[a-z][a-z0-9-]{1,61}[a-z0-9]$.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// Response for CheckDnsNameAvailability Api servive call
        /// </returns>
        public async Task <DnsNameAvailabilityResponse> CheckDnsNameAvailabilityAsync(string location, string domainNameLabel, CancellationToken cancellationToken)
        {
            // Validate
            if (location == null)
            {
                throw new ArgumentNullException("location");
            }
            if (domainNameLabel == null)
            {
                throw new ArgumentNullException("domainNameLabel");
            }

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

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

            // Construct URL
            string url = "";

            url = url + "/subscriptions/";
            if (this.Credentials.SubscriptionId != null)
            {
                url = url + Uri.EscapeDataString(this.Credentials.SubscriptionId);
            }
            url = url + "/providers/";
            url = url + "Microsoft.Network";
            url = url + "/locations/";
            url = url + Uri.EscapeDataString(location);
            url = url + "/CheckDnsNameAvailability";
            List <string> queryParameters = new List <string>();

            queryParameters.Add("domainNameLabel=" + Uri.EscapeDataString(domainNameLabel));
            queryParameters.Add("api-version=2015-05-01-preview");
            if (queryParameters.Count > 0)
            {
                url = url + "?" + string.Join("&", queryParameters);
            }
            string baseUrl = this.BaseUri.AbsoluteUri;

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

            // Create HTTP transport objects
            HttpRequestMessage httpRequest = null;

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

                // Set Headers

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

                // Send Request
                HttpResponseMessage httpResponse = null;
                try
                {
                    if (shouldTrace)
                    {
                        TracingAdapter.SendRequest(invocationId, httpRequest);
                    }
                    cancellationToken.ThrowIfCancellationRequested();
                    httpResponse = await this.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
                    DnsNameAvailabilityResponse result = null;
                    // Deserialize Response
                    if (statusCode == HttpStatusCode.OK)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

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

                        if (responseDoc != null && responseDoc.Type != JTokenType.Null)
                        {
                            JToken availableValue = responseDoc["available"];
                            if (availableValue != null && availableValue.Type != JTokenType.Null)
                            {
                                bool availableInstance = ((bool)availableValue);
                                result.DnsNameAvailability = availableInstance;
                            }
                        }
                    }
                    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>
        ///
        /// </summary>
        /// <param name="account"></param>
        /// <param name="environment"></param>
        /// <param name="tenant"></param>
        /// <param name="password"></param>
        /// <param name="promptBehavior"></param>
        /// <param name="promptAction"></param>
        /// <param name="tokenCache"></param>
        /// <param name="resourceId"></param>
        /// <returns></returns>
        public IAccessToken Authenticate(
            IAzureAccount account,
            IAzureEnvironment environment,
            string tenant,
            SecureString password,
            string promptBehavior,
            Action <string> promptAction,
            IAzureTokenCache tokenCache,
            string resourceId = AzureEnvironment.Endpoint.ActiveDirectoryServiceEndpointResourceId)
        {
            IAccessToken token = null;

            PowerShellTokenCacheProvider tokenCacheProvider;

            if (!AzureSession.Instance.TryGetComponent(PowerShellTokenCacheProvider.PowerShellTokenCacheProviderKey, out tokenCacheProvider))
            {
                throw new NullReferenceException(Resources.AuthenticationClientFactoryNotRegistered);
            }

            Task <IAccessToken> authToken;
            var processAuthenticator = Builder.Authenticator;
            var retries       = 5;
            var authParamters = GetAuthenticationParameters(tokenCacheProvider, account, environment, tenant, password, promptBehavior, promptAction, tokenCache, resourceId);

            while (retries-- > 0)
            {
                try
                {
                    while (processAuthenticator != null && processAuthenticator.TryAuthenticate(authParamters, out authToken))
                    {
                        token = authToken?.GetAwaiter().GetResult();
                        if (token != null)
                        {
                            // token.UserId is null when getting tenant token in ADFS environment
                            account.Id = token.UserId ?? account.Id;
                            if (!string.IsNullOrEmpty(token.HomeAccountId))
                            {
                                account.SetProperty(AzureAccount.Property.HomeAccountId, token.HomeAccountId);
                            }
                            break;
                        }

                        processAuthenticator = processAuthenticator.Next;
                    }
                }
                catch (Exception e)
                {
                    if (!IsTransientException(e) || retries == 0)
                    {
                        var mfaException = AnalyzeMsalException(e, environment, tenant, resourceId);
                        if (mfaException != null)
                        {
                            throw mfaException;
                        }
                        else
                        {
                            throw;
                        }
                    }

                    TracingAdapter.Information(string.Format("[AuthenticationFactory] Exception caught when calling TryAuthenticate, retrying authentication - Exception message: '{0}'", e.Message));
                    continue;
                }

                break;
            }

            return(token);
        }
Ejemplo n.º 18
0
        /// <summary>
        /// The Get Operation Status operation returns the status of the
        /// specified operation. After calling an asynchronous operation, you
        /// can call Get Operation Status to determine whether the operation
        /// has succeeded, failed, or is still in progress.
        /// </summary>
        /// <param name='azureAsyncOperation'>
        /// Required. Location value returned by the Begin operation.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// The response body contains the status of the specified asynchronous
        /// operation, indicating whether it has succeeded, is inprogress, or
        /// has failed. Note that this status is distinct from the HTTP status
        /// code returned for the Get Operation Status operation itself. If
        /// the asynchronous operation succeeded, the response body includes
        /// the HTTP status code for the successful request. If the
        /// asynchronous operation failed, the response body includes the HTTP
        /// status code for the failed request and error information regarding
        /// the failure.
        /// </returns>
        public async Task <AzureAsyncOperationResponse> GetLongRunningOperationStatusAsync(string azureAsyncOperation, CancellationToken cancellationToken)
        {
            // Validate
            if (azureAsyncOperation == null)
            {
                throw new ArgumentNullException("azureAsyncOperation");
            }

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

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

            // Construct URL
            string url = "";

            url = url + azureAsyncOperation;
            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("x-ms-version", "2015-05-01-preview");

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

                // Send Request
                HttpResponseMessage httpResponse = null;
                try
                {
                    if (shouldTrace)
                    {
                        TracingAdapter.SendRequest(invocationId, httpRequest);
                    }
                    cancellationToken.ThrowIfCancellationRequested();
                    httpResponse = await this.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
                    AzureAsyncOperationResponse result = null;
                    // Deserialize Response
                    if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Accepted)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

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

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

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

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

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

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

                                JToken detailsArray = errorValue["details"];
                                if (detailsArray != null && detailsArray.Type != JTokenType.Null)
                                {
                                    foreach (JToken detailsValue in ((JArray)detailsArray))
                                    {
                                        ErrorDetails errorDetailsInstance = new ErrorDetails();
                                        errorInstance.Details.Add(errorDetailsInstance);

                                        JToken codeValue2 = detailsValue["code"];
                                        if (codeValue2 != null && codeValue2.Type != JTokenType.Null)
                                        {
                                            string codeInstance2 = ((string)codeValue2);
                                            errorDetailsInstance.Code = codeInstance2;
                                        }

                                        JToken targetValue2 = detailsValue["target"];
                                        if (targetValue2 != null && targetValue2.Type != JTokenType.Null)
                                        {
                                            string targetInstance2 = ((string)targetValue2);
                                            errorDetailsInstance.Target = targetInstance2;
                                        }

                                        JToken messageValue2 = detailsValue["message"];
                                        if (messageValue2 != null && messageValue2.Type != JTokenType.Null)
                                        {
                                            string messageInstance2 = ((string)messageValue2);
                                            errorDetailsInstance.Message = messageInstance2;
                                        }
                                    }
                                }

                                JToken innerErrorValue = errorValue["innerError"];
                                if (innerErrorValue != null && innerErrorValue.Type != JTokenType.Null)
                                {
                                    string innerErrorInstance = ((string)innerErrorValue);
                                    errorInstance.InnerError = innerErrorInstance;
                                }
                            }
                        }
                    }
                    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();
                }
            }
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Return test credentials and URI using AAD auth for an OrgID account.  Use this method with caution - it may take a dependency on ADAL.
        /// </summary>
        /// <returns>The test credentials, or null if the appropriate environment variable is not set.</returns>
        protected virtual TestEnvironment GetOrgIdTestEnvironment(string orgIdVariable)
        {
            TestEnvironment orgIdEnvironment = null;
            string          orgIdAuth        = GetOrgId(orgIdVariable);

            if (!string.IsNullOrEmpty(orgIdAuth))
            {
                string token = null;
                IDictionary <string, string> authSettings = ParseConnectionString(orgIdAuth);
                string subscription         = authSettings[SubscriptionIdKey];
                string authEndpoint         = authSettings.ContainsKey(AADAuthEndpoint) ? authSettings[AADAuthEndpoint] : AADAuthEndpointDefault;
                string tenant               = authSettings.ContainsKey(AADTenant) ? authSettings[AADTenant] : AADTenantDefault;
                string user                 = null;
                AuthenticationResult result = null;

                if (authSettings.ContainsKey(AADUserIdKey))
                {
                    user = authSettings[AADUserIdKey];
                }

                // Preserve/restore subscription ID
                if (HttpMockServer.Mode == HttpRecorderMode.Record)
                {
                    HttpMockServer.Variables[SubscriptionIdKey] = subscription;
                    if (authSettings.ContainsKey(AADUserIdKey) && authSettings.ContainsKey(AADPasswordKey))
                    {
                        string password = authSettings[AADPasswordKey];
                        TracingAdapter.Information("Using AAD auth with username and password combination");
                        token = TokenCloudCredentialsHelper.GetTokenFromBasicCredentials(user, password, authEndpoint, tenant);
                    }
                    else
                    {
                        TracingAdapter.Information("Using AAD auth with pop-up dialog");
                        string clientId = authSettings.ContainsKey(ClientID) ? authSettings[ClientID] : ClientIdDefault;
                        if (authSettings.ContainsKey(RawToken))
                        {
                            token = authSettings[RawToken];
                        }
                        else
                        {
                            result = TokenCloudCredentialsHelper.GetToken(authEndpoint, tenant, clientId);
                            token  = result.CreateAuthorizationHeader().Substring("Bearer ".Length);
                        }
                    }
                }

                if (HttpMockServer.Mode == HttpRecorderMode.Playback)
                {
                    // playback mode but no stored credentials in mocks
                    TracingAdapter.Information("Using dummy token for playback");
                    token = Guid.NewGuid().ToString();
                }

                orgIdEnvironment = new TestEnvironment
                {
                    Credentials          = token == null ? null : new TokenCloudCredentials(subscription, token),
                    UserName             = user,
                    AuthenticationResult = result
                };

                if (authSettings.ContainsKey(BaseUriKey))
                {
                    orgIdEnvironment.BaseUri = new Uri(authSettings[BaseUriKey]);
                }

                if (!string.IsNullOrEmpty(authEndpoint))
                {
                    orgIdEnvironment.ActiveDirectoryEndpoint = new Uri(authEndpoint);
                }

                orgIdEnvironment.SubscriptionId = subscription;
            }

            return(orgIdEnvironment);
        }
        /// <summary>
        /// Retrieve a list of Resource Groups
        /// </summary>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// The response model for the list resource group operation.
        /// </returns>
        public async Task <ResourceGroupListResponse> 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 + "/Subscriptions/";
            if (this.Client.Credentials.SubscriptionId != null)
            {
                url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
            }
            url = url + "/resourceGroups";
            List <string> queryParameters = new List <string>();

            queryParameters.Add("api-version=2015-01-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("x-ms-version", "2015-01-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
                    ResourceGroupListResponse result = null;
                    // Deserialize Response
                    if (statusCode == HttpStatusCode.OK)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

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

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

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

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

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

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

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

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

                                    JToken tagsSequenceElement = ((JToken)valueValue["tags"]);
                                    if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
                                    {
                                        foreach (JProperty property in tagsSequenceElement)
                                        {
                                            string tagsKey   = ((string)property.Name);
                                            string tagsValue = ((string)property.Value);
                                            resourceGroupInstance.Tags.Add(tagsKey, tagsValue);
                                        }
                                    }
                                }
                            }
                        }
                    }
                    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>
        /// List all API associated products.
        /// </summary>
        /// <param name='resourceGroupName'>
        /// Required. The name of the resource group.
        /// </param>
        /// <param name='serviceName'>
        /// Required. The name of the Api Management service.
        /// </param>
        /// <param name='aid'>
        /// Required. Identifier of the API.
        /// </param>
        /// <param name='query'>
        /// Optional.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// List Products operation response details.
        /// </returns>
        public async Task <ProductListResponse> ListAsync(string resourceGroupName, string serviceName, string aid, QueryParameters query, CancellationToken cancellationToken)
        {
            // Validate
            if (resourceGroupName == null)
            {
                throw new ArgumentNullException("resourceGroupName");
            }
            if (serviceName == null)
            {
                throw new ArgumentNullException("serviceName");
            }
            if (aid == null)
            {
                throw new ArgumentNullException("aid");
            }

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

            if (shouldTrace)
            {
                invocationId = TracingAdapter.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("resourceGroupName", resourceGroupName);
                tracingParameters.Add("serviceName", serviceName);
                tracingParameters.Add("aid", aid);
                tracingParameters.Add("query", query);
                TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters);
            }

            // Construct URL
            string url = "";

            url = url + "/subscriptions/";
            if (this.Client.Credentials.SubscriptionId != null)
            {
                url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
            }
            url = url + "/resourceGroups/";
            url = url + Uri.EscapeDataString(resourceGroupName);
            url = url + "/providers/";
            url = url + "Microsoft.ApiManagement";
            url = url + "/service/";
            url = url + Uri.EscapeDataString(serviceName);
            url = url + "/apis/";
            url = url + Uri.EscapeDataString(aid);
            url = url + "/products";
            List <string> queryParameters = new List <string>();

            queryParameters.Add("api-version=2016-07-07");
            List <string> odataFilter = new List <string>();

            if (query != null && query.Filter != null)
            {
                odataFilter.Add(Uri.EscapeDataString(query.Filter));
            }
            if (odataFilter.Count > 0)
            {
                queryParameters.Add("$filter=" + string.Join(null, odataFilter));
            }
            if (query != null && query.Top != null)
            {
                queryParameters.Add("$top=" + Uri.EscapeDataString(query.Top.Value.ToString()));
            }
            if (query != null && query.Skip != null)
            {
                queryParameters.Add("$skip=" + Uri.EscapeDataString(query.Skip.Value.ToString()));
            }
            if (queryParameters.Count > 0)
            {
                url = url + "?" + string.Join("&", queryParameters);
            }
            string baseUrl = this.Client.BaseUri.AbsoluteUri;

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

            // Create HTTP transport objects
            HttpRequestMessage httpRequest = null;

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

                // Set Headers

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

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

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

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

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

                        if (responseDoc != null && responseDoc.Type != JTokenType.Null)
                        {
                            ProductPaged resultInstance = new ProductPaged();
                            result.Result = resultInstance;

                            JToken valueArray = responseDoc["value"];
                            if (valueArray != null && valueArray.Type != JTokenType.Null)
                            {
                                foreach (JToken valueValue in ((JArray)valueArray))
                                {
                                    ProductContract productContractInstance = new ProductContract();
                                    resultInstance.Values.Add(productContractInstance);

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

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

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

                                    JToken termsValue = valueValue["terms"];
                                    if (termsValue != null && termsValue.Type != JTokenType.Null)
                                    {
                                        string termsInstance = ((string)termsValue);
                                        productContractInstance.Terms = termsInstance;
                                    }

                                    JToken subscriptionRequiredValue = valueValue["subscriptionRequired"];
                                    if (subscriptionRequiredValue != null && subscriptionRequiredValue.Type != JTokenType.Null)
                                    {
                                        bool subscriptionRequiredInstance = ((bool)subscriptionRequiredValue);
                                        productContractInstance.SubscriptionRequired = subscriptionRequiredInstance;
                                    }

                                    JToken approvalRequiredValue = valueValue["approvalRequired"];
                                    if (approvalRequiredValue != null && approvalRequiredValue.Type != JTokenType.Null)
                                    {
                                        bool approvalRequiredInstance = ((bool)approvalRequiredValue);
                                        productContractInstance.ApprovalRequired = approvalRequiredInstance;
                                    }

                                    JToken subscriptionsLimitValue = valueValue["subscriptionsLimit"];
                                    if (subscriptionsLimitValue != null && subscriptionsLimitValue.Type != JTokenType.Null)
                                    {
                                        int subscriptionsLimitInstance = ((int)subscriptionsLimitValue);
                                        productContractInstance.SubscriptionsLimit = subscriptionsLimitInstance;
                                    }

                                    JToken stateValue = valueValue["state"];
                                    if (stateValue != null && stateValue.Type != JTokenType.Null)
                                    {
                                        ProductStateContract stateInstance = ((ProductStateContract)Enum.Parse(typeof(ProductStateContract), ((string)stateValue), true));
                                        productContractInstance.State = stateInstance;
                                    }
                                }
                            }

                            JToken countValue = responseDoc["count"];
                            if (countValue != null && countValue.Type != JTokenType.Null)
                            {
                                long countInstance = ((long)countValue);
                                resultInstance.TotalCount = countInstance;
                            }

                            JToken nextLinkValue = responseDoc["nextLink"];
                            if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null)
                            {
                                string nextLinkInstance = ((string)nextLinkValue);
                                resultInstance.NextLink = nextLinkInstance;
                            }
                        }
                    }
                    result.StatusCode = statusCode;
                    if (httpResponse.Headers.Contains("x-ms-request-id"))
                    {
                        result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
                    }

                    if (shouldTrace)
                    {
                        TracingAdapter.Exit(invocationId, result);
                    }
                    return(result);
                }
                finally
                {
                    if (httpResponse != null)
                    {
                        httpResponse.Dispose();
                    }
                }
            }
            finally
            {
                if (httpRequest != null)
                {
                    httpRequest.Dispose();
                }
            }
        }
        /// <summary>
        /// Get the vault extended info.
        /// </summary>
        /// <param name='resourceGroupName'>
        /// Required. The name of the resource group containing the job
        /// collection.
        /// </param>
        /// <param name='resourceName'>
        /// Required. The name of the resource.
        /// </param>
        /// <param name='extendedInfoArgs'>
        /// Optional. Update resource exnteded info input parameters.
        /// </param>
        /// <param name='customRequestHeaders'>
        /// Optional. Request header parameters.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// The response model for the resource extended information object
        /// </returns>
        public async Task <ResourceExtendedInformationResponse> UpdateExtendedInfoAsync(string resourceGroupName, string resourceName, ResourceExtendedInformationArgs extendedInfoArgs, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken)
        {
            // Validate
            if (resourceGroupName == null)
            {
                throw new ArgumentNullException("resourceGroupName");
            }
            if (resourceName == null)
            {
                throw new ArgumentNullException("resourceName");
            }
            if (extendedInfoArgs != null)
            {
                if (extendedInfoArgs.ContractVersion == null)
                {
                    throw new ArgumentNullException("extendedInfoArgs.ContractVersion");
                }
                if (extendedInfoArgs.ExtendedInfo == null)
                {
                    throw new ArgumentNullException("extendedInfoArgs.ExtendedInfo");
                }
                if (extendedInfoArgs.ExtendedInfoETag == null)
                {
                    throw new ArgumentNullException("extendedInfoArgs.ExtendedInfoETag");
                }
            }

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

            if (shouldTrace)
            {
                invocationId = TracingAdapter.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("resourceGroupName", resourceGroupName);
                tracingParameters.Add("resourceName", resourceName);
                tracingParameters.Add("extendedInfoArgs", extendedInfoArgs);
                tracingParameters.Add("customRequestHeaders", customRequestHeaders);
                TracingAdapter.Enter(invocationId, this, "UpdateExtendedInfoAsync", tracingParameters);
            }

            // Construct URL
            string url = "";

            url = url + "/Subscriptions/";
            if (this.Client.Credentials.SubscriptionId != null)
            {
                url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
            }
            url = url + "/resourceGroups/";
            url = url + Uri.EscapeDataString(resourceGroupName);
            url = url + "/providers/";
            url = url + Uri.EscapeDataString(this.Client.ResourceNamespace);
            url = url + "/";
            url = url + "SiteRecoveryVault";
            url = url + "/";
            url = url + Uri.EscapeDataString(resourceName);
            url = url + "/ExtendedInfo";
            List <string> queryParameters = new List <string>();

            queryParameters.Add("api-version=2015-03-15");
            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("x-ms-client-request-id", customRequestHeaders.ClientRequestId);
                httpRequest.Headers.Add("x-ms-version", "2015-01-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
                    ResourceExtendedInformationResponse result = null;
                    // Deserialize Response
                    if (statusCode == HttpStatusCode.OK)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

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

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

                            JToken resourceGroupNameValue = responseDoc["ResourceGroupName"];
                            if (resourceGroupNameValue != null && resourceGroupNameValue.Type != JTokenType.Null)
                            {
                                string resourceGroupNameInstance = ((string)resourceGroupNameValue);
                                extendedInformationInstance.ResourceGroupName = resourceGroupNameInstance;
                            }

                            JToken extendedInfoValue = responseDoc["ExtendedInfo"];
                            if (extendedInfoValue != null && extendedInfoValue.Type != JTokenType.Null)
                            {
                                string extendedInfoInstance = ((string)extendedInfoValue);
                                extendedInformationInstance.ExtendedInfo = extendedInfoInstance;
                            }

                            JToken extendedInfoETagValue = responseDoc["ExtendedInfoETag"];
                            if (extendedInfoETagValue != null && extendedInfoETagValue.Type != JTokenType.Null)
                            {
                                string extendedInfoETagInstance = ((string)extendedInfoETagValue);
                                extendedInformationInstance.ExtendedInfoETag = extendedInfoETagInstance;
                            }

                            JToken resourceIdValue = responseDoc["ResourceId"];
                            if (resourceIdValue != null && resourceIdValue.Type != JTokenType.Null)
                            {
                                long resourceIdInstance = ((long)resourceIdValue);
                                extendedInformationInstance.ResourceId = resourceIdInstance;
                            }

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

                            JToken resourceTypeValue = responseDoc["ResourceType"];
                            if (resourceTypeValue != null && resourceTypeValue.Type != JTokenType.Null)
                            {
                                string resourceTypeInstance = ((string)resourceTypeValue);
                                extendedInformationInstance.ResourceType = resourceTypeInstance;
                            }

                            JToken subscriptionIdValue = responseDoc["SubscriptionId"];
                            if (subscriptionIdValue != null && subscriptionIdValue.Type != JTokenType.Null)
                            {
                                Guid subscriptionIdInstance = Guid.Parse(((string)subscriptionIdValue));
                                extendedInformationInstance.SubscriptionId = subscriptionIdInstance;
                            }
                        }
                    }
                    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>
        /// The Get Operation Status operation returns the status of
        /// thespecified operation. After calling an asynchronous operation,
        /// you can call Get Operation Status to determine whether the
        /// operation has succeeded, failed, or is still in progress.  (see
        /// http://msdn.microsoft.com/en-us/library/windowsazure/ee460783.aspx
        /// for more information)
        /// </summary>
        /// <param name='requestId'>
        /// Required. The request ID for the request you wish to track. The
        /// request ID is returned in the x-ms-request-id response header for
        /// every request.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// The response body contains the status of the specified asynchronous
        /// operation, indicating whether it has succeeded, is inprogress, or
        /// has failed. Note that this status is distinct from the HTTP status
        /// code returned for the Get Operation Status operation itself.  If
        /// the asynchronous operation succeeded, the response body includes
        /// the HTTP status code for the successful request.  If the
        /// asynchronous operation failed, the response body includes the HTTP
        /// status code for the failed request, and also includes error
        /// information regarding the failure.
        /// </returns>
        public async Task <LongRunningOperationStatusResponse> GetOperationStatusAsync(string requestId, CancellationToken cancellationToken)
        {
            // Validate
            if (requestId == null)
            {
                throw new ArgumentNullException("requestId");
            }

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

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

            // Construct URL
            string url = "";

            url = url + "/";
            if (this.Credentials.SubscriptionId != null)
            {
                url = url + Uri.EscapeDataString(this.Credentials.SubscriptionId);
            }
            url = url + "/operations/";
            url = url + Uri.EscapeDataString(requestId);
            string baseUrl = this.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("x-ms-version", "2013-06-01");

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

                // Send Request
                HttpResponseMessage httpResponse = null;
                try
                {
                    if (shouldTrace)
                    {
                        TracingAdapter.SendRequest(invocationId, httpRequest);
                    }
                    cancellationToken.ThrowIfCancellationRequested();
                    httpResponse = await this.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
                    LongRunningOperationStatusResponse result = null;
                    // Deserialize Response
                    if (statusCode == HttpStatusCode.OK)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                        result = new LongRunningOperationStatusResponse();
                        XDocument responseDoc = XDocument.Parse(responseContent);

                        XElement operationElement = responseDoc.Element(XName.Get("Operation", "http://schemas.microsoft.com/windowsazure"));
                        if (operationElement != null)
                        {
                            XElement idElement = operationElement.Element(XName.Get("ID", "http://schemas.microsoft.com/windowsazure"));
                            if (idElement != null)
                            {
                                string idInstance = idElement.Value;
                                result.Id = idInstance;
                            }

                            XElement statusElement = operationElement.Element(XName.Get("Status", "http://schemas.microsoft.com/windowsazure"));
                            if (statusElement != null)
                            {
                                OperationStatus statusInstance = ((OperationStatus)Enum.Parse(typeof(OperationStatus), statusElement.Value, true));
                                result.Status = statusInstance;
                            }

                            XElement httpStatusCodeElement = operationElement.Element(XName.Get("HttpStatusCode", "http://schemas.microsoft.com/windowsazure"));
                            if (httpStatusCodeElement != null)
                            {
                                HttpStatusCode httpStatusCodeInstance = ((HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), httpStatusCodeElement.Value, true));
                                result.HttpStatusCode = httpStatusCodeInstance;
                            }

                            XElement errorElement = operationElement.Element(XName.Get("Error", "http://schemas.microsoft.com/windowsazure"));
                            if (errorElement != null)
                            {
                                LongRunningOperationStatusResponse.ErrorDetails errorInstance = new LongRunningOperationStatusResponse.ErrorDetails();
                                result.Error = errorInstance;

                                XElement codeElement = errorElement.Element(XName.Get("Code", "http://schemas.microsoft.com/windowsazure"));
                                if (codeElement != null)
                                {
                                    string codeInstance = codeElement.Value;
                                    errorInstance.Code = codeInstance;
                                }

                                XElement messageElement = errorElement.Element(XName.Get("Message", "http://schemas.microsoft.com/windowsazure"));
                                if (messageElement != null)
                                {
                                    string messageInstance = messageElement.Value;
                                    errorInstance.Message = messageInstance;
                                }
                            }
                        }
                    }
                    result.StatusCode = statusCode;
                    if (httpResponse.Headers.Contains("x-ms-request-id"))
                    {
                        result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
                    }

                    if (shouldTrace)
                    {
                        TracingAdapter.Exit(invocationId, result);
                    }
                    return(result);
                }
                finally
                {
                    if (httpResponse != null)
                    {
                        httpResponse.Dispose();
                    }
                }
            }
            finally
            {
                if (httpRequest != null)
                {
                    httpRequest.Dispose();
                }
            }
        }
        /// <summary>
        /// Get the vault extended info.
        /// </summary>
        /// <param name='resourceGroupName'>
        /// Required. The name of the resource group containing the job
        /// collection.
        /// </param>
        /// <param name='resourceName'>
        /// Required. The name of the resource.
        /// </param>
        /// <param name='parameters'>
        /// Required. Upload Vault Certificate input parameters.
        /// </param>
        /// <param name='certFriendlyName'>
        /// Required. Certificate friendly name
        /// </param>
        /// <param name='customRequestHeaders'>
        /// Optional. Request header parameters.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// The response model for the upload certificate response
        /// </returns>
        public async Task <UploadCertificateResponse> UploadCertificateAsync(string resourceGroupName, string resourceName, CertificateArgs parameters, string certFriendlyName, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken)
        {
            // Validate
            if (resourceGroupName == null)
            {
                throw new ArgumentNullException("resourceGroupName");
            }
            if (resourceName == null)
            {
                throw new ArgumentNullException("resourceName");
            }
            if (parameters == null)
            {
                throw new ArgumentNullException("parameters");
            }
            if (parameters.Properties == null)
            {
                throw new ArgumentNullException("parameters.Properties");
            }
            if (certFriendlyName == null)
            {
                throw new ArgumentNullException("certFriendlyName");
            }

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

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

            // Construct URL
            string url = "";

            url = url + "/Subscriptions/";
            if (this.Client.Credentials.SubscriptionId != null)
            {
                url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
            }
            url = url + "/resourceGroups/";
            url = url + Uri.EscapeDataString(resourceGroupName);
            url = url + "/providers/";
            url = url + Uri.EscapeDataString(this.Client.ResourceNamespace);
            url = url + "/";
            url = url + "SiteRecoveryVault";
            url = url + "/";
            url = url + Uri.EscapeDataString(resourceName);
            url = url + "/certificates/";
            url = url + Uri.EscapeDataString(certFriendlyName);
            List <string> queryParameters = new List <string>();

            queryParameters.Add("api-version=2015-03-15");
            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-client-request-id", customRequestHeaders.ClientRequestId);

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

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

                JObject parametersValue = new JObject();
                requestDoc = parametersValue;

                if (parameters.Properties != null)
                {
                    if (parameters.Properties is ILazyCollection == false || ((ILazyCollection)parameters.Properties).IsInitialized)
                    {
                        JObject propertiesDictionary = new JObject();
                        foreach (KeyValuePair <string, string> pair in parameters.Properties)
                        {
                            string propertiesKey   = pair.Key;
                            string propertiesValue = pair.Value;
                            propertiesDictionary[propertiesKey] = propertiesValue;
                        }
                        parametersValue["properties"] = propertiesDictionary;
                    }
                }

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

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

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

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

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

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

                                JToken friendlyNameValue = propertiesValue2["friendlyName"];
                                if (friendlyNameValue != null && friendlyNameValue.Type != JTokenType.Null)
                                {
                                    string friendlyNameInstance = ((string)friendlyNameValue);
                                    propertiesInstance.FriendlyName = friendlyNameInstance;
                                }

                                JToken globalAcsHostNameValue = propertiesValue2["globalAcsHostName"];
                                if (globalAcsHostNameValue != null && globalAcsHostNameValue.Type != JTokenType.Null)
                                {
                                    string globalAcsHostNameInstance = ((string)globalAcsHostNameValue);
                                    propertiesInstance.GlobalAcsHostName = globalAcsHostNameInstance;
                                }

                                JToken globalAcsNamespaceValue = propertiesValue2["globalAcsNamespace"];
                                if (globalAcsNamespaceValue != null && globalAcsNamespaceValue.Type != JTokenType.Null)
                                {
                                    string globalAcsNamespaceInstance = ((string)globalAcsNamespaceValue);
                                    propertiesInstance.GlobalAcsNamespace = globalAcsNamespaceInstance;
                                }

                                JToken globalAcsRPRealmValue = propertiesValue2["globalAcsRPRealm"];
                                if (globalAcsRPRealmValue != null && globalAcsRPRealmValue.Type != JTokenType.Null)
                                {
                                    string globalAcsRPRealmInstance = ((string)globalAcsRPRealmValue);
                                    propertiesInstance.GlobalAcsRPRealm = globalAcsRPRealmInstance;
                                }

                                JToken resourceIdValue = propertiesValue2["resourceId"];
                                if (resourceIdValue != null && resourceIdValue.Type != JTokenType.Null)
                                {
                                    long resourceIdInstance = ((long)resourceIdValue);
                                    propertiesInstance.ResourceId = resourceIdInstance;
                                }
                            }
                        }
                    }
                    result.StatusCode = statusCode;

                    if (shouldTrace)
                    {
                        TracingAdapter.Exit(invocationId, result);
                    }
                    return(result);
                }
                finally
                {
                    if (httpResponse != null)
                    {
                        httpResponse.Dispose();
                    }
                }
            }
            finally
            {
                if (httpRequest != null)
                {
                    httpRequest.Dispose();
                }
            }
        }
        /// <summary>
        /// Gets details about particular subscription.
        /// </summary>
        /// <param name='subscriptionId'>
        /// Required. Id of the subscription.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// Subscription detailed information.
        /// </returns>
        public async Task <GetSubscriptionResult> GetAsync(string subscriptionId, CancellationToken cancellationToken)
        {
            // Validate
            if (subscriptionId == null)
            {
                throw new ArgumentNullException("subscriptionId");
            }

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

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

            // Construct URL
            string url = "";

            url = url + "/subscriptions/";
            url = url + Uri.EscapeDataString(subscriptionId);
            List <string> queryParameters = new List <string>();

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

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

            // Create HTTP transport objects
            HttpRequestMessage httpRequest = null;

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

                // Set Headers

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

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

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

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

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

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

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

                            JToken subscriptionIdValue = responseDoc["subscriptionId"];
                            if (subscriptionIdValue != null && subscriptionIdValue.Type != JTokenType.Null)
                            {
                                string subscriptionIdInstance = ((string)subscriptionIdValue);
                                subscriptionInstance.SubscriptionId = subscriptionIdInstance;
                            }

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

                            JToken stateValue = responseDoc["state"];
                            if (stateValue != null && stateValue.Type != JTokenType.Null)
                            {
                                string stateInstance = ((string)stateValue);
                                subscriptionInstance.State = stateInstance;
                            }

                            JToken subscriptionPoliciesValue = responseDoc["subscriptionPolicies"];
                            if (subscriptionPoliciesValue != null && subscriptionPoliciesValue.Type != JTokenType.Null)
                            {
                                SubscriptionPolicies subscriptionPoliciesInstance = new SubscriptionPolicies();
                                subscriptionInstance.SubscriptionPolicies = subscriptionPoliciesInstance;

                                JToken locationPlacementIdValue = subscriptionPoliciesValue["locationPlacementId"];
                                if (locationPlacementIdValue != null && locationPlacementIdValue.Type != JTokenType.Null)
                                {
                                    string locationPlacementIdInstance = ((string)locationPlacementIdValue);
                                    subscriptionPoliciesInstance.LocationPlacementId = locationPlacementIdInstance;
                                }

                                JToken quotaIdValue = subscriptionPoliciesValue["quotaId"];
                                if (quotaIdValue != null && quotaIdValue.Type != JTokenType.Null)
                                {
                                    string quotaIdInstance = ((string)quotaIdValue);
                                    subscriptionPoliciesInstance.QuotaId = quotaIdInstance;
                                }
                            }
                        }
                    }
                    result.StatusCode = statusCode;
                    if (httpResponse.Headers.Contains("x-ms-request-id"))
                    {
                        result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
                    }

                    if (shouldTrace)
                    {
                        TracingAdapter.Exit(invocationId, result);
                    }
                    return(result);
                }
                finally
                {
                    if (httpResponse != null)
                    {
                        httpResponse.Dispose();
                    }
                }
            }
            finally
            {
                if (httpRequest != null)
                {
                    httpRequest.Dispose();
                }
            }
        }
        /// <summary>
        /// Get the vault extended info.
        /// </summary>
        /// <param name='resourceGroupName'>
        /// Required. The name of the resource group containing the job
        /// collection.
        /// </param>
        /// <param name='resourceName'>
        /// Required. The name of the resource.
        /// </param>
        /// <param name='extendedInfoArgs'>
        /// Required. Create resource exnteded info input parameters.
        /// </param>
        /// <param name='customRequestHeaders'>
        /// Optional. Request header parameters.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// A standard service response including an HTTP status code and
        /// request ID.
        /// </returns>
        public async Task <AzureOperationResponse> CreateExtendedInfoAsync(string resourceGroupName, string resourceName, ResourceExtendedInformationArgs extendedInfoArgs, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken)
        {
            // Validate
            if (resourceGroupName == null)
            {
                throw new ArgumentNullException("resourceGroupName");
            }
            if (resourceName == null)
            {
                throw new ArgumentNullException("resourceName");
            }
            if (extendedInfoArgs == null)
            {
                throw new ArgumentNullException("extendedInfoArgs");
            }
            if (extendedInfoArgs.ContractVersion == null)
            {
                throw new ArgumentNullException("extendedInfoArgs.ContractVersion");
            }
            if (extendedInfoArgs.ExtendedInfo == null)
            {
                throw new ArgumentNullException("extendedInfoArgs.ExtendedInfo");
            }
            if (extendedInfoArgs.ExtendedInfoETag == null)
            {
                throw new ArgumentNullException("extendedInfoArgs.ExtendedInfoETag");
            }

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

            if (shouldTrace)
            {
                invocationId = TracingAdapter.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("resourceGroupName", resourceGroupName);
                tracingParameters.Add("resourceName", resourceName);
                tracingParameters.Add("extendedInfoArgs", extendedInfoArgs);
                tracingParameters.Add("customRequestHeaders", customRequestHeaders);
                TracingAdapter.Enter(invocationId, this, "CreateExtendedInfoAsync", tracingParameters);
            }

            // Construct URL
            string url = "";

            url = url + "/Subscriptions/";
            if (this.Client.Credentials.SubscriptionId != null)
            {
                url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
            }
            url = url + "/resourceGroups/";
            url = url + Uri.EscapeDataString(resourceGroupName);
            url = url + "/providers/";
            url = url + Uri.EscapeDataString(this.Client.ResourceNamespace);
            url = url + "/";
            url = url + "SiteRecoveryVault";
            url = url + "/";
            url = url + Uri.EscapeDataString(resourceName);
            url = url + "/ExtendedInfo";
            List <string> queryParameters = new List <string>();

            queryParameters.Add("api-version=2015-03-15");
            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-client-request-id", customRequestHeaders.ClientRequestId);
                httpRequest.Headers.Add("x-ms-version", "2015-01-01");

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

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

                JObject resourceExtendedInformationArgsValue = new JObject();
                requestDoc = resourceExtendedInformationArgsValue;

                resourceExtendedInformationArgsValue["ContractVersion"] = extendedInfoArgs.ContractVersion;

                resourceExtendedInformationArgsValue["ExtendedInfo"] = extendedInfoArgs.ExtendedInfo;

                resourceExtendedInformationArgsValue["ExtendedInfoETag"] = extendedInfoArgs.ExtendedInfoETag;

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

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

                    if (shouldTrace)
                    {
                        TracingAdapter.Exit(invocationId, result);
                    }
                    return(result);
                }
                finally
                {
                    if (httpResponse != null)
                    {
                        httpResponse.Dispose();
                    }
                }
            }
            finally
            {
                if (httpRequest != null)
                {
                    httpRequest.Dispose();
                }
            }
        }
        public ServiceClientCredentials GetServiceClientCredentials(AzureContext context, AzureEnvironment.Endpoint targetEndpoint)
        {
            if (context.Account == null)
            {
                throw new ArgumentException(Resources.ArmAccountNotFound);
            }

            if (context.Account.Type == AzureAccount.AccountType.Certificate)
            {
                throw new NotSupportedException(AzureAccount.AccountType.Certificate.ToString());
            }

            if (context.Account.Type == AzureAccount.AccountType.AccessToken)
            {
                return(new TokenCredentials(context.Account.GetProperty(AzureAccount.Property.AccessToken)));
            }

            string tenant = null;

            if (context.Subscription != null && context.Account != null)
            {
                tenant = context.Subscription.GetPropertyAsArray(AzureSubscription.Property.Tenants)
                         .Intersect(context.Account.GetPropertyAsArray(AzureAccount.Property.Tenants))
                         .FirstOrDefault();
            }

            if (tenant == null && context.Tenant != null && context.Tenant.Id != Guid.Empty)
            {
                tenant = context.Tenant.Id.ToString();
            }

            if (tenant == null)
            {
                throw new ArgumentException(Resources.NoTenantInContext);
            }

            try
            {
                TracingAdapter.Information(Resources.UPNAuthenticationTrace,
                                           context.Account.Id, context.Environment.Name, tenant);

                // TODO: When we will refactor the code, need to add tracing

                /*TracingAdapter.Information(Resources.UPNAuthenticationTokenTrace,
                 *  token.LoginType, token.TenantId, token.UserId);*/

                var env = new ActiveDirectoryServiceSettings
                {
                    AuthenticationEndpoint = context.Environment.GetEndpointAsUri(AzureEnvironment.Endpoint.ActiveDirectory),
                    TokenAudience          = context.Environment.GetEndpointAsUri(context.Environment.GetTokenAudience(targetEndpoint)),
                    ValidateAuthority      = !context.Environment.OnPremise
                };

                var tokenCache = AzureSession.TokenCache;

                if (context.TokenCache != null && context.TokenCache.Length > 0)
                {
                    tokenCache = new TokenCache(context.TokenCache);
                }

                ServiceClientCredentials result = null;

                if (context.Account.Type == AzureAccount.AccountType.User)
                {
                    result = Rest.Azure.Authentication.UserTokenProvider.CreateCredentialsFromCache(
                        AdalConfiguration.PowerShellClientId,
                        tenant,
                        context.Account.Id,
                        env,
                        tokenCache).ConfigureAwait(false).GetAwaiter().GetResult();
                }
                else if (context.Account.Type == AzureAccount.AccountType.ServicePrincipal)
                {
                    if (context.Account.IsPropertySet(AzureAccount.Property.CertificateThumbprint))
                    {
                        result = ApplicationTokenProvider.LoginSilentAsync(
                            tenant,
                            context.Account.Id,
                            new CertificateApplicationCredentialProvider(
                                context.Account.GetProperty(AzureAccount.Property.CertificateThumbprint)),
                            env,
                            tokenCache).ConfigureAwait(false).GetAwaiter().GetResult();
                    }
                    else
                    {
                        result = ApplicationTokenProvider.LoginSilentAsync(
                            tenant,
                            context.Account.Id,
                            new KeyStoreApplicationCredentialProvider(tenant),
                            env,
                            tokenCache).ConfigureAwait(false).GetAwaiter().GetResult();
                    }
                }
                else
                {
                    throw new NotSupportedException(context.Account.Type.ToString());
                }

                if (context.TokenCache != null && context.TokenCache.Length > 0)
                {
                    context.TokenCache = tokenCache.Serialize();
                }

                return(result);
            }
            catch (Exception ex)
            {
                TracingAdapter.Information(Resources.AdalAuthException, ex.Message);
                throw new ArgumentException(Resources.InvalidArmContext, ex);
            }
        }
Ejemplo n.º 28
0
        /// <summary>
        /// The List Metric operation lists the metric value sets for the
        /// resource metrics.
        /// </summary>
        /// <param name='resourceUri'>
        /// Required. The resource identifier of the target resource to get
        /// metrics for.
        /// </param>
        /// <param name='filterString'>
        /// Optional. An OData $filter expression that supports querying by the
        /// name, startTime, endTime and timeGrain of the metric value sets.
        /// For example, "(name.value eq 'Percentage CPU') and startTime eq
        /// 2014-07-02T01:00Z and endTime eq 2014-08-21T01:00:00Z and
        /// timeGrain eq duration'PT1H'". In the expression, startTime,
        /// endTime and timeGrain are required. Name is optional.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// The List Metric values operation response.
        /// </returns>
        public async Task <MetricListResponse> GetMetricsAsync(string resourceUri, string filterString, CancellationToken cancellationToken)
        {
            // Validate
            if (resourceUri == null)
            {
                throw new ArgumentNullException("resourceUri");
            }

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

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

            // Construct URL
            string url = "/" + Uri.EscapeDataString(resourceUri) + "/metrics?";

            url = url + "api-version=2014-04-01";
            if (filterString != null)
            {
                url = url + "&$filter=" + Uri.EscapeDataString(filterString);
            }
            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");
                httpRequest.Headers.Add("x-ms-version", "2014-04-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
                    MetricListResponse result = null;
                    // Deserialize Response
                    if (statusCode == HttpStatusCode.OK)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

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

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

                            JToken valueArray = responseDoc["value"];
                            if (valueArray != null && valueArray.Type != JTokenType.Null)
                            {
                                foreach (JToken valueValue in ((JArray)valueArray))
                                {
                                    Metric metricInstance = new Metric();
                                    metricCollectionInstance.Value.Add(metricInstance);

                                    JToken nameValue = valueValue["name"];
                                    if (nameValue != null && nameValue.Type != JTokenType.Null)
                                    {
                                        LocalizableString nameInstance = new LocalizableString();
                                        metricInstance.Name = nameInstance;

                                        JToken valueValue2 = nameValue["value"];
                                        if (valueValue2 != null && valueValue2.Type != JTokenType.Null)
                                        {
                                            string valueInstance = ((string)valueValue2);
                                            nameInstance.Value = valueInstance;
                                        }

                                        JToken localizedValueValue = nameValue["localizedValue"];
                                        if (localizedValueValue != null && localizedValueValue.Type != JTokenType.Null)
                                        {
                                            string localizedValueInstance = ((string)localizedValueValue);
                                            nameInstance.LocalizedValue = localizedValueInstance;
                                        }
                                    }

                                    JToken unitValue = valueValue["unit"];
                                    if (unitValue != null && unitValue.Type != JTokenType.Null)
                                    {
                                        Unit unitInstance = ((Unit)Enum.Parse(typeof(Unit), ((string)unitValue), true));
                                        metricInstance.Unit = unitInstance;
                                    }

                                    JToken timeGrainValue = valueValue["timeGrain"];
                                    if (timeGrainValue != null && timeGrainValue.Type != JTokenType.Null)
                                    {
                                        TimeSpan timeGrainInstance = XmlConvert.ToTimeSpan(((string)timeGrainValue));
                                        metricInstance.TimeGrain = timeGrainInstance;
                                    }

                                    JToken startTimeValue = valueValue["startTime"];
                                    if (startTimeValue != null && startTimeValue.Type != JTokenType.Null)
                                    {
                                        DateTime startTimeInstance = ((DateTime)startTimeValue);
                                        metricInstance.StartTime = startTimeInstance;
                                    }

                                    JToken endTimeValue = valueValue["endTime"];
                                    if (endTimeValue != null && endTimeValue.Type != JTokenType.Null)
                                    {
                                        DateTime endTimeInstance = ((DateTime)endTimeValue);
                                        metricInstance.EndTime = endTimeInstance;
                                    }

                                    JToken metricValuesArray = valueValue["metricValues"];
                                    if (metricValuesArray != null && metricValuesArray.Type != JTokenType.Null)
                                    {
                                        foreach (JToken metricValuesValue in ((JArray)metricValuesArray))
                                        {
                                            MetricValue metricValueInstance = new MetricValue();
                                            metricInstance.MetricValues.Add(metricValueInstance);

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

                                            JToken averageValue = metricValuesValue["average"];
                                            if (averageValue != null && averageValue.Type != JTokenType.Null)
                                            {
                                                double averageInstance = ((double)averageValue);
                                                metricValueInstance.Average = averageInstance;
                                            }

                                            JToken minimumValue = metricValuesValue["minimum"];
                                            if (minimumValue != null && minimumValue.Type != JTokenType.Null)
                                            {
                                                double minimumInstance = ((double)minimumValue);
                                                metricValueInstance.Minimum = minimumInstance;
                                            }

                                            JToken maximumValue = metricValuesValue["maximum"];
                                            if (maximumValue != null && maximumValue.Type != JTokenType.Null)
                                            {
                                                double maximumInstance = ((double)maximumValue);
                                                metricValueInstance.Maximum = maximumInstance;
                                            }

                                            JToken totalValue = metricValuesValue["total"];
                                            if (totalValue != null && totalValue.Type != JTokenType.Null)
                                            {
                                                double totalInstance = ((double)totalValue);
                                                metricValueInstance.Total = totalInstance;
                                            }

                                            JToken countValue = metricValuesValue["count"];
                                            if (countValue != null && countValue.Type != JTokenType.Null)
                                            {
                                                long countInstance = ((long)countValue);
                                                metricValueInstance.Count = countInstance;
                                            }

                                            JToken lastValue = metricValuesValue["last"];
                                            if (lastValue != null && lastValue.Type != JTokenType.Null)
                                            {
                                                double lastInstance = ((double)lastValue);
                                                metricValueInstance.Last = lastInstance;
                                            }

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

                                    JToken resourceIdValue = valueValue["resourceId"];
                                    if (resourceIdValue != null && resourceIdValue.Type != JTokenType.Null)
                                    {
                                        string resourceIdInstance = ((string)resourceIdValue);
                                        metricInstance.ResourceId = resourceIdInstance;
                                    }

                                    JToken propertiesSequenceElement2 = ((JToken)valueValue["properties"]);
                                    if (propertiesSequenceElement2 != null && propertiesSequenceElement2.Type != JTokenType.Null)
                                    {
                                        foreach (JProperty property2 in propertiesSequenceElement2)
                                        {
                                            string propertiesKey2   = ((string)property2.Name);
                                            string propertiesValue2 = ((string)property2.Value);
                                            metricInstance.Properties.Add(propertiesKey2, propertiesValue2);
                                        }
                                    }

                                    JToken dimensionNameValue = valueValue["dimensionName"];
                                    if (dimensionNameValue != null && dimensionNameValue.Type != JTokenType.Null)
                                    {
                                        LocalizableString dimensionNameInstance = new LocalizableString();
                                        metricInstance.DimensionName = dimensionNameInstance;

                                        JToken valueValue3 = dimensionNameValue["value"];
                                        if (valueValue3 != null && valueValue3.Type != JTokenType.Null)
                                        {
                                            string valueInstance2 = ((string)valueValue3);
                                            dimensionNameInstance.Value = valueInstance2;
                                        }

                                        JToken localizedValueValue2 = dimensionNameValue["localizedValue"];
                                        if (localizedValueValue2 != null && localizedValueValue2.Type != JTokenType.Null)
                                        {
                                            string localizedValueInstance2 = ((string)localizedValueValue2);
                                            dimensionNameInstance.LocalizedValue = localizedValueInstance2;
                                        }
                                    }

                                    JToken dimensionValueValue = valueValue["dimensionValue"];
                                    if (dimensionValueValue != null && dimensionValueValue.Type != JTokenType.Null)
                                    {
                                        LocalizableString dimensionValueInstance = new LocalizableString();
                                        metricInstance.DimensionValue = dimensionValueInstance;

                                        JToken valueValue4 = dimensionValueValue["value"];
                                        if (valueValue4 != null && valueValue4.Type != JTokenType.Null)
                                        {
                                            string valueInstance3 = ((string)valueValue4);
                                            dimensionValueInstance.Value = valueInstance3;
                                        }

                                        JToken localizedValueValue3 = dimensionValueValue["localizedValue"];
                                        if (localizedValueValue3 != null && localizedValueValue3.Type != JTokenType.Null)
                                        {
                                            string localizedValueInstance3 = ((string)localizedValueValue3);
                                            dimensionValueInstance.LocalizedValue = localizedValueInstance3;
                                        }
                                    }
                                }
                            }
                        }
                    }
                    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>
        /// Lists the notification hubs associated with a namespace.
        /// </summary>
        /// <param name='namespaceName'>
        /// Required. The namespace name.
        /// </param>
        /// <param name='notificationHubName'>
        /// Required. The notification hub name.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// The set of connection details for a service bus entity.
        /// </returns>
        public async Task <ServiceBusConnectionDetailsResponse> GetConnectionDetailsAsync(string namespaceName, string notificationHubName, CancellationToken cancellationToken)
        {
            // Validate
            if (namespaceName == null)
            {
                throw new ArgumentNullException("namespaceName");
            }
            if (notificationHubName == null)
            {
                throw new ArgumentNullException("notificationHubName");
            }

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

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

            // Construct URL
            string url = "";

            url = url + "/";
            if (this.Client.Credentials.SubscriptionId != null)
            {
                url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
            }
            url = url + "/services/servicebus/namespaces/";
            url = url + Uri.EscapeDataString(namespaceName);
            url = url + "/NotificationHubs/";
            url = url + Uri.EscapeDataString(notificationHubName);
            url = url + "/ConnectionDetails";
            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("x-ms-version", "2013-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
                    ServiceBusConnectionDetailsResponse result = null;
                    // Deserialize Response
                    if (statusCode == HttpStatusCode.OK)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                        result = new ServiceBusConnectionDetailsResponse();
                        XDocument responseDoc = XDocument.Parse(responseContent);

                        XElement feedElement = responseDoc.Element(XName.Get("feed", "http://www.w3.org/2005/Atom"));
                        if (feedElement != null)
                        {
                            if (feedElement != null)
                            {
                                foreach (XElement entriesElement in feedElement.Elements(XName.Get("entry", "http://www.w3.org/2005/Atom")))
                                {
                                    ServiceBusConnectionDetail entryInstance = new ServiceBusConnectionDetail();
                                    result.ConnectionDetails.Add(entryInstance);

                                    XElement contentElement = entriesElement.Element(XName.Get("content", "http://www.w3.org/2005/Atom"));
                                    if (contentElement != null)
                                    {
                                        XElement connectionDetailElement = contentElement.Element(XName.Get("ConnectionDetail", "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect"));
                                        if (connectionDetailElement != null)
                                        {
                                            XElement keyNameElement = connectionDetailElement.Element(XName.Get("KeyName", "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect"));
                                            if (keyNameElement != null)
                                            {
                                                string keyNameInstance = keyNameElement.Value;
                                                entryInstance.KeyName = keyNameInstance;
                                            }

                                            XElement connectionStringElement = connectionDetailElement.Element(XName.Get("ConnectionString", "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect"));
                                            if (connectionStringElement != null)
                                            {
                                                string connectionStringInstance = connectionStringElement.Value;
                                                entryInstance.ConnectionString = connectionStringInstance;
                                            }

                                            XElement authorizationTypeElement = connectionDetailElement.Element(XName.Get("AuthorizationType", "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect"));
                                            if (authorizationTypeElement != null)
                                            {
                                                string authorizationTypeInstance = authorizationTypeElement.Value;
                                                entryInstance.AuthorizationType = authorizationTypeInstance;
                                            }

                                            XElement rightsSequenceElement = connectionDetailElement.Element(XName.Get("Rights", "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect"));
                                            if (rightsSequenceElement != null)
                                            {
                                                foreach (XElement rightsElement in rightsSequenceElement.Elements(XName.Get("AccessRights", "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect")))
                                                {
                                                    entryInstance.Rights.Add(((AccessRight)Enum.Parse(typeof(AccessRight), rightsElement.Value, true)));
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    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();
                }
            }
        }
        public IAccessToken Authenticate(
            IAzureAccount account,
            IAzureEnvironment environment,
            string tenant,
            SecureString password,
            string promptBehavior,
            Action <string> promptAction,
            IAzureTokenCache tokenCache,
            string resourceId = AzureEnvironment.Endpoint.ActiveDirectoryServiceEndpointResourceId)
        {
            IAccessToken token;
            var          cache = tokenCache as TokenCache;

            if (cache == null)
            {
                cache = TokenCache.DefaultShared;
            }

            var configuration = GetAdalConfiguration(environment, tenant, resourceId, cache);

            TracingAdapter.Information(
                Resources.AdalAuthConfigurationTrace,
                configuration.AdDomain,
                configuration.AdEndpoint,
                configuration.ClientId,
                configuration.ClientRedirectUri,
                configuration.ResourceClientUri,
                configuration.ValidateAuthority);
            if (account != null && account.Type == AzureAccount.AccountType.ManagedService)
            {
                token = GetManagedServiceToken(account, environment, tenant, resourceId);
            }
            else if (account != null && environment != null &&
                     account.Type == AzureAccount.AccountType.AccessToken)
            {
                var rawToken = new RawAccessToken
                {
                    TenantId  = tenant,
                    UserId    = account.Id,
                    LoginType = AzureAccount.AccountType.AccessToken
                };

                if ((string.Equals(resourceId, environment.AzureKeyVaultServiceEndpointResourceId, StringComparison.OrdinalIgnoreCase) ||
                     string.Equals(AzureEnvironment.Endpoint.AzureKeyVaultServiceEndpointResourceId, resourceId, StringComparison.OrdinalIgnoreCase)) &&
                    account.IsPropertySet(AzureAccount.Property.KeyVaultAccessToken))
                {
                    rawToken.AccessToken = account.GetProperty(AzureAccount.Property.KeyVaultAccessToken);
                }
                else if ((string.Equals(resourceId, environment.GraphEndpointResourceId, StringComparison.OrdinalIgnoreCase) ||
                          string.Equals(AzureEnvironment.Endpoint.GraphEndpointResourceId, resourceId, StringComparison.OrdinalIgnoreCase)) &&
                         account.IsPropertySet(AzureAccount.Property.GraphAccessToken))
                {
                    rawToken.AccessToken = account.GetProperty(AzureAccount.Property.GraphAccessToken);
                }
                else if ((string.Equals(resourceId, environment.ActiveDirectoryServiceEndpointResourceId, StringComparison.OrdinalIgnoreCase) ||
                          string.Equals(AzureEnvironment.Endpoint.ActiveDirectoryServiceEndpointResourceId, resourceId, StringComparison.OrdinalIgnoreCase)) &&
                         account.IsPropertySet(AzureAccount.Property.AccessToken))
                {
                    rawToken.AccessToken = account.GetAccessToken();
                }
                else
                {
                    throw new InvalidOperationException(string.Format(Resources.AccessTokenResourceNotFound, resourceId));
                }

                token = rawToken;
            }
            else if (account.IsPropertySet(AzureAccount.Property.CertificateThumbprint))
            {
                var thumbprint = account.GetProperty(AzureAccount.Property.CertificateThumbprint);
#if !NETSTANDARD
                token = TokenProvider.GetAccessTokenWithCertificate(configuration, account.Id, thumbprint, account.Type);
#else
                throw new NotSupportedException("Certificate based authentication is not supported in netcore version.");
#endif
            }
            else
            {
                token = TokenProvider.GetAccessToken(configuration, promptBehavior, promptAction, account.Id, password, account.Type);
            }

            account.Id = token.UserId;
            return(token);
        }