/// <summary>
        /// Gets a next list of deployments operations.
        /// </summary>
        /// <param name='nextLink'>
        /// Required. NextLink from the previous successful call to List
        /// operation.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// List of deployment operations.
        /// </returns>
        public async Task <DeploymentOperationsListResult> ListNextAsync(string nextLink, CancellationToken cancellationToken)
        {
            // Validate
            if (nextLink == null)
            {
                throw new ArgumentNullException("nextLink");
            }

            // Tracing
            bool   shouldTrace  = CloudContext.Configuration.Tracing.IsEnabled;
            string invocationId = null;

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

            // Construct URL
            string url = nextLink.Trim();

            // 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)
                    {
                        Tracing.SendRequest(invocationId, httpRequest);
                    }
                    cancellationToken.ThrowIfCancellationRequested();
                    httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);

                    if (shouldTrace)
                    {
                        Tracing.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)
                        {
                            Tracing.Error(invocationId, ex);
                        }
                        throw ex;
                    }

                    // Create Result
                    DeploymentOperationsListResult result = null;
                    // Deserialize Response
                    cancellationToken.ThrowIfCancellationRequested();
                    string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                    result = new DeploymentOperationsListResult();
                    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))
                            {
                                DeploymentOperation deploymentOperationInstance = new DeploymentOperation();
                                result.Operations.Add(deploymentOperationInstance);

                                JToken operationIdValue = valueValue["operationId"];
                                if (operationIdValue != null && operationIdValue.Type != JTokenType.Null)
                                {
                                    string operationIdInstance = ((string)operationIdValue);
                                    deploymentOperationInstance.OperationId = operationIdInstance;
                                }

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

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

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

                                    JToken statusCodeValue = propertiesValue["statusCode"];
                                    if (statusCodeValue != null && statusCodeValue.Type != JTokenType.Null)
                                    {
                                        string statusCodeInstance = ((string)statusCodeValue);
                                        propertiesInstance.StatusCode = statusCodeInstance;
                                    }

                                    JToken statusMessageValue = propertiesValue["statusMessage"];
                                    if (statusMessageValue != null && statusMessageValue.Type != JTokenType.Null)
                                    {
                                        string statusMessageInstance = statusMessageValue.ToString(Formatting.Indented);
                                        propertiesInstance.StatusMessage = statusMessageInstance;
                                    }

                                    JToken targetResourceValue = propertiesValue["targetResource"];
                                    if (targetResourceValue != null && targetResourceValue.Type != JTokenType.Null)
                                    {
                                        TargetResource targetResourceInstance = new TargetResource();
                                        propertiesInstance.TargetResource = targetResourceInstance;

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

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

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

                        JToken odatanextLinkValue = responseDoc["@odata.nextLink"];
                        if (odatanextLinkValue != null && odatanextLinkValue.Type != JTokenType.Null)
                        {
                            string odatanextLinkInstance = ((string)odatanextLinkValue);
                            result.NextLink = odatanextLinkInstance;
                        }
                    }

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

                    if (shouldTrace)
                    {
                        Tracing.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 System.Threading.Tasks.Task <Microsoft.WindowsAzure.Management.Store.Models.CloudServiceListResponse> ListAsync(CancellationToken cancellationToken)
        {
            // Validate

            // Tracing
            bool   shouldTrace  = CloudContext.Configuration.Tracing.IsEnabled;
            string invocationId = null;

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

            // Construct URL
            string url     = "/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/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)
                    {
                        Tracing.SendRequest(invocationId, httpRequest);
                    }
                    cancellationToken.ThrowIfCancellationRequested();
                    httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);

                    if (shouldTrace)
                    {
                        Tracing.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)
                        {
                            Tracing.Error(invocationId, ex);
                        }
                        throw ex;
                    }

                    // Create Result
                    CloudServiceListResponse result = null;
                    // Deserialize Response
                    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)
                    {
                        Tracing.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 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.  (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 error information regarding
        /// the failure.
        /// </returns>
        public async System.Threading.Tasks.Task <OperationStatusResponse> GetOperationStatusAsync(string requestId, CancellationToken cancellationToken)
        {
            // Validate
            if (requestId == null)
            {
                throw new ArgumentNullException("requestId");
            }

            // Tracing
            bool   shouldTrace  = CloudContext.Configuration.Tracing.IsEnabled;
            string invocationId = null;

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

            // Construct URL
            string baseUrl = this.BaseUri.AbsoluteUri;
            string url     = "/" + (this.Credentials.SubscriptionId != null ? this.Credentials.SubscriptionId.Trim() : "") + "/operations/" + requestId.Trim();

            // 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;

            // 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-03-01");

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

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

                    if (shouldTrace)
                    {
                        Tracing.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), CloudExceptionType.Xml);
                        if (shouldTrace)
                        {
                            Tracing.Error(invocationId, ex);
                        }
                        throw ex;
                    }

                    // Create Result
                    OperationStatusResponse result = null;
                    // Deserialize Response
                    cancellationToken.ThrowIfCancellationRequested();
                    string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                    result = new OperationStatusResponse();
                    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)
                        {
                            OperationStatusResponse.ErrorDetails errorInstance = new OperationStatusResponse.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)
                    {
                        Tracing.Exit(invocationId, result);
                    }
                    return(result);
                }
                finally
                {
                    if (httpResponse != null)
                    {
                        httpResponse.Dispose();
                    }
                }
            }
            finally
            {
                if (httpRequest != null)
                {
                    httpRequest.Dispose();
                }
            }
        }
        /// <summary>
        /// The List Dedicated Circuit operation retrieves a list of dedicated
        /// circuits owned by the customer.
        /// </summary>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// The List Dedicated Circuit operation response.
        /// </returns>
        public async System.Threading.Tasks.Task <Microsoft.WindowsAzure.Management.ExpressRoute.Models.DedicatedCircuitListResponse> ListAsync(CancellationToken cancellationToken)
        {
            // Validate

            // Tracing
            bool   shouldTrace  = CloudContext.Configuration.Tracing.IsEnabled;
            string invocationId = null;

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

            // Construct URL
            string baseUrl = this.Client.BaseUri.AbsoluteUri;
            string url     = "/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/services/networking/dedicatedcircuits?api-version=1.0";

            // 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;

            // 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", "2011-10-01");

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

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

                    if (shouldTrace)
                    {
                        Tracing.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), CloudExceptionType.Xml);
                        if (shouldTrace)
                        {
                            Tracing.Error(invocationId, ex);
                        }
                        throw ex;
                    }

                    // Create Result
                    DedicatedCircuitListResponse result = null;
                    // Deserialize Response
                    cancellationToken.ThrowIfCancellationRequested();
                    string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

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

                    XElement dedicatedCircuitsSequenceElement = responseDoc.Element(XName.Get("DedicatedCircuits", "http://schemas.microsoft.com/windowsazure"));
                    if (dedicatedCircuitsSequenceElement != null)
                    {
                        foreach (XElement dedicatedCircuitsElement in dedicatedCircuitsSequenceElement.Elements(XName.Get("DedicatedCircuit", "http://schemas.microsoft.com/windowsazure")))
                        {
                            AzureDedicatedCircuit dedicatedCircuitInstance = new AzureDedicatedCircuit();
                            result.DedicatedCircuits.Add(dedicatedCircuitInstance);

                            XElement bandwidthElement = dedicatedCircuitsElement.Element(XName.Get("Bandwidth", "http://schemas.microsoft.com/windowsazure"));
                            if (bandwidthElement != null)
                            {
                                uint bandwidthInstance = uint.Parse(bandwidthElement.Value, CultureInfo.InvariantCulture);
                                dedicatedCircuitInstance.Bandwidth = bandwidthInstance;
                            }

                            XElement circuitNameElement = dedicatedCircuitsElement.Element(XName.Get("CircuitName", "http://schemas.microsoft.com/windowsazure"));
                            if (circuitNameElement != null)
                            {
                                string circuitNameInstance = circuitNameElement.Value;
                                dedicatedCircuitInstance.CircuitName = circuitNameInstance;
                            }

                            XElement locationElement = dedicatedCircuitsElement.Element(XName.Get("Location", "http://schemas.microsoft.com/windowsazure"));
                            if (locationElement != null)
                            {
                                string locationInstance = locationElement.Value;
                                dedicatedCircuitInstance.Location = locationInstance;
                            }

                            XElement serviceKeyElement = dedicatedCircuitsElement.Element(XName.Get("ServiceKey", "http://schemas.microsoft.com/windowsazure"));
                            if (serviceKeyElement != null)
                            {
                                string serviceKeyInstance = serviceKeyElement.Value;
                                dedicatedCircuitInstance.ServiceKey = serviceKeyInstance;
                            }

                            XElement serviceProviderNameElement = dedicatedCircuitsElement.Element(XName.Get("ServiceProviderName", "http://schemas.microsoft.com/windowsazure"));
                            if (serviceProviderNameElement != null)
                            {
                                string serviceProviderNameInstance = serviceProviderNameElement.Value;
                                dedicatedCircuitInstance.ServiceProviderName = serviceProviderNameInstance;
                            }

                            XElement serviceProviderProvisioningStateElement = dedicatedCircuitsElement.Element(XName.Get("ServiceProviderProvisioningState", "http://schemas.microsoft.com/windowsazure"));
                            if (serviceProviderProvisioningStateElement != null)
                            {
                                ProviderProvisioningState serviceProviderProvisioningStateInstance = ((ProviderProvisioningState)Enum.Parse(typeof(ProviderProvisioningState), serviceProviderProvisioningStateElement.Value, true));
                                dedicatedCircuitInstance.ServiceProviderProvisioningState = serviceProviderProvisioningStateInstance;
                            }

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

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

                    if (shouldTrace)
                    {
                        Tracing.Exit(invocationId, result);
                    }
                    return(result);
                }
                finally
                {
                    if (httpResponse != null)
                    {
                        httpResponse.Dispose();
                    }
                }
            }
            finally
            {
                if (httpRequest != null)
                {
                    httpRequest.Dispose();
                }
            }
        }
        /// <summary>
        /// The New Dedicated Circuit operation creates a new dedicated circuit.
        /// </summary>
        /// <param name='parameters'>
        /// Required. Parameters supplied to the New Dedicated Circuit
        /// operation.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// A standard express route gateway response including an HTTP status
        /// code and request ID.
        /// </returns>
        public async System.Threading.Tasks.Task <Microsoft.WindowsAzure.Management.ExpressRoute.Models.ExpressRouteOperationResponse> BeginNewAsync(DedicatedCircuitNewParameters parameters, CancellationToken cancellationToken)
        {
            // Validate
            if (parameters == null)
            {
                throw new ArgumentNullException("parameters");
            }
            if (parameters.CircuitName == null)
            {
                throw new ArgumentNullException("parameters.CircuitName");
            }
            if (parameters.Location == null)
            {
                throw new ArgumentNullException("parameters.Location");
            }
            if (parameters.ServiceProviderName == null)
            {
                throw new ArgumentNullException("parameters.ServiceProviderName");
            }

            // Tracing
            bool   shouldTrace  = CloudContext.Configuration.Tracing.IsEnabled;
            string invocationId = null;

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

            // Construct URL
            string baseUrl = this.Client.BaseUri.AbsoluteUri;
            string url     = "/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/services/networking/dedicatedcircuits?api-version=1.0";

            // 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;

            // 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-version", "2011-10-01");

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

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

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

                XElement bandwidthElement = new XElement(XName.Get("Bandwidth", "http://schemas.microsoft.com/windowsazure"));
                bandwidthElement.Value = parameters.Bandwidth.ToString();
                createDedicatedCircuitElement.Add(bandwidthElement);

                XElement circuitNameElement = new XElement(XName.Get("CircuitName", "http://schemas.microsoft.com/windowsazure"));
                circuitNameElement.Value = parameters.CircuitName;
                createDedicatedCircuitElement.Add(circuitNameElement);

                XElement locationElement = new XElement(XName.Get("Location", "http://schemas.microsoft.com/windowsazure"));
                locationElement.Value = parameters.Location;
                createDedicatedCircuitElement.Add(locationElement);

                XElement serviceProviderNameElement = new XElement(XName.Get("ServiceProviderName", "http://schemas.microsoft.com/windowsazure"));
                serviceProviderNameElement.Value = parameters.ServiceProviderName;
                createDedicatedCircuitElement.Add(serviceProviderNameElement);

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

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

                    if (shouldTrace)
                    {
                        Tracing.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), CloudExceptionType.Xml);
                        if (shouldTrace)
                        {
                            Tracing.Error(invocationId, ex);
                        }
                        throw ex;
                    }

                    // Create Result
                    ExpressRouteOperationResponse result = null;
                    // Deserialize Response
                    cancellationToken.ThrowIfCancellationRequested();
                    string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

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

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

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

                    if (shouldTrace)
                    {
                        Tracing.Exit(invocationId, result);
                    }
                    return(result);
                }
                finally
                {
                    if (httpResponse != null)
                    {
                        httpResponse.Dispose();
                    }
                }
            }
            finally
            {
                if (httpRequest != null)
                {
                    httpRequest.Dispose();
                }
            }
        }
Esempio n. 6
0
        /// <summary>
        /// The List Role Sizes operation lists all of the role sizes that are
        /// valid for your subscription.
        /// </summary>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// The List Role Sizes operation response.
        /// </returns>
        public async System.Threading.Tasks.Task <Microsoft.WindowsAzure.Management.Models.RoleSizeListResponse> ListAsync(CancellationToken cancellationToken)
        {
            // Validate

            // Tracing
            bool   shouldTrace  = CloudContext.Configuration.Tracing.IsEnabled;
            string invocationId = null;

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

            // Construct URL
            string url     = "/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/rolesizes";
            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-05-01");

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

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

                    if (shouldTrace)
                    {
                        Tracing.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)
                        {
                            Tracing.Error(invocationId, ex);
                        }
                        throw ex;
                    }

                    // Create Result
                    RoleSizeListResponse result = null;
                    // Deserialize Response
                    cancellationToken.ThrowIfCancellationRequested();
                    string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

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

                    XElement roleSizesSequenceElement = responseDoc.Element(XName.Get("RoleSizes", "http://schemas.microsoft.com/windowsazure"));
                    if (roleSizesSequenceElement != null)
                    {
                        foreach (XElement roleSizesElement in roleSizesSequenceElement.Elements(XName.Get("RoleSize", "http://schemas.microsoft.com/windowsazure")))
                        {
                            RoleSizeListResponse.RoleSize roleSizeInstance = new RoleSizeListResponse.RoleSize();
                            result.RoleSizes.Add(roleSizeInstance);

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

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

                            XElement coresElement = roleSizesElement.Element(XName.Get("Cores", "http://schemas.microsoft.com/windowsazure"));
                            if (coresElement != null)
                            {
                                int coresInstance = int.Parse(coresElement.Value, CultureInfo.InvariantCulture);
                                roleSizeInstance.Cores = coresInstance;
                            }

                            XElement memoryInMbElement = roleSizesElement.Element(XName.Get("MemoryInMb", "http://schemas.microsoft.com/windowsazure"));
                            if (memoryInMbElement != null)
                            {
                                int memoryInMbInstance = int.Parse(memoryInMbElement.Value, CultureInfo.InvariantCulture);
                                roleSizeInstance.MemoryInMb = memoryInMbInstance;
                            }

                            XElement supportedByWebWorkerRolesElement = roleSizesElement.Element(XName.Get("SupportedByWebWorkerRoles", "http://schemas.microsoft.com/windowsazure"));
                            if (supportedByWebWorkerRolesElement != null)
                            {
                                bool supportedByWebWorkerRolesInstance = bool.Parse(supportedByWebWorkerRolesElement.Value);
                                roleSizeInstance.SupportedByWebWorkerRoles = supportedByWebWorkerRolesInstance;
                            }

                            XElement supportedByVirtualMachinesElement = roleSizesElement.Element(XName.Get("SupportedByVirtualMachines", "http://schemas.microsoft.com/windowsazure"));
                            if (supportedByVirtualMachinesElement != null)
                            {
                                bool supportedByVirtualMachinesInstance = bool.Parse(supportedByVirtualMachinesElement.Value);
                                roleSizeInstance.SupportedByVirtualMachines = supportedByVirtualMachinesInstance;
                            }

                            XElement maxDataDiskCountElement = roleSizesElement.Element(XName.Get("MaxDataDiskCount", "http://schemas.microsoft.com/windowsazure"));
                            if (maxDataDiskCountElement != null)
                            {
                                int maxDataDiskCountInstance = int.Parse(maxDataDiskCountElement.Value, CultureInfo.InvariantCulture);
                                roleSizeInstance.MaxDataDiskCount = maxDataDiskCountInstance;
                            }

                            XElement webWorkerResourceDiskSizeInMbElement = roleSizesElement.Element(XName.Get("WebWorkerResourceDiskSizeInMb", "http://schemas.microsoft.com/windowsazure"));
                            if (webWorkerResourceDiskSizeInMbElement != null)
                            {
                                int webWorkerResourceDiskSizeInMbInstance = int.Parse(webWorkerResourceDiskSizeInMbElement.Value, CultureInfo.InvariantCulture);
                                roleSizeInstance.WebWorkerResourceDiskSizeInMb = webWorkerResourceDiskSizeInMbInstance;
                            }

                            XElement virtualMachineResourceDiskSizeInMbElement = roleSizesElement.Element(XName.Get("VirtualMachineResourceDiskSizeInMb", "http://schemas.microsoft.com/windowsazure"));
                            if (virtualMachineResourceDiskSizeInMbElement != null)
                            {
                                int virtualMachineResourceDiskSizeInMbInstance = int.Parse(virtualMachineResourceDiskSizeInMbElement.Value, CultureInfo.InvariantCulture);
                                roleSizeInstance.VirtualMachineResourceDiskSizeInMb = virtualMachineResourceDiskSizeInMbInstance;
                            }
                        }
                    }

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

                    if (shouldTrace)
                    {
                        Tracing.Exit(invocationId, result);
                    }
                    return(result);
                }
                finally
                {
                    if (httpResponse != null)
                    {
                        httpResponse.Dispose();
                    }
                }
            }
            finally
            {
                if (httpRequest != null)
                {
                    httpRequest.Dispose();
                }
            }
        }
Esempio n. 7
0
        /// <summary>
        /// Retrieve a list of Cloud services  (see
        /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXXXX.aspx
        /// for more information)
        /// </summary>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// The response model for the list cloud service operation.
        /// </returns>
        public async Task <CloudServiceListResponse> ListAsync(CancellationToken cancellationToken)
        {
            // Validate

            // Tracing
            bool   shouldTrace  = CloudContext.Configuration.Tracing.IsEnabled;
            string invocationId = null;

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

            // Construct URL
            string url = "/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/cloudservices?";

            url = url + "resourceType=AutomationAccount";
            url = url + "&detailLevel=Full";
            url = url + "&resourceProviderNamespace=automation";
            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)
                    {
                        Tracing.SendRequest(invocationId, httpRequest);
                    }
                    cancellationToken.ThrowIfCancellationRequested();
                    httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);

                    if (shouldTrace)
                    {
                        Tracing.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)
                        {
                            Tracing.Error(invocationId, ex);
                        }
                        throw ex;
                    }

                    // Create Result
                    CloudServiceListResponse result = null;
                    // Deserialize Response
                    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")))
                        {
                            CloudService cloudServiceInstance = new 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 = 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")))
                                {
                                    AutomationResource resourceInstance = new AutomationResource();
                                    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;
                                    }
                                }
                            }
                        }
                    }

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

                    if (shouldTrace)
                    {
                        Tracing.Exit(invocationId, result);
                    }
                    return(result);
                }
                finally
                {
                    if (httpResponse != null)
                    {
                        httpResponse.Dispose();
                    }
                }
            }
            finally
            {
                if (httpRequest != null)
                {
                    httpRequest.Dispose();
                }
            }
        }
Esempio n. 8
0
        /// <summary>
        /// Updates a setting.
        /// </summary>
        /// <param name='parameters'>
        /// Required. The setting value.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// A standard service response including an HTTP status code and
        /// request ID.
        /// </returns>
        public async System.Threading.Tasks.Task <OperationResponse> UpdateAsync(SettingsUpdateParameters parameters, CancellationToken cancellationToken)
        {
            // Validate
            if (parameters == null)
            {
                throw new ArgumentNullException("parameters");
            }

            // Tracing
            bool   shouldTrace  = CloudContext.Configuration.Tracing.IsEnabled;
            string invocationId = null;

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

            // Construct URL
            string baseUrl = this.Client.BaseUri.AbsoluteUri;
            string url     = "/api/settings";

            // 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;

            // Create HTTP transport objects
            HttpRequestMessage httpRequest = null;

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

                // Set Headers

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

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

                JObject settingsDictionary = new JObject();
                if (parameters.Settings != null)
                {
                    foreach (KeyValuePair <string, string> pair in parameters.Settings)
                    {
                        string settingsKey   = pair.Key;
                        string settingsValue = pair.Value;
                        settingsDictionary[settingsKey] = settingsValue;
                    }
                }
                requestDoc = settingsDictionary;

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

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

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

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

                    if (shouldTrace)
                    {
                        Tracing.Exit(invocationId, result);
                    }
                    return(result);
                }
                finally
                {
                    if (httpResponse != null)
                    {
                        httpResponse.Dispose();
                    }
                }
            }
            finally
            {
                if (httpRequest != null)
                {
                    httpRequest.Dispose();
                }
            }
        }
Esempio n. 9
0
        /// <summary>
        /// Gets the status of the DAC.
        /// </summary>
        /// <param name='serverName'>
        /// Required. The name of the server.
        /// </param>
        /// <param name='fullyQualifiedServerName'>
        /// Required. The fully qualified name of the server.
        /// </param>
        /// <param name='username'>
        /// Required. The server's username.
        /// </param>
        /// <param name='password'>
        /// Required. The server's password.
        /// </param>
        /// <param name='requestId'>
        /// Required. The request ID of the operation being queried.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// The response structure for the DAC GetStatus operation.
        /// </returns>
        public async System.Threading.Tasks.Task <Microsoft.WindowsAzure.Management.Sql.Models.DacGetStatusResponse> GetStatusAsync(string serverName, string fullyQualifiedServerName, string username, string password, string requestId, CancellationToken cancellationToken)
        {
            // Validate
            if (serverName == null)
            {
                throw new ArgumentNullException("serverName");
            }
            if (fullyQualifiedServerName == null)
            {
                throw new ArgumentNullException("fullyQualifiedServerName");
            }
            if (username == null)
            {
                throw new ArgumentNullException("username");
            }
            if (password == null)
            {
                throw new ArgumentNullException("password");
            }
            if (requestId == null)
            {
                throw new ArgumentNullException("requestId");
            }

            // Tracing
            bool   shouldTrace  = CloudContext.Configuration.Tracing.IsEnabled;
            string invocationId = null;

            if (shouldTrace)
            {
                invocationId = Tracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("serverName", serverName);
                tracingParameters.Add("fullyQualifiedServerName", fullyQualifiedServerName);
                tracingParameters.Add("username", username);
                tracingParameters.Add("password", password);
                tracingParameters.Add("requestId", requestId);
                Tracing.Enter(invocationId, this, "GetStatusAsync", tracingParameters);
            }

            // Construct URL
            string baseUrl = this.Client.BaseUri.AbsoluteUri;
            string url     = "/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/services/sqlservers/servers/" + serverName.Trim() + "/DacOperations/Status?";

            url = url + "servername=" + Uri.EscapeUriString(fullyQualifiedServerName.Trim());
            url = url + "&username="******"&password="******"&reqId=" + Uri.EscapeUriString(requestId.Trim());
            // 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;

            // 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", "2012-03-01");

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

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

                    if (shouldTrace)
                    {
                        Tracing.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), CloudExceptionType.Xml);
                        if (shouldTrace)
                        {
                            Tracing.Error(invocationId, ex);
                        }
                        throw ex;
                    }

                    // Create Result
                    DacGetStatusResponse result = null;
                    // Deserialize Response
                    cancellationToken.ThrowIfCancellationRequested();
                    string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

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

                    XElement arrayOfStatusInfoElement = responseDoc.Element(XName.Get("ArrayOfStatusInfo", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes"));
                    if (arrayOfStatusInfoElement != null)
                    {
                        if (arrayOfStatusInfoElement != null)
                        {
                            foreach (XElement statusInfoElement in arrayOfStatusInfoElement.Elements(XName.Get("StatusInfo", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes")))
                            {
                                StatusInfo statusInfoInstance = new StatusInfo();
                                result.StatusInfoList.Add(statusInfoInstance);

                                XElement blobUriElement = statusInfoElement.Element(XName.Get("BlobUri", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes"));
                                if (blobUriElement != null)
                                {
                                    Uri blobUriInstance = TypeConversion.TryParseUri(blobUriElement.Value);
                                    statusInfoInstance.BlobUri = blobUriInstance;
                                }

                                XElement databaseNameElement = statusInfoElement.Element(XName.Get("DatabaseName", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes"));
                                if (databaseNameElement != null)
                                {
                                    string databaseNameInstance = databaseNameElement.Value;
                                    statusInfoInstance.DatabaseName = databaseNameInstance;
                                }

                                XElement errorMessageElement = statusInfoElement.Element(XName.Get("ErrorMessage", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes"));
                                if (errorMessageElement != null)
                                {
                                    bool       isNil        = false;
                                    XAttribute nilAttribute = errorMessageElement.Attribute(XName.Get("nil", "http://www.w3.org/2001/XMLSchema-instance"));
                                    if (nilAttribute != null)
                                    {
                                        isNil = nilAttribute.Value == "true";
                                    }
                                    if (isNil == false)
                                    {
                                        string errorMessageInstance = errorMessageElement.Value;
                                        statusInfoInstance.ErrorMessage = errorMessageInstance;
                                    }
                                }

                                XElement lastModifiedTimeElement = statusInfoElement.Element(XName.Get("LastModifiedTime", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes"));
                                if (lastModifiedTimeElement != null)
                                {
                                    DateTime lastModifiedTimeInstance = DateTime.Parse(lastModifiedTimeElement.Value, CultureInfo.InvariantCulture);
                                    statusInfoInstance.LastModifiedTime = lastModifiedTimeInstance;
                                }

                                XElement queuedTimeElement = statusInfoElement.Element(XName.Get("QueuedTime", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes"));
                                if (queuedTimeElement != null)
                                {
                                    DateTime queuedTimeInstance = DateTime.Parse(queuedTimeElement.Value, CultureInfo.InvariantCulture);
                                    statusInfoInstance.QueuedTime = queuedTimeInstance;
                                }

                                XElement requestIdElement = statusInfoElement.Element(XName.Get("RequestId", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes"));
                                if (requestIdElement != null)
                                {
                                    string requestIdInstance = requestIdElement.Value;
                                    statusInfoInstance.RequestId = requestIdInstance;
                                }

                                XElement requestTypeElement = statusInfoElement.Element(XName.Get("RequestType", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes"));
                                if (requestTypeElement != null)
                                {
                                    string requestTypeInstance = requestTypeElement.Value;
                                    statusInfoInstance.RequestType = requestTypeInstance;
                                }

                                XElement serverNameElement = statusInfoElement.Element(XName.Get("ServerName", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes"));
                                if (serverNameElement != null)
                                {
                                    string serverNameInstance = serverNameElement.Value;
                                    statusInfoInstance.ServerName = serverNameInstance;
                                }

                                XElement statusElement = statusInfoElement.Element(XName.Get("Status", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes"));
                                if (statusElement != null)
                                {
                                    string statusInstance = statusElement.Value;
                                    statusInfoInstance.Status = statusInstance;
                                }
                            }
                        }
                    }

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

                    if (shouldTrace)
                    {
                        Tracing.Exit(invocationId, result);
                    }
                    return(result);
                }
                finally
                {
                    if (httpResponse != null)
                    {
                        httpResponse.Dispose();
                    }
                }
            }
            finally
            {
                if (httpRequest != null)
                {
                    httpRequest.Dispose();
                }
            }
        }
        /// <summary>
        /// The Add Service Certificate operation adds a certificate to a
        /// hosted service.  The Add Service Certificate operation is an
        /// asynchronous operation. To determine whether the management
        /// service has finished processing the request, call Get Operation
        /// Status.   (see
        /// http://msdn.microsoft.com/en-us/library/windowsazure/ee460817.aspx
        /// for more information)
        /// </summary>
        /// <param name='serviceName'>
        /// The DNS prefix name of your service.
        /// </param>
        /// <param name='parameters'>
        /// Parameters supplied to the Create Service Certificate operation.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// A standard service response including an HTTP status code and
        /// request ID.
        /// </returns>
        public async System.Threading.Tasks.Task <OperationResponse> BeginCreatingAsync(string serviceName, ServiceCertificateCreateParameters parameters, CancellationToken cancellationToken)
        {
            // Validate
            if (serviceName == null)
            {
                throw new ArgumentNullException("serviceName");
            }
            // TODO: Validate serviceName is a valid DNS name.
            if (parameters == null)
            {
                throw new ArgumentNullException("parameters");
            }
            if (parameters.Data == null)
            {
                throw new ArgumentNullException("parameters.Data");
            }

            // Tracing
            bool   shouldTrace  = CloudContext.Configuration.Tracing.IsEnabled;
            string invocationId = null;

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

            // Construct URL
            string url = new Uri(this.Client.BaseUri, "/").ToString() + this.Client.Credentials.SubscriptionId + "/services/hostedservices/" + serviceName + "/certificates";

            // 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-version", "2013-11-01");

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

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

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

                XElement dataElement = new XElement(XName.Get("Data", "http://schemas.microsoft.com/windowsazure"));
                dataElement.Value = Convert.ToBase64String(parameters.Data);
                certificateFileElement.Add(dataElement);

                XElement certificateFormatElement = new XElement(XName.Get("CertificateFormat", "http://schemas.microsoft.com/windowsazure"));
                certificateFormatElement.Value = ComputeManagementClient.CertificateFormatToString(parameters.CertificateFormat);
                certificateFileElement.Add(certificateFormatElement);

                if (parameters.Password != null)
                {
                    XElement passwordElement = new XElement(XName.Get("Password", "http://schemas.microsoft.com/windowsazure"));
                    passwordElement.Value = parameters.Password;
                    certificateFileElement.Add(passwordElement);
                }

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

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

                    if (shouldTrace)
                    {
                        Tracing.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), CloudExceptionType.Xml);
                        if (shouldTrace)
                        {
                            Tracing.Error(invocationId, ex);
                        }
                        throw ex;
                    }

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

                    if (shouldTrace)
                    {
                        Tracing.Exit(invocationId, result);
                    }
                    return(result);
                }
                finally
                {
                    if (httpResponse != null)
                    {
                        httpResponse.Dispose();
                    }
                }
            }
            finally
            {
                if (httpRequest != null)
                {
                    httpRequest.Dispose();
                }
            }
        }
Esempio n. 11
0
        /// <summary>
        /// Lists the settings.
        /// </summary>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// The list settings operation response.
        /// </returns>
        public async System.Threading.Tasks.Task <Microsoft.WindowsAzure.WebSitesExtensions.Models.SettingsListResponse> ListAsync(CancellationToken cancellationToken)
        {
            // Validate

            // Tracing
            bool   shouldTrace  = CloudContext.Configuration.Tracing.IsEnabled;
            string invocationId = null;

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

            // Construct URL
            string baseUrl = this.Client.BaseUri.AbsoluteUri;
            string url     = "/api/settings";

            // 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;

            // 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)
                    {
                        Tracing.SendRequest(invocationId, httpRequest);
                    }
                    cancellationToken.ThrowIfCancellationRequested();
                    httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);

                    if (shouldTrace)
                    {
                        Tracing.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), CloudExceptionType.Json);
                        if (shouldTrace)
                        {
                            Tracing.Error(invocationId, ex);
                        }
                        throw ex;
                    }

                    // Create Result
                    SettingsListResponse result = null;
                    // Deserialize Response
                    cancellationToken.ThrowIfCancellationRequested();
                    string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

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

                    if (responseDoc != null && responseDoc.Type != JTokenType.Null)
                    {
                        JToken settingsSequenceElement = ((JToken)responseDoc);
                        if (settingsSequenceElement != null && settingsSequenceElement.Type != JTokenType.Null)
                        {
                            foreach (JProperty property in settingsSequenceElement)
                            {
                                string settingsKey   = ((string)property.Name);
                                string settingsValue = ((string)property.Value);
                                result.Settings.Add(settingsKey, settingsValue);
                            }
                        }
                    }

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

                    if (shouldTrace)
                    {
                        Tracing.Exit(invocationId, result);
                    }
                    return(result);
                }
                finally
                {
                    if (httpResponse != null)
                    {
                        httpResponse.Dispose();
                    }
                }
            }
            finally
            {
                if (httpRequest != null)
                {
                    httpRequest.Dispose();
                }
            }
        }
        /// <summary>
        /// The List Service Certificates operation lists all of the service
        /// certificates associated with the specified hosted service.  (see
        /// http://msdn.microsoft.com/en-us/library/windowsazure/jj154105.aspx
        /// for more information)
        /// </summary>
        /// <param name='serviceName'>
        /// The DNS prefix name of your hosted service.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// The List Service Certificates operation response.
        /// </returns>
        public async System.Threading.Tasks.Task <Microsoft.WindowsAzure.Management.Compute.Models.ServiceCertificateListResponse> ListAsync(string serviceName, CancellationToken cancellationToken)
        {
            // Validate
            if (serviceName == null)
            {
                throw new ArgumentNullException("serviceName");
            }
            // TODO: Validate serviceName is a valid DNS name.

            // Tracing
            bool   shouldTrace  = CloudContext.Configuration.Tracing.IsEnabled;
            string invocationId = null;

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

            // Construct URL
            string url = new Uri(this.Client.BaseUri, "/").ToString() + this.Client.Credentials.SubscriptionId + "/services/hostedservices/" + serviceName + "/certificates";

            // 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-11-01");

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

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

                    if (shouldTrace)
                    {
                        Tracing.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), CloudExceptionType.Xml);
                        if (shouldTrace)
                        {
                            Tracing.Error(invocationId, ex);
                        }
                        throw ex;
                    }

                    // Create Result
                    ServiceCertificateListResponse result = null;
                    // Deserialize Response
                    cancellationToken.ThrowIfCancellationRequested();
                    string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

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

                    XElement certificatesSequenceElement = responseDoc.Element(XName.Get("Certificates", "http://schemas.microsoft.com/windowsazure"));
                    if (certificatesSequenceElement != null)
                    {
                        foreach (XElement certificatesElement in certificatesSequenceElement.Elements(XName.Get("Certificate", "http://schemas.microsoft.com/windowsazure")))
                        {
                            ServiceCertificateListResponse.Certificate certificateInstance = new ServiceCertificateListResponse.Certificate();
                            result.Certificates.Add(certificateInstance);

                            XElement certificateUrlElement = certificatesElement.Element(XName.Get("CertificateUrl", "http://schemas.microsoft.com/windowsazure"));
                            if (certificateUrlElement != null)
                            {
                                Uri certificateUrlInstance = TypeConversion.TryParseUri(certificateUrlElement.Value);
                                certificateInstance.CertificateUri = certificateUrlInstance;
                            }

                            XElement thumbprintElement = certificatesElement.Element(XName.Get("Thumbprint", "http://schemas.microsoft.com/windowsazure"));
                            if (thumbprintElement != null)
                            {
                                string thumbprintInstance = thumbprintElement.Value;
                                certificateInstance.Thumbprint = thumbprintInstance;
                            }

                            XElement thumbprintAlgorithmElement = certificatesElement.Element(XName.Get("ThumbprintAlgorithm", "http://schemas.microsoft.com/windowsazure"));
                            if (thumbprintAlgorithmElement != null)
                            {
                                string thumbprintAlgorithmInstance = thumbprintAlgorithmElement.Value;
                                certificateInstance.ThumbprintAlgorithm = thumbprintAlgorithmInstance;
                            }

                            XElement dataElement = certificatesElement.Element(XName.Get("Data", "http://schemas.microsoft.com/windowsazure"));
                            if (dataElement != null)
                            {
                                byte[] dataInstance = Convert.FromBase64String(dataElement.Value);
                                certificateInstance.Data = dataInstance;
                            }
                        }
                    }

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

                    if (shouldTrace)
                    {
                        Tracing.Exit(invocationId, result);
                    }
                    return(result);
                }
                finally
                {
                    if (httpResponse != null)
                    {
                        httpResponse.Dispose();
                    }
                }
            }
            finally
            {
                if (httpRequest != null)
                {
                    httpRequest.Dispose();
                }
            }
        }
        /// <summary>
        /// The Delete Service Certificate operation deletes a service
        /// certificate from the certificate store of a hosted service.  The
        /// Delete Service Certificate operation is an asynchronous operation.
        /// To determine whether the management service has finished
        /// processing the request, call Get Operation Status.  (see
        /// http://msdn.microsoft.com/en-us/library/windowsazure/ee460803.aspx
        /// for more information)
        /// </summary>
        /// <param name='parameters'>
        /// Parameters supplied to the Delete Service Certificate operation.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// A standard service response including an HTTP status code and
        /// request ID.
        /// </returns>
        public async System.Threading.Tasks.Task <OperationResponse> BeginDeletingAsync(ServiceCertificateDeleteParameters parameters, CancellationToken cancellationToken)
        {
            // Validate
            if (parameters == null)
            {
                throw new ArgumentNullException("parameters");
            }
            if (parameters.ServiceName == null)
            {
                throw new ArgumentNullException("parameters.ServiceName");
            }
            // TODO: Validate parameters.ServiceName is a valid DNS name.
            if (parameters.Thumbprint == null)
            {
                throw new ArgumentNullException("parameters.Thumbprint");
            }
            if (parameters.ThumbprintAlgorithm == null)
            {
                throw new ArgumentNullException("parameters.ThumbprintAlgorithm");
            }

            // Tracing
            bool   shouldTrace  = CloudContext.Configuration.Tracing.IsEnabled;
            string invocationId = null;

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

            // Construct URL
            string url = new Uri(this.Client.BaseUri, "/").ToString() + this.Client.Credentials.SubscriptionId + "/services/hostedservices/" + parameters.ServiceName + "/certificates/" + parameters.ThumbprintAlgorithm + "-" + parameters.Thumbprint;

            // Create HTTP transport objects
            HttpRequestMessage httpRequest = null;

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

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

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

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

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

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

                    if (shouldTrace)
                    {
                        Tracing.Exit(invocationId, result);
                    }
                    return(result);
                }
                finally
                {
                    if (httpResponse != null)
                    {
                        httpResponse.Dispose();
                    }
                }
            }
            finally
            {
                if (httpRequest != null)
                {
                    httpRequest.Dispose();
                }
            }
        }
        /// <summary>
        /// Get a list of deployments operations.
        /// </summary>
        /// <param name='resourceGroupName'>
        /// Required. The name of the resource group. The name is case
        /// insensitive.
        /// </param>
        /// <param name='deploymentName'>
        /// Required. The name of the deployment.
        /// </param>
        /// <param name='operationId'>
        /// Required. Operation Id.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// Deployment operation.
        /// </returns>
        public async Task <DeploymentOperationsGetResult> GetAsync(string resourceGroupName, string deploymentName, string operationId, CancellationToken cancellationToken)
        {
            // Validate
            if (resourceGroupName == null)
            {
                throw new ArgumentNullException("resourceGroupName");
            }
            if (resourceGroupName != null && resourceGroupName.Length > 1000)
            {
                throw new ArgumentOutOfRangeException("resourceGroupName");
            }
            if (Regex.IsMatch(resourceGroupName, "^[-\\w\\._]+$") == false)
            {
                throw new ArgumentOutOfRangeException("resourceGroupName");
            }
            if (deploymentName == null)
            {
                throw new ArgumentNullException("deploymentName");
            }
            if (operationId == null)
            {
                throw new ArgumentNullException("operationId");
            }

            // Tracing
            bool   shouldTrace  = CloudContext.Configuration.Tracing.IsEnabled;
            string invocationId = null;

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

            // Construct URL
            string baseUrl = this.Client.BaseUri.AbsoluteUri;
            string url     = "/subscriptions/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/resourcegroups/" + resourceGroupName.Trim() + "/deployments/" + deploymentName.Trim() + "/operations/" + operationId.Trim() + "?";

            url = url + "api-version=2014-04-01-preview";
            // 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;

            // 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)
                    {
                        Tracing.SendRequest(invocationId, httpRequest);
                    }
                    cancellationToken.ThrowIfCancellationRequested();
                    httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);

                    if (shouldTrace)
                    {
                        Tracing.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)
                        {
                            Tracing.Error(invocationId, ex);
                        }
                        throw ex;
                    }

                    // Create Result
                    DeploymentOperationsGetResult result = null;
                    // Deserialize Response
                    cancellationToken.ThrowIfCancellationRequested();
                    string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

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

                    if (responseDoc != null && responseDoc.Type != JTokenType.Null)
                    {
                        DeploymentOperation operationInstance = new DeploymentOperation();
                        result.Operation = operationInstance;

                        JToken operationIdValue = responseDoc["operationId"];
                        if (operationIdValue != null && operationIdValue.Type != JTokenType.Null)
                        {
                            string operationIdInstance = ((string)operationIdValue);
                            operationInstance.OperationId = operationIdInstance;
                        }

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

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

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

                            JToken statusCodeValue = propertiesValue["statusCode"];
                            if (statusCodeValue != null && statusCodeValue.Type != JTokenType.Null)
                            {
                                string statusCodeInstance = ((string)statusCodeValue);
                                propertiesInstance.StatusCode = statusCodeInstance;
                            }

                            JToken statusMessageValue = propertiesValue["statusMessage"];
                            if (statusMessageValue != null && statusMessageValue.Type != JTokenType.Null)
                            {
                                string statusMessageInstance = statusMessageValue.ToString(Formatting.Indented);
                                propertiesInstance.StatusMessage = statusMessageInstance;
                            }

                            JToken targetResourceValue = propertiesValue["targetResource"];
                            if (targetResourceValue != null && targetResourceValue.Type != JTokenType.Null)
                            {
                                TargetResource targetResourceInstance = new TargetResource();
                                propertiesInstance.TargetResource = targetResourceInstance;

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

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

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

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

                    if (shouldTrace)
                    {
                        Tracing.Exit(invocationId, result);
                    }
                    return(result);
                }
                finally
                {
                    if (httpResponse != null)
                    {
                        httpResponse.Dispose();
                    }
                }
            }
            finally
            {
                if (httpRequest != null)
                {
                    httpRequest.Dispose();
                }
            }
        }
Esempio n. 15
0
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// A standard service response including an HTTP status code and
        /// request ID.
        /// </returns>
        public async System.Threading.Tasks.Task <Microsoft.WindowsAzure.Subscriptions.Models.SubscriptionListOperationResponse> ListAsync(CancellationToken cancellationToken)
        {
            // Validate

            // Tracing
            bool   shouldTrace  = CloudContext.Configuration.Tracing.IsEnabled;
            string invocationId = null;

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

            // Construct URL
            string url = new Uri(this.Client.BaseUri, "/subscriptions").AbsoluteUri;

            // 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)
                    {
                        Tracing.SendRequest(invocationId, httpRequest);
                    }
                    cancellationToken.ThrowIfCancellationRequested();
                    httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);

                    if (shouldTrace)
                    {
                        Tracing.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), CloudExceptionType.Xml);
                        if (shouldTrace)
                        {
                            Tracing.Error(invocationId, ex);
                        }
                        throw ex;
                    }

                    // Create Result
                    SubscriptionListOperationResponse result = null;
                    // Deserialize Response
                    cancellationToken.ThrowIfCancellationRequested();
                    string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

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

                    XElement subscriptionsElement = responseDoc.Element(XName.Get("Subscriptions", "http://schemas.microsoft.com/windowsazure"));
                    if (subscriptionsElement != null)
                    {
                        if (subscriptionsElement != null)
                        {
                            foreach (XElement subscriptionsElement2 in subscriptionsElement.Elements(XName.Get("Subscription", "http://schemas.microsoft.com/windowsazure")))
                            {
                                SubscriptionListOperationResponse.Subscription subscriptionInstance = new SubscriptionListOperationResponse.Subscription();
                                result.Subscriptions.Add(subscriptionInstance);

                                XElement subscriptionIDElement = subscriptionsElement2.Element(XName.Get("SubscriptionID", "http://schemas.microsoft.com/windowsazure"));
                                if (subscriptionIDElement != null)
                                {
                                    string subscriptionIDInstance = subscriptionIDElement.Value;
                                    subscriptionInstance.SubscriptionId = subscriptionIDInstance;
                                }

                                XElement subscriptionNameElement = subscriptionsElement2.Element(XName.Get("SubscriptionName", "http://schemas.microsoft.com/windowsazure"));
                                if (subscriptionNameElement != null)
                                {
                                    string subscriptionNameInstance = subscriptionNameElement.Value;
                                    subscriptionInstance.SubscriptionName = subscriptionNameInstance;
                                }

                                XElement subscriptionStatusElement = subscriptionsElement2.Element(XName.Get("SubscriptionStatus", "http://schemas.microsoft.com/windowsazure"));
                                if (subscriptionStatusElement != null)
                                {
                                    SubscriptionStatus subscriptionStatusInstance = (SubscriptionStatus)Enum.Parse(typeof(SubscriptionStatus), subscriptionStatusElement.Value, false);
                                    subscriptionInstance.SubscriptionStatus = subscriptionStatusInstance;
                                }

                                XElement accountAdminLiveEmailIdElement = subscriptionsElement2.Element(XName.Get("AccountAdminLiveEmailId", "http://schemas.microsoft.com/windowsazure"));
                                if (accountAdminLiveEmailIdElement != null)
                                {
                                    string accountAdminLiveEmailIdInstance = accountAdminLiveEmailIdElement.Value;
                                    subscriptionInstance.AccountAdminLiveEmailId = accountAdminLiveEmailIdInstance;
                                }

                                XElement serviceAdminLiveEmailIdElement = subscriptionsElement2.Element(XName.Get("ServiceAdminLiveEmailId", "http://schemas.microsoft.com/windowsazure"));
                                if (serviceAdminLiveEmailIdElement != null)
                                {
                                    string serviceAdminLiveEmailIdInstance = serviceAdminLiveEmailIdElement.Value;
                                    subscriptionInstance.ServiceAdminLiveEmailId = serviceAdminLiveEmailIdInstance;
                                }

                                XElement maxCoreCountElement = subscriptionsElement2.Element(XName.Get("MaxCoreCount", "http://schemas.microsoft.com/windowsazure"));
                                if (maxCoreCountElement != null)
                                {
                                    int maxCoreCountInstance = int.Parse(maxCoreCountElement.Value, CultureInfo.InvariantCulture);
                                    subscriptionInstance.MaximumCoreCount = maxCoreCountInstance;
                                }

                                XElement maxStorageAccountsElement = subscriptionsElement2.Element(XName.Get("MaxStorageAccounts", "http://schemas.microsoft.com/windowsazure"));
                                if (maxStorageAccountsElement != null)
                                {
                                    int maxStorageAccountsInstance = int.Parse(maxStorageAccountsElement.Value, CultureInfo.InvariantCulture);
                                    subscriptionInstance.MaximumStorageAccounts = maxStorageAccountsInstance;
                                }

                                XElement maxHostedServicesElement = subscriptionsElement2.Element(XName.Get("MaxHostedServices", "http://schemas.microsoft.com/windowsazure"));
                                if (maxHostedServicesElement != null)
                                {
                                    int maxHostedServicesInstance = int.Parse(maxHostedServicesElement.Value, CultureInfo.InvariantCulture);
                                    subscriptionInstance.MaximumHostedServices = maxHostedServicesInstance;
                                }

                                XElement currentCoreCountElement = subscriptionsElement2.Element(XName.Get("CurrentCoreCount", "http://schemas.microsoft.com/windowsazure"));
                                if (currentCoreCountElement != null)
                                {
                                    int currentCoreCountInstance = int.Parse(currentCoreCountElement.Value, CultureInfo.InvariantCulture);
                                    subscriptionInstance.CurrentCoreCount = currentCoreCountInstance;
                                }

                                XElement currentStorageAccountsElement = subscriptionsElement2.Element(XName.Get("CurrentStorageAccounts", "http://schemas.microsoft.com/windowsazure"));
                                if (currentStorageAccountsElement != null)
                                {
                                    int currentStorageAccountsInstance = int.Parse(currentStorageAccountsElement.Value, CultureInfo.InvariantCulture);
                                    subscriptionInstance.CurrentStorageAccounts = currentStorageAccountsInstance;
                                }

                                XElement currentHostedServicesElement = subscriptionsElement2.Element(XName.Get("CurrentHostedServices", "http://schemas.microsoft.com/windowsazure"));
                                if (currentHostedServicesElement != null)
                                {
                                    int currentHostedServicesInstance = int.Parse(currentHostedServicesElement.Value, CultureInfo.InvariantCulture);
                                    subscriptionInstance.CurrentHostedServices = currentHostedServicesInstance;
                                }

                                XElement maxVirtualNetworkSitesElement = subscriptionsElement2.Element(XName.Get("MaxVirtualNetworkSites", "http://schemas.microsoft.com/windowsazure"));
                                if (maxVirtualNetworkSitesElement != null)
                                {
                                    int maxVirtualNetworkSitesInstance = int.Parse(maxVirtualNetworkSitesElement.Value, CultureInfo.InvariantCulture);
                                    subscriptionInstance.MaximumVirtualNetworkSites = maxVirtualNetworkSitesInstance;
                                }

                                XElement maxLocalNetworkSitesElement = subscriptionsElement2.Element(XName.Get("MaxLocalNetworkSites", "http://schemas.microsoft.com/windowsazure"));
                                if (maxLocalNetworkSitesElement != null)
                                {
                                    int maxLocalNetworkSitesInstance = int.Parse(maxLocalNetworkSitesElement.Value, CultureInfo.InvariantCulture);
                                    subscriptionInstance.MaximumLocalNetworkSites = maxLocalNetworkSitesInstance;
                                }

                                XElement maxDnsServersElement = subscriptionsElement2.Element(XName.Get("MaxDnsServers", "http://schemas.microsoft.com/windowsazure"));
                                if (maxDnsServersElement != null)
                                {
                                    int maxDnsServersInstance = int.Parse(maxDnsServersElement.Value, CultureInfo.InvariantCulture);
                                    subscriptionInstance.MaximumDnsServers = maxDnsServersInstance;
                                }

                                XElement maxExtraVIPCountElement = subscriptionsElement2.Element(XName.Get("MaxExtraVIPCount", "http://schemas.microsoft.com/windowsazure"));
                                if (maxExtraVIPCountElement != null)
                                {
                                    int maxExtraVIPCountInstance = int.Parse(maxExtraVIPCountElement.Value, CultureInfo.InvariantCulture);
                                    subscriptionInstance.MaximumExtraVirtualIPCount = maxExtraVIPCountInstance;
                                }

                                XElement aADTenantIDElement = subscriptionsElement2.Element(XName.Get("AADTenantID", "http://schemas.microsoft.com/windowsazure"));
                                if (aADTenantIDElement != null)
                                {
                                    string aADTenantIDInstance = aADTenantIDElement.Value;
                                    subscriptionInstance.ActiveDirectoryTenantId = aADTenantIDInstance;
                                }

                                XElement createdTimeElement = subscriptionsElement2.Element(XName.Get("CreatedTime", "http://schemas.microsoft.com/windowsazure"));
                                if (createdTimeElement != null)
                                {
                                    DateTime createdTimeInstance = DateTime.Parse(createdTimeElement.Value, CultureInfo.InvariantCulture);
                                    subscriptionInstance.Created = createdTimeInstance;
                                }
                            }
                        }
                    }

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

                    if (shouldTrace)
                    {
                        Tracing.Exit(invocationId, result);
                    }
                    return(result);
                }
                finally
                {
                    if (httpResponse != null)
                    {
                        httpResponse.Dispose();
                    }
                }
            }
            finally
            {
                if (httpRequest != null)
                {
                    httpRequest.Dispose();
                }
            }
        }
Esempio n. 16
0
        /// <summary>
        /// Export DAC into Windows Azure blob storage.
        /// </summary>
        /// <param name='serverName'>
        /// Required. The name of the server being exported from.
        /// </param>
        /// <param name='parameters'>
        /// Optional. Export parameters.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// Response for an DAC Import/Export request.
        /// </returns>
        public async System.Threading.Tasks.Task <Microsoft.WindowsAzure.Management.Sql.Models.DacImportExportResponse> ExportAsync(string serverName, DacExportParameters parameters, CancellationToken cancellationToken)
        {
            // Validate
            if (serverName == null)
            {
                throw new ArgumentNullException("serverName");
            }
            if (parameters != null)
            {
                if (parameters.BlobCredentials != null)
                {
                    if (parameters.BlobCredentials.StorageAccessKey == null)
                    {
                        throw new ArgumentNullException("parameters.BlobCredentials.StorageAccessKey");
                    }
                    if (parameters.BlobCredentials.Uri == null)
                    {
                        throw new ArgumentNullException("parameters.BlobCredentials.Uri");
                    }
                }
                if (parameters.ConnectionInfo != null)
                {
                    if (parameters.ConnectionInfo.DatabaseName == null)
                    {
                        throw new ArgumentNullException("parameters.ConnectionInfo.DatabaseName");
                    }
                    if (parameters.ConnectionInfo.Password == null)
                    {
                        throw new ArgumentNullException("parameters.ConnectionInfo.Password");
                    }
                    if (parameters.ConnectionInfo.ServerName == null)
                    {
                        throw new ArgumentNullException("parameters.ConnectionInfo.ServerName");
                    }
                    if (parameters.ConnectionInfo.UserName == null)
                    {
                        throw new ArgumentNullException("parameters.ConnectionInfo.UserName");
                    }
                }
            }

            // Tracing
            bool   shouldTrace  = CloudContext.Configuration.Tracing.IsEnabled;
            string invocationId = null;

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

            // Construct URL
            string baseUrl = this.Client.BaseUri.AbsoluteUri;
            string url     = "/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/services/sqlservers/servers/" + serverName.Trim() + "/DacOperations/Export";

            // 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;

            // 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-version", "2012-03-01");

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

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

                if (parameters != null)
                {
                    XElement exportInputElement = new XElement(XName.Get("ExportInput", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes"));
                    requestDoc.Add(exportInputElement);

                    if (parameters.BlobCredentials != null)
                    {
                        XElement blobCredentialsElement = new XElement(XName.Get("BlobCredentials", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes"));
                        exportInputElement.Add(blobCredentialsElement);

                        XAttribute typeAttribute = new XAttribute(XName.Get("type", "http://www.w3.org/2001/XMLSchema-instance"), "");
                        typeAttribute.Value = "BlobStorageAccessKeyCredentials";
                        blobCredentialsElement.Add(typeAttribute);

                        XElement uriElement = new XElement(XName.Get("Uri", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes"));
                        uriElement.Value = parameters.BlobCredentials.Uri.AbsoluteUri;
                        blobCredentialsElement.Add(uriElement);

                        XElement storageAccessKeyElement = new XElement(XName.Get("StorageAccessKey", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes"));
                        storageAccessKeyElement.Value = parameters.BlobCredentials.StorageAccessKey;
                        blobCredentialsElement.Add(storageAccessKeyElement);
                    }

                    if (parameters.ConnectionInfo != null)
                    {
                        XElement connectionInfoElement = new XElement(XName.Get("ConnectionInfo", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes"));
                        exportInputElement.Add(connectionInfoElement);

                        XElement databaseNameElement = new XElement(XName.Get("DatabaseName", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes"));
                        databaseNameElement.Value = parameters.ConnectionInfo.DatabaseName;
                        connectionInfoElement.Add(databaseNameElement);

                        XElement passwordElement = new XElement(XName.Get("Password", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes"));
                        passwordElement.Value = parameters.ConnectionInfo.Password;
                        connectionInfoElement.Add(passwordElement);

                        XElement serverNameElement = new XElement(XName.Get("ServerName", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes"));
                        serverNameElement.Value = parameters.ConnectionInfo.ServerName;
                        connectionInfoElement.Add(serverNameElement);

                        XElement userNameElement = new XElement(XName.Get("UserName", "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes"));
                        userNameElement.Value = parameters.ConnectionInfo.UserName;
                        connectionInfoElement.Add(userNameElement);
                    }
                }

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

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

                    if (shouldTrace)
                    {
                        Tracing.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), CloudExceptionType.Xml);
                        if (shouldTrace)
                        {
                            Tracing.Error(invocationId, ex);
                        }
                        throw ex;
                    }

                    // Create Result
                    DacImportExportResponse result = null;
                    // Deserialize Response
                    cancellationToken.ThrowIfCancellationRequested();
                    string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

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

                    XElement guidElement = responseDoc.Element(XName.Get("guid", "http://schemas.microsoft.com/2003/10/Serialization/"));
                    if (guidElement != null)
                    {
                        result.Guid = guidElement.Value;
                    }

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

                    if (shouldTrace)
                    {
                        Tracing.Exit(invocationId, result);
                    }
                    return(result);
                }
                finally
                {
                    if (httpResponse != null)
                    {
                        httpResponse.Dispose();
                    }
                }
            }
            finally
            {
                if (httpRequest != null)
                {
                    httpRequest.Dispose();
                }
            }
        }
        /// <summary>
        /// The Check Static IP operation retrieves the details for the
        /// availability of static IP addresses for the given virtual network.
        /// </summary>
        /// <param name='virtualNetworkName'>
        /// The name of the virtual network.
        /// </param>
        /// <param name='ipAddress'>
        /// 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, provide a list of suggestions.
        /// </returns>
        public async System.Threading.Tasks.Task <Microsoft.WindowsAzure.Management.Network.Models.NetworkStaticIPAvailabilityResponse> CheckAsync(string virtualNetworkName, string ipAddress, CancellationToken cancellationToken)
        {
            // Validate
            if (virtualNetworkName == null)
            {
                throw new ArgumentNullException("virtualNetworkName");
            }
            if (ipAddress == null)
            {
                throw new ArgumentNullException("ipAddress");
            }

            // Tracing
            bool   shouldTrace  = CloudContext.Configuration.Tracing.IsEnabled;
            string invocationId = null;

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

            // Construct URL
            string url = new Uri(this.Client.BaseUri, "/").ToString() + this.Client.Credentials.SubscriptionId + "/services/networking/" + virtualNetworkName + "?";

            url = url + "op=checkavailability";
            url = url + "&address=" + Uri.EscapeUriString(ipAddress);

            // 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-11-01");

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

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

                    if (shouldTrace)
                    {
                        Tracing.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), CloudExceptionType.Xml);
                        if (shouldTrace)
                        {
                            Tracing.Error(invocationId, ex);
                        }
                        throw ex;
                    }

                    // Create Result
                    NetworkStaticIPAvailabilityResponse result = null;
                    // Deserialize Response
                    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)
                    {
                        Tracing.Exit(invocationId, result);
                    }
                    return(result);
                }
                finally
                {
                    if (httpResponse != null)
                    {
                        httpResponse.Dispose();
                    }
                }
            }
            finally
            {
                if (httpRequest != null)
                {
                    httpRequest.Dispose();
                }
            }
        }
Esempio n. 18
0
        internal override SoapServerMethod RouteRequest()
        {
            string           action = ContentType.GetAction(base.ServerProtocol.Request.ContentType);
            SoapServerMethod method = null;
            bool             flag   = false;
            bool             flag2  = false;
            TraceMethod      caller = Tracing.On ? new TraceMethod(this, "RouteRequest", new object[0]) : null;

            if ((action != null) && (action.Length > 0))
            {
                action = System.Web.HttpUtility.UrlDecode(action);
                if (Tracing.On)
                {
                    Tracing.Enter("RouteRequest", caller, new TraceMethod(base.ServerType, "GetMethod", new object[] { action }), Tracing.Details(base.ServerProtocol.Request));
                }
                method = base.ServerType.GetMethod(action);
                if (Tracing.On)
                {
                    Tracing.Exit("RouteRequest", caller);
                }
                if ((method != null) && (base.ServerType.GetDuplicateMethod(action) != null))
                {
                    method = null;
                    flag   = true;
                }
            }
            XmlQualifiedName empty = XmlQualifiedName.Empty;

            if (method == null)
            {
                empty = base.GetRequestElement();
                if (Tracing.On)
                {
                    Tracing.Enter("RouteRequest", caller, new TraceMethod(base.ServerType, "GetMethod", new object[] { empty }), Tracing.Details(base.ServerProtocol.Request));
                }
                method = base.ServerType.GetMethod(empty);
                if (Tracing.On)
                {
                    Tracing.Exit("RouteRequest", caller);
                }
                if ((method != null) && (base.ServerType.GetDuplicateMethod(empty) != null))
                {
                    method = null;
                    flag2  = true;
                }
            }
            if (method != null)
            {
                return(method);
            }
            if ((action == null) || (action.Length == 0))
            {
                throw new SoapException(System.Web.Services.Res.GetString("UnableToHandleRequestActionRequired0"), Soap12FaultCodes.SenderFaultCode);
            }
            if (flag)
            {
                if (flag2)
                {
                    throw new SoapException(System.Web.Services.Res.GetString("UnableToHandleRequest0"), Soap12FaultCodes.ReceiverFaultCode);
                }
                throw new SoapException(System.Web.Services.Res.GetString("TheRequestElementXmlnsWasNotRecognized2", new object[] { empty.Name, empty.Namespace }), Soap12FaultCodes.SenderFaultCode);
            }
            throw new SoapException(System.Web.Services.Res.GetString("UnableToHandleRequestActionNotRecognized1", new object[] { action }), Soap12FaultCodes.SenderFaultCode);
        }
        /// <summary>
        /// Gets a resource permissions.
        /// </summary>
        /// <param name='resourceGroupName'>
        /// Required. The name of the resource group. The name is case
        /// insensitive.
        /// </param>
        /// <param name='identity'>
        /// Required. Resource
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// Permissions information.
        /// </returns>
        public async Task <PermissionGetResult> ListForResourceAsync(string resourceGroupName, ResourceIdentity identity, CancellationToken cancellationToken)
        {
            // Validate
            if (resourceGroupName == null)
            {
                throw new ArgumentNullException("resourceGroupName");
            }
            if (identity == null)
            {
                throw new ArgumentNullException("identity");
            }
            if (identity.ResourceName == null)
            {
                throw new ArgumentNullException("identity.ResourceName");
            }
            if (identity.ResourceProviderNamespace == null)
            {
                throw new ArgumentNullException("identity.ResourceProviderNamespace");
            }
            if (identity.ResourceType == null)
            {
                throw new ArgumentNullException("identity.ResourceType");
            }

            // Tracing
            bool   shouldTrace  = CloudContext.Configuration.Tracing.IsEnabled;
            string invocationId = null;

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

            // Construct URL
            string url = "/subscriptions/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/resourcegroups/" + resourceGroupName.Trim() + "/providers/" + identity.ResourceProviderNamespace.Trim() + "/" + (identity.ParentResourcePath != null ? identity.ParentResourcePath.Trim() : "") + "/" + identity.ResourceType.Trim() + "/" + identity.ResourceName.Trim() + "/providers/Microsoft.Authorization/permissions?";

            url = url + "api-version=2014-07-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.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)
                    {
                        Tracing.SendRequest(invocationId, httpRequest);
                    }
                    cancellationToken.ThrowIfCancellationRequested();
                    httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);

                    if (shouldTrace)
                    {
                        Tracing.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)
                        {
                            Tracing.Error(invocationId, ex);
                        }
                        throw ex;
                    }

                    // Create Result
                    PermissionGetResult result = null;
                    // Deserialize Response
                    cancellationToken.ThrowIfCancellationRequested();
                    string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                    result = new PermissionGetResult();
                    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))
                            {
                                Permission permissionInstance = new Permission();
                                result.Permissions.Add(permissionInstance);

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

                                JToken notActionsArray = valueValue["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)
                    {
                        Tracing.Exit(invocationId, result);
                    }
                    return(result);
                }
                finally
                {
                    if (httpResponse != null)
                    {
                        httpResponse.Dispose();
                    }
                }
            }
            finally
            {
                if (httpRequest != null)
                {
                    httpRequest.Dispose();
                }
            }
        }
Esempio n. 20
0
        /// <summary>
        /// The Get Client Root Certificate operation returns the public
        /// portion of a previously uploaded client root certificate in a
        /// base-64-encoded format from Azure.  (see
        /// http://msdn.microsoft.com/en-us/library/windowsazure/dn205127.aspx
        /// for more information)
        /// </summary>
        /// <param name='networkName'>
        /// Required. The name of the virtual network for this gateway.
        /// </param>
        /// <param name='certificateThumbprint'>
        /// Required. The X509 certificate thumbprint.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// Response to the Get Client Root Certificate operation.
        /// </returns>
        public async System.Threading.Tasks.Task <Microsoft.WindowsAzure.Management.Network.Models.ClientRootCertificateGetResponse> GetAsync(string networkName, string certificateThumbprint, CancellationToken cancellationToken)
        {
            // Validate
            if (networkName == null)
            {
                throw new ArgumentNullException("networkName");
            }
            if (certificateThumbprint == null)
            {
                throw new ArgumentNullException("certificateThumbprint");
            }

            // Tracing
            bool   shouldTrace  = CloudContext.Configuration.Tracing.IsEnabled;
            string invocationId = null;

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

            // Construct URL
            string baseUrl = this.Client.BaseUri.AbsoluteUri;
            string url     = "/" + this.Client.Credentials.SubscriptionId.Trim() + "/services/networking/" + networkName.Trim() + "/gateway/clientrootcertificates/" + certificateThumbprint.Trim();

            // 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;

            // 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-11-01");

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

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

                    if (shouldTrace)
                    {
                        Tracing.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), CloudExceptionType.Xml);
                        if (shouldTrace)
                        {
                            Tracing.Error(invocationId, ex);
                        }
                        throw ex;
                    }

                    // Create Result
                    ClientRootCertificateGetResponse result = null;
                    // Deserialize Response
                    cancellationToken.ThrowIfCancellationRequested();
                    string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                    result             = new ClientRootCertificateGetResponse();
                    result.Certificate = responseContent;

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

                    if (shouldTrace)
                    {
                        Tracing.Exit(invocationId, result);
                    }
                    return(result);
                }
                finally
                {
                    if (httpResponse != null)
                    {
                        httpResponse.Dispose();
                    }
                }
            }
            finally
            {
                if (httpRequest != null)
                {
                    httpRequest.Dispose();
                }
            }
        }
Esempio n. 21
0
        /// <summary>
        /// Gets a gallery items.
        /// </summary>
        /// <param name='itemIdentity'>
        /// Required. Gallery item identity.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// Gallery item information.
        /// </returns>
        public async Task <ItemGetParameters> GetAsync(string itemIdentity, CancellationToken cancellationToken)
        {
            // Validate

            // Tracing
            bool   shouldTrace  = CloudContext.Configuration.Tracing.IsEnabled;
            string invocationId = null;

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

            // Construct URL
            string baseUrl = this.Client.BaseUri.AbsoluteUri;
            string url     = "/Microsoft.Gallery/galleryitems/" + (itemIdentity != null ? itemIdentity.Trim() : "");

            // 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;

            // 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)
                    {
                        Tracing.SendRequest(invocationId, httpRequest);
                    }
                    cancellationToken.ThrowIfCancellationRequested();
                    httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);

                    if (shouldTrace)
                    {
                        Tracing.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)
                        {
                            Tracing.Error(invocationId, ex);
                        }
                        throw ex;
                    }

                    // Create Result
                    ItemGetParameters result = null;
                    // Deserialize Response
                    cancellationToken.ThrowIfCancellationRequested();
                    string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

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

                    if (responseDoc != null && responseDoc.Type != JTokenType.Null)
                    {
                        GalleryItem itemInstance = new GalleryItem();
                        result.Item = itemInstance;

                        JToken identityValue = responseDoc["identity"];
                        if (identityValue != null && identityValue.Type != JTokenType.Null)
                        {
                            string identityInstance = ((string)identityValue);
                            itemInstance.Identity = identityInstance;
                        }

                        JToken itemNameValue = responseDoc["itemName"];
                        if (itemNameValue != null && itemNameValue.Type != JTokenType.Null)
                        {
                            string itemNameInstance = ((string)itemNameValue);
                            itemInstance.Name = itemNameInstance;
                        }

                        JToken itemDisplayNameValue = responseDoc["itemDisplayName"];
                        if (itemDisplayNameValue != null && itemDisplayNameValue.Type != JTokenType.Null)
                        {
                            string itemDisplayNameInstance = ((string)itemDisplayNameValue);
                            itemInstance.DisplayName = itemDisplayNameInstance;
                        }

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

                        JToken publisherDisplayNameValue = responseDoc["publisherDisplayName"];
                        if (publisherDisplayNameValue != null && publisherDisplayNameValue.Type != JTokenType.Null)
                        {
                            string publisherDisplayNameInstance = ((string)publisherDisplayNameValue);
                            itemInstance.PublisherDisplayName = publisherDisplayNameInstance;
                        }

                        JToken versionValue = responseDoc["version"];
                        if (versionValue != null && versionValue.Type != JTokenType.Null)
                        {
                            string versionInstance = ((string)versionValue);
                            itemInstance.Version = versionInstance;
                        }

                        JToken summaryValue = responseDoc["summary"];
                        if (summaryValue != null && summaryValue.Type != JTokenType.Null)
                        {
                            string summaryInstance = ((string)summaryValue);
                            itemInstance.Summary = summaryInstance;
                        }

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

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

                        JToken definitionTemplatesValue = responseDoc["definitionTemplates"];
                        if (definitionTemplatesValue != null && definitionTemplatesValue.Type != JTokenType.Null)
                        {
                            DefinitionTemplates definitionTemplatesInstance = new DefinitionTemplates();
                            itemInstance.DefinitionTemplates = definitionTemplatesInstance;

                            JToken uiDefinitionFileUrlValue = definitionTemplatesValue["uiDefinitionFileUrl"];
                            if (uiDefinitionFileUrlValue != null && uiDefinitionFileUrlValue.Type != JTokenType.Null)
                            {
                                string uiDefinitionFileUrlInstance = ((string)uiDefinitionFileUrlValue);
                                definitionTemplatesInstance.UiDefinitionFileUrl = uiDefinitionFileUrlInstance;
                            }

                            JToken defaultDeploymentTemplateIdValue = definitionTemplatesValue["defaultDeploymentTemplateId"];
                            if (defaultDeploymentTemplateIdValue != null && defaultDeploymentTemplateIdValue.Type != JTokenType.Null)
                            {
                                string defaultDeploymentTemplateIdInstance = ((string)defaultDeploymentTemplateIdValue);
                                definitionTemplatesInstance.DefaultDeploymentTemplateId = defaultDeploymentTemplateIdInstance;
                            }

                            JToken deploymentTemplateFileUrlsSequenceElement = ((JToken)definitionTemplatesValue["deploymentTemplateFileUrls"]);
                            if (deploymentTemplateFileUrlsSequenceElement != null && deploymentTemplateFileUrlsSequenceElement.Type != JTokenType.Null)
                            {
                                foreach (JProperty property in deploymentTemplateFileUrlsSequenceElement)
                                {
                                    string deploymentTemplateFileUrlsKey   = ((string)property.Name);
                                    string deploymentTemplateFileUrlsValue = ((string)property.Value);
                                    definitionTemplatesInstance.DeploymentTemplateFileUrls.Add(deploymentTemplateFileUrlsKey, deploymentTemplateFileUrlsValue);
                                }
                            }
                        }

                        JToken categoryIdsArray = responseDoc["categoryIds"];
                        if (categoryIdsArray != null && categoryIdsArray.Type != JTokenType.Null)
                        {
                            foreach (JToken categoryIdsValue in ((JArray)categoryIdsArray))
                            {
                                itemInstance.CategoryIds.Add(((string)categoryIdsValue));
                            }
                        }

                        JToken screenshotUrlsArray = responseDoc["screenshotUrls"];
                        if (screenshotUrlsArray != null && screenshotUrlsArray.Type != JTokenType.Null)
                        {
                            foreach (JToken screenshotUrlsValue in ((JArray)screenshotUrlsArray))
                            {
                                itemInstance.ScreenshotUrls.Add(((string)screenshotUrlsValue));
                            }
                        }

                        JToken iconFileUrlsSequenceElement = ((JToken)responseDoc["iconFileUrls"]);
                        if (iconFileUrlsSequenceElement != null && iconFileUrlsSequenceElement.Type != JTokenType.Null)
                        {
                            foreach (JProperty property2 in iconFileUrlsSequenceElement)
                            {
                                string iconFileUrlsKey   = ((string)property2.Name);
                                string iconFileUrlsValue = ((string)property2.Value);
                                itemInstance.IconFileUrls.Add(iconFileUrlsKey, iconFileUrlsValue);
                            }
                        }
                    }

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

                    if (shouldTrace)
                    {
                        Tracing.Exit(invocationId, result);
                    }
                    return(result);
                }
                finally
                {
                    if (httpResponse != null)
                    {
                        httpResponse.Dispose();
                    }
                }
            }
            finally
            {
                if (httpRequest != null)
                {
                    httpRequest.Dispose();
                }
            }
        }
Esempio n. 22
0
        /// <summary>
        /// The List Client Root Certificates operation returns a list of all
        /// the client root certificates that are associated with the
        /// specified virtual network in Azure.  (see
        /// http://msdn.microsoft.com/en-us/library/windowsazure/dn205130.aspx
        /// for more information)
        /// </summary>
        /// <param name='networkName'>
        /// Required. The name of the virtual network for this gateway.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// The response for the List Client Root Certificates operation.
        /// </returns>
        public async System.Threading.Tasks.Task <Microsoft.WindowsAzure.Management.Network.Models.ClientRootCertificateListResponse> ListAsync(string networkName, CancellationToken cancellationToken)
        {
            // Validate
            if (networkName == null)
            {
                throw new ArgumentNullException("networkName");
            }

            // Tracing
            bool   shouldTrace  = CloudContext.Configuration.Tracing.IsEnabled;
            string invocationId = null;

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

            // Construct URL
            string baseUrl = this.Client.BaseUri.AbsoluteUri;
            string url     = "/" + this.Client.Credentials.SubscriptionId.Trim() + "/services/networking/" + networkName.Trim() + "/gateway/clientrootcertificates";

            // 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;

            // 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-11-01");

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

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

                    if (shouldTrace)
                    {
                        Tracing.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), CloudExceptionType.Xml);
                        if (shouldTrace)
                        {
                            Tracing.Error(invocationId, ex);
                        }
                        throw ex;
                    }

                    // Create Result
                    ClientRootCertificateListResponse result = null;
                    // Deserialize Response
                    cancellationToken.ThrowIfCancellationRequested();
                    string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

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

                    XElement clientRootCertificatesSequenceElement = responseDoc.Element(XName.Get("ClientRootCertificates", "http://schemas.microsoft.com/windowsazure"));
                    if (clientRootCertificatesSequenceElement != null && clientRootCertificatesSequenceElement.IsEmpty == false)
                    {
                        foreach (XElement clientRootCertificatesElement in clientRootCertificatesSequenceElement.Elements(XName.Get("ClientRootCertificate", "http://schemas.microsoft.com/windowsazure")))
                        {
                            ClientRootCertificateListResponse.ClientRootCertificate clientRootCertificateInstance = new ClientRootCertificateListResponse.ClientRootCertificate();
                            result.ClientRootCertificates.Add(clientRootCertificateInstance);

                            XElement expirationTimeElement = clientRootCertificatesElement.Element(XName.Get("ExpirationTime", "http://schemas.microsoft.com/windowsazure"));
                            if (expirationTimeElement != null && expirationTimeElement.IsEmpty == false)
                            {
                                DateTime expirationTimeInstance = DateTime.Parse(expirationTimeElement.Value, CultureInfo.InvariantCulture);
                                clientRootCertificateInstance.ExpirationTime = expirationTimeInstance;
                            }

                            XElement subjectElement = clientRootCertificatesElement.Element(XName.Get("Subject", "http://schemas.microsoft.com/windowsazure"));
                            if (subjectElement != null && subjectElement.IsEmpty == false)
                            {
                                string subjectInstance = subjectElement.Value;
                                clientRootCertificateInstance.Subject = subjectInstance;
                            }

                            XElement thumbprintElement = clientRootCertificatesElement.Element(XName.Get("Thumbprint", "http://schemas.microsoft.com/windowsazure"));
                            if (thumbprintElement != null && thumbprintElement.IsEmpty == false)
                            {
                                string thumbprintInstance = thumbprintElement.Value;
                                clientRootCertificateInstance.Thumbprint = thumbprintInstance;
                            }
                        }
                    }

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

                    if (shouldTrace)
                    {
                        Tracing.Exit(invocationId, result);
                    }
                    return(result);
                }
                finally
                {
                    if (httpResponse != null)
                    {
                        httpResponse.Dispose();
                    }
                }
            }
            finally
            {
                if (httpRequest != null)
                {
                    httpRequest.Dispose();
                }
            }
        }
        /// <summary>
        /// The New Dedicated Circuit operation creates a new dedicated circuit.
        /// </summary>
        /// <param name='parameters'>
        /// Required. Parameters supplied to the Create Virtual Network Gateway
        /// operation.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// The Get Dedicated Circuit operation response.
        /// </returns>
        public async System.Threading.Tasks.Task <Microsoft.WindowsAzure.Management.ExpressRoute.Models.DedicatedCircuitGetResponse> NewAsync(DedicatedCircuitNewParameters parameters, CancellationToken cancellationToken)
        {
            ExpressRouteManagementClient client = this.Client;
            bool   shouldTrace  = CloudContext.Configuration.Tracing.IsEnabled;
            string invocationId = null;

            if (shouldTrace)
            {
                invocationId = Tracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("parameters", parameters);
                Tracing.Enter(invocationId, this, "NewAsync", tracingParameters);
            }
            try
            {
                if (shouldTrace)
                {
                    client = this.Client.WithHandler(new ClientRequestTrackingHandler(invocationId));
                }

                cancellationToken.ThrowIfCancellationRequested();
                ExpressRouteOperationResponse originalResponse = await client.DedicatedCircuit.BeginNewAsync(parameters, cancellationToken).ConfigureAwait(false);

                cancellationToken.ThrowIfCancellationRequested();
                ExpressRouteOperationStatusResponse result = await client.GetOperationStatusAsync(originalResponse.OperationId, cancellationToken).ConfigureAwait(false);

                int delayInSeconds = 30;
                while (result.Status == ExpressRouteOperationStatus.InProgress)
                {
                    cancellationToken.ThrowIfCancellationRequested();
                    await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false);

                    cancellationToken.ThrowIfCancellationRequested();
                    result = await client.GetOperationStatusAsync(originalResponse.OperationId, cancellationToken).ConfigureAwait(false);

                    delayInSeconds = 10;
                }

                if (result.Status == ExpressRouteOperationStatus.Failed)
                {
                    string exStr = "A new dedicated circuit could not be created due to an internal server error.";
                    throw new ArgumentException(exStr);
                }
                cancellationToken.ThrowIfCancellationRequested();
                DedicatedCircuitGetResponse getResult = await client.DedicatedCircuit.GetAsync(result.Data, cancellationToken).ConfigureAwait(false);

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

                return(getResult);
            }
            finally
            {
                if (client != null && shouldTrace)
                {
                    client.Dispose();
                }
            }
        }
Esempio n. 24
0
        /// <summary>
        /// Retrieves the list of regions that support the creation and
        /// management of Service Bus service namespaces.  (see
        /// http://msdn.microsoft.com/en-us/library/windowsazure/jj860465.aspx
        /// for more information)
        /// </summary>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// A response to a request for a list of regions.
        /// </returns>
        public async System.Threading.Tasks.Task <Microsoft.WindowsAzure.Management.ServiceBus.Models.ServiceBusRegionsResponse> GetServiceBusRegionsAsync(CancellationToken cancellationToken)
        {
            // Validate

            // Tracing
            bool   shouldTrace  = CloudContext.Configuration.Tracing.IsEnabled;
            string invocationId = null;

            if (shouldTrace)
            {
                invocationId = Tracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                Tracing.Enter(invocationId, this, "GetServiceBusRegionsAsync", tracingParameters);
            }

            // Construct URL
            string url = new Uri(this.BaseUri, "/").ToString() + this.Credentials.SubscriptionId + "/services/servicebus/regions";

            // 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/atom+xml");
                httpRequest.Headers.Add("x-ms-version", "2013-08-01");

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

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

                    if (shouldTrace)
                    {
                        Tracing.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), CloudExceptionType.Xml);
                        if (shouldTrace)
                        {
                            Tracing.Error(invocationId, ex);
                        }
                        throw ex;
                    }

                    // Create Result
                    ServiceBusRegionsResponse result = null;
                    // Deserialize Response
                    cancellationToken.ThrowIfCancellationRequested();
                    string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                    result = new ServiceBusRegionsResponse();
                    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")))
                            {
                                ServiceBusLocation entryInstance = new ServiceBusLocation();
                                result.Regions.Add(entryInstance);

                                XElement contentElement = entriesElement.Element(XName.Get("content", "http://www.w3.org/2005/Atom"));
                                if (contentElement != null)
                                {
                                    XElement regionCodeDescriptionElement = contentElement.Element(XName.Get("RegionCodeDescription", "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect"));
                                    if (regionCodeDescriptionElement != null)
                                    {
                                        XElement codeElement = regionCodeDescriptionElement.Element(XName.Get("Code", "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect"));
                                        if (codeElement != null)
                                        {
                                            string codeInstance = codeElement.Value;
                                            entryInstance.Code = codeInstance;
                                        }

                                        XElement fullNameElement = regionCodeDescriptionElement.Element(XName.Get("FullName", "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect"));
                                        if (fullNameElement != null)
                                        {
                                            string fullNameInstance = fullNameElement.Value;
                                            entryInstance.FullName = fullNameInstance;
                                        }
                                    }
                                }
                            }
                        }
                    }

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

                    if (shouldTrace)
                    {
                        Tracing.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 System.Threading.Tasks.Task <OperationStatusResponse> CreateAsync(CloudServiceCreateParameters parameters, CancellationToken cancellationToken)
        {
            StoreManagementClient client = this.Client;
            bool   shouldTrace           = CloudContext.Configuration.Tracing.IsEnabled;
            string invocationId          = null;

            if (shouldTrace)
            {
                invocationId = Tracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("parameters", parameters);
                Tracing.Enter(invocationId, this, "CreateAsync", tracingParameters);
            }
            try
            {
                if (shouldTrace)
                {
                    client = this.Client.WithHandler(new ClientRequestTrackingHandler(invocationId));
                }

                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)
                {
                    Tracing.Exit(invocationId, result);
                }

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

                return(result);
            }
            finally
            {
                if (client != null && shouldTrace)
                {
                    client.Dispose();
                }
            }
        }
Esempio n. 26
0
        /// <summary>
        /// The Get Dedicated Circuit Link operation retrieves the specified
        /// dedicated circuit link.
        /// </summary>
        /// <param name='serviceKey'>
        /// Required. The service key representing the circuit.
        /// </param>
        /// <param name='vnetName'>
        /// Required.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// The Get Dedicated Circuit Link operation response.
        /// </returns>
        public async System.Threading.Tasks.Task <Microsoft.WindowsAzure.Management.ExpressRoute.Models.DedicatedCircuitLinkGetResponse> GetAsync(string serviceKey, string vnetName, CancellationToken cancellationToken)
        {
            // Validate
            if (serviceKey == null)
            {
                throw new ArgumentNullException("serviceKey");
            }
            if (vnetName == null)
            {
                throw new ArgumentNullException("vnetName");
            }

            // Tracing
            bool   shouldTrace  = CloudContext.Configuration.Tracing.IsEnabled;
            string invocationId = null;

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

            // Construct URL
            string baseUrl = this.Client.BaseUri.AbsoluteUri;
            string url     = "/" + this.Client.Credentials.SubscriptionId.Trim() + "/services/networking/dedicatedcircuits/" + serviceKey.Trim() + "/vnets/" + vnetName.Trim() + "?api-version=1.0";

            // 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;

            // 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", "2011-10-01");

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

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

                    if (shouldTrace)
                    {
                        Tracing.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), CloudExceptionType.Xml);
                        if (shouldTrace)
                        {
                            Tracing.Error(invocationId, ex);
                        }
                        throw ex;
                    }

                    // Create Result
                    DedicatedCircuitLinkGetResponse result = null;
                    // Deserialize Response
                    cancellationToken.ThrowIfCancellationRequested();
                    string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

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

                    XElement dedicatedCircuitLinkElement = responseDoc.Element(XName.Get("DedicatedCircuitLink", "http://schemas.microsoft.com/windowsazure"));
                    if (dedicatedCircuitLinkElement != null && dedicatedCircuitLinkElement.IsEmpty == false)
                    {
                        AzureDedicatedCircuitLink dedicatedCircuitLinkInstance = new AzureDedicatedCircuitLink();
                        result.DedicatedCircuitLink = dedicatedCircuitLinkInstance;

                        XElement stateElement = dedicatedCircuitLinkElement.Element(XName.Get("State", "http://schemas.microsoft.com/windowsazure"));
                        if (stateElement != null && stateElement.IsEmpty == false)
                        {
                            DedicatedCircuitLinkState stateInstance = ((DedicatedCircuitLinkState)Enum.Parse(typeof(DedicatedCircuitLinkState), stateElement.Value, true));
                            dedicatedCircuitLinkInstance.State = stateInstance;
                        }

                        XElement vnetNameElement = dedicatedCircuitLinkElement.Element(XName.Get("VnetName", "http://schemas.microsoft.com/windowsazure"));
                        if (vnetNameElement != null && vnetNameElement.IsEmpty == false)
                        {
                            string vnetNameInstance = vnetNameElement.Value;
                            dedicatedCircuitLinkInstance.VnetName = vnetNameInstance;
                        }
                    }

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

                    if (shouldTrace)
                    {
                        Tracing.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 System.Threading.Tasks.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  = CloudContext.Configuration.Tracing.IsEnabled;
            string invocationId = null;

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

            // Construct URL
            string url     = "/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/CloudServices/" + parameters.Name.Trim() + "/";
            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         = new MediaTypeHeaderValue("application/xml");
                httpRequest.Content.Headers.ContentType.CharSet = "utf-8";

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

                    if (shouldTrace)
                    {
                        Tracing.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)
                        {
                            Tracing.Error(invocationId, ex);
                        }
                        throw ex;
                    }

                    // Create Result
                    OperationStatusResponse result = null;
                    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)
                    {
                        Tracing.Exit(invocationId, result);
                    }
                    return(result);
                }
                finally
                {
                    if (httpResponse != null)
                    {
                        httpResponse.Dispose();
                    }
                }
            }
            finally
            {
                if (httpRequest != null)
                {
                    httpRequest.Dispose();
                }
            }
        }
Esempio n. 28
0
        internal SoapClientType(Type type)
        {
            this.binding = WebServiceBindingReflector.GetAttribute(type);
            if (this.binding == null)
            {
                throw new InvalidOperationException(Res.GetString("WebClientBindingAttributeRequired"));
            }
            this.serviceNamespace        = this.binding.Namespace;
            this.serviceDefaultIsEncoded = SoapReflector.ServiceDefaultIsEncoded(type);
            ArrayList soapMethodList = new ArrayList();
            ArrayList mappings       = new ArrayList();

            GenerateXmlMappings(type, soapMethodList, this.serviceNamespace, this.serviceDefaultIsEncoded, mappings);
            XmlMapping[] mappingArray = (XmlMapping[])mappings.ToArray(typeof(XmlMapping));
            TraceMethod  caller       = Tracing.On ? new TraceMethod(this, ".ctor", new object[] { type }) : null;

            if (Tracing.On)
            {
                Tracing.Enter(Tracing.TraceId("TraceCreateSerializer"), caller, new TraceMethod(typeof(XmlSerializer), "FromMappings", new object[] { mappingArray, type }));
            }
            XmlSerializer[] serializerArray = XmlSerializer.FromMappings(mappingArray, type);
            if (Tracing.On)
            {
                Tracing.Exit(Tracing.TraceId("TraceCreateSerializer"), caller);
            }
            SoapExtensionTypeElementCollection soapExtensionTypes = WebServicesSection.Current.SoapExtensionTypes;
            ArrayList list3 = new ArrayList();
            ArrayList list4 = new ArrayList();

            for (int i = 0; i < soapExtensionTypes.Count; i++)
            {
                SoapExtensionTypeElement element1  = soapExtensionTypes[i];
                SoapReflectedExtension   extension = new SoapReflectedExtension(soapExtensionTypes[i].Type, null, soapExtensionTypes[i].Priority);
                if (soapExtensionTypes[i].Group == PriorityGroup.High)
                {
                    list3.Add(extension);
                }
                else
                {
                    list4.Add(extension);
                }
            }
            this.HighPriExtensions = (SoapReflectedExtension[])list3.ToArray(typeof(SoapReflectedExtension));
            this.LowPriExtensions  = (SoapReflectedExtension[])list4.ToArray(typeof(SoapReflectedExtension));
            Array.Sort <SoapReflectedExtension>(this.HighPriExtensions);
            Array.Sort <SoapReflectedExtension>(this.LowPriExtensions);
            this.HighPriExtensionInitializers = SoapReflectedExtension.GetInitializers(type, this.HighPriExtensions);
            this.LowPriExtensionInitializers  = SoapReflectedExtension.GetInitializers(type, this.LowPriExtensions);
            int num2 = 0;

            for (int j = 0; j < soapMethodList.Count; j++)
            {
                SoapReflectedMethod method2 = (SoapReflectedMethod)soapMethodList[j];
                SoapClientMethod    method3 = new SoapClientMethod {
                    parameterSerializer = serializerArray[num2++]
                };
                if (method2.responseMappings != null)
                {
                    method3.returnSerializer = serializerArray[num2++];
                }
                method3.inHeaderSerializer = serializerArray[num2++];
                if (method2.outHeaderMappings != null)
                {
                    method3.outHeaderSerializer = serializerArray[num2++];
                }
                method3.action                = method2.action;
                method3.oneWay                = method2.oneWay;
                method3.rpc                   = method2.rpc;
                method3.use                   = method2.use;
                method3.paramStyle            = method2.paramStyle;
                method3.methodInfo            = method2.methodInfo;
                method3.extensions            = method2.extensions;
                method3.extensionInitializers = SoapReflectedExtension.GetInitializers(method3.methodInfo, method2.extensions);
                ArrayList list5 = new ArrayList();
                ArrayList list6 = new ArrayList();
                for (int k = 0; k < method2.headers.Length; k++)
                {
                    SoapHeaderMapping   mapping = new SoapHeaderMapping();
                    SoapReflectedHeader header  = method2.headers[k];
                    mapping.memberInfo = header.memberInfo;
                    mapping.repeats    = header.repeats;
                    mapping.custom     = header.custom;
                    mapping.direction  = header.direction;
                    mapping.headerType = header.headerType;
                    if ((mapping.direction & SoapHeaderDirection.In) != 0)
                    {
                        list5.Add(mapping);
                    }
                    if ((mapping.direction & (SoapHeaderDirection.Fault | SoapHeaderDirection.Out)) != 0)
                    {
                        list6.Add(mapping);
                    }
                }
                method3.inHeaderMappings = (SoapHeaderMapping[])list5.ToArray(typeof(SoapHeaderMapping));
                if (method3.outHeaderSerializer != null)
                {
                    method3.outHeaderMappings = (SoapHeaderMapping[])list6.ToArray(typeof(SoapHeaderMapping));
                }
                this.methods.Add(method2.name, method3);
            }
        }
Esempio n. 29
0
        /// <summary>
        /// Begins deleting a resource group.
        /// </summary>
        /// <param name='resourceGroupName'>
        /// Required. The name of the resource group.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// A standard service response including an HTTP status code and
        /// request ID.
        /// </returns>
        public async Task <OperationResponse> BeginDeletingResourceGroupAsync(string resourceGroupName, CancellationToken cancellationToken)
        {
            // Validate
            if (resourceGroupName == null)
            {
                throw new ArgumentNullException("resourceGroupName");
            }

            // Tracing
            bool   shouldTrace  = CloudContext.Configuration.Tracing.IsEnabled;
            string invocationId = null;

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

            // Construct URL
            string url = "/subscriptions/" + (this.Credentials.SubscriptionId != null ? this.Credentials.SubscriptionId.Trim() : "") + "/resourcegroups/" + resourceGroupName.Trim() + "?";

            url = url + "api-version=2014-04-01";
            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.Delete;
                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)
                    {
                        Tracing.SendRequest(invocationId, httpRequest);
                    }
                    cancellationToken.ThrowIfCancellationRequested();
                    httpResponse = await this.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);

                    if (shouldTrace)
                    {
                        Tracing.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)
                        {
                            Tracing.Error(invocationId, ex);
                        }
                        throw ex;
                    }

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

                    if (shouldTrace)
                    {
                        Tracing.Exit(invocationId, result);
                    }
                    return(result);
                }
                finally
                {
                    if (httpResponse != null)
                    {
                        httpResponse.Dispose();
                    }
                }
            }
            finally
            {
                if (httpRequest != null)
                {
                    httpRequest.Dispose();
                }
            }
        }
Esempio n. 30
0
        /// <summary>
        /// Returns information about a specific operation by using the
        /// operation Guid.
        /// </summary>
        /// <param name='serverName'>
        /// Required. The name of the Azure SQL Database Server where the
        /// database is hosted.
        /// </param>
        /// <param name='operationGuid'>
        /// Required. The Guid of the Azure SQL Database operation to be
        /// obtained.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// Represents the database operation for a given operation Guid.
        /// </returns>
        public async System.Threading.Tasks.Task <Microsoft.WindowsAzure.Management.Sql.Models.DatabaseOperationGetResponse> GetAsync(string serverName, string operationGuid, CancellationToken cancellationToken)
        {
            // Validate
            if (serverName == null)
            {
                throw new ArgumentNullException("serverName");
            }
            if (operationGuid == null)
            {
                throw new ArgumentNullException("operationGuid");
            }

            // Tracing
            bool   shouldTrace  = CloudContext.Configuration.Tracing.IsEnabled;
            string invocationId = null;

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

            // Construct URL
            string url     = Uri.EscapeDataString(this.Client.Credentials.SubscriptionId) + "/services/sqlservers/servers/" + Uri.EscapeDataString(serverName) + "/databaseoperations/" + Uri.EscapeDataString(operationGuid);
            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", "2012-03-01");

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

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

                    if (shouldTrace)
                    {
                        Tracing.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)
                        {
                            Tracing.Error(invocationId, ex);
                        }
                        throw ex;
                    }

                    // Create Result
                    DatabaseOperationGetResponse result = null;
                    // Deserialize Response
                    cancellationToken.ThrowIfCancellationRequested();
                    string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

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

                    XElement serviceResourceElement = responseDoc.Element(XName.Get("ServiceResource", "http://schemas.microsoft.com/windowsazure"));
                    if (serviceResourceElement != null)
                    {
                        DatabaseOperation serviceResourceInstance = new DatabaseOperation();
                        result.DatabaseOperation = serviceResourceInstance;

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

                        XElement stateIdElement = serviceResourceElement.Element(XName.Get("StateId", "http://schemas.microsoft.com/windowsazure"));
                        if (stateIdElement != null)
                        {
                            int stateIdInstance = int.Parse(stateIdElement.Value, CultureInfo.InvariantCulture);
                            serviceResourceInstance.StateId = stateIdInstance;
                        }

                        XElement sessionActivityIdElement = serviceResourceElement.Element(XName.Get("SessionActivityId", "http://schemas.microsoft.com/windowsazure"));
                        if (sessionActivityIdElement != null)
                        {
                            string sessionActivityIdInstance = sessionActivityIdElement.Value;
                            serviceResourceInstance.SessionActivityId = sessionActivityIdInstance;
                        }

                        XElement databaseNameElement = serviceResourceElement.Element(XName.Get("DatabaseName", "http://schemas.microsoft.com/windowsazure"));
                        if (databaseNameElement != null)
                        {
                            string databaseNameInstance = databaseNameElement.Value;
                            serviceResourceInstance.DatabaseName = databaseNameInstance;
                        }

                        XElement percentCompleteElement = serviceResourceElement.Element(XName.Get("PercentComplete", "http://schemas.microsoft.com/windowsazure"));
                        if (percentCompleteElement != null)
                        {
                            int percentCompleteInstance = int.Parse(percentCompleteElement.Value, CultureInfo.InvariantCulture);
                            serviceResourceInstance.PercentComplete = percentCompleteInstance;
                        }

                        XElement errorCodeElement = serviceResourceElement.Element(XName.Get("ErrorCode", "http://schemas.microsoft.com/windowsazure"));
                        if (errorCodeElement != null)
                        {
                            int errorCodeInstance = int.Parse(errorCodeElement.Value, CultureInfo.InvariantCulture);
                            serviceResourceInstance.ErrorCode = errorCodeInstance;
                        }

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

                        XElement errorSeverityElement = serviceResourceElement.Element(XName.Get("ErrorSeverity", "http://schemas.microsoft.com/windowsazure"));
                        if (errorSeverityElement != null)
                        {
                            int errorSeverityInstance = int.Parse(errorSeverityElement.Value, CultureInfo.InvariantCulture);
                            serviceResourceInstance.ErrorSeverity = errorSeverityInstance;
                        }

                        XElement errorStateElement = serviceResourceElement.Element(XName.Get("ErrorState", "http://schemas.microsoft.com/windowsazure"));
                        if (errorStateElement != null)
                        {
                            int errorStateInstance = int.Parse(errorStateElement.Value, CultureInfo.InvariantCulture);
                            serviceResourceInstance.ErrorState = errorStateInstance;
                        }

                        XElement startTimeElement = serviceResourceElement.Element(XName.Get("StartTime", "http://schemas.microsoft.com/windowsazure"));
                        if (startTimeElement != null)
                        {
                            DateTime startTimeInstance = DateTime.Parse(startTimeElement.Value, CultureInfo.InvariantCulture);
                            serviceResourceInstance.StartTime = startTimeInstance;
                        }

                        XElement lastModifyTimeElement = serviceResourceElement.Element(XName.Get("LastModifyTime", "http://schemas.microsoft.com/windowsazure"));
                        if (lastModifyTimeElement != null)
                        {
                            DateTime lastModifyTimeInstance = DateTime.Parse(lastModifyTimeElement.Value, CultureInfo.InvariantCulture);
                            serviceResourceInstance.LastModifyTime = lastModifyTimeInstance;
                        }

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

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

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

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

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