Exemple #1
0
        public static void _update_pl_tracing(IBaseUnit sprite, Tracing trace, int frang, int trang, int cur_clock_tm)
        {
            bool can_reach = true;

            IMapUnit pl = sprite.get_pack_data();

            if (trace.trace_tm_left > 0 || cur_clock_tm - sprite.last_trace_target_tm > 500)
            {

            }
        }
        // Constructor.
        public CommandSettings(IHostContext context, string[] args)
        {
            ArgUtil.NotNull(context, nameof(context));
            _context = context;
            _promptManager = context.GetService<IPromptManager>();
            _trace = context.GetTrace(nameof(CommandSettings));

            // Parse the command line args.
            _parser = new CommandLineParser(
                hostContext: context,
                secretArgNames: Constants.Agent.CommandLine.Args.Secrets);
            _parser.Parse(args);
        }
Exemple #3
0
        /// <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, "/").AbsoluteUri + 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();
                }
            }
        }
Exemple #4
0
        /// <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>
        /// 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 <Microsoft.WindowsAzure.Management.Compute.Models.ComputeOperationStatusResponse> DeleteAsync(ServiceCertificateDeleteParameters parameters, CancellationToken cancellationToken)
        {
            ComputeManagementClient 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, "DeleteAsync", tracingParameters);
            }
            try
            {
                if (shouldTrace)
                {
                    client = this.Client.WithHandler(new ClientRequestTrackingHandler(invocationId));
                }

                cancellationToken.ThrowIfCancellationRequested();
                OperationResponse response = await client.ServiceCertificates.BeginDeletingAsync(parameters, cancellationToken).ConfigureAwait(false);

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

                int delayInSeconds = 30;
                while ((result.Status != ComputeOperationStatus.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 (shouldTrace)
                {
                    Tracing.Exit(invocationId, result);
                }

                if (result.Status != ComputeOperationStatus.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();
                }
            }
        }
Exemple #5
0
        public ValidatedRequest Validate(AuthorizeRequest request)
        {
            var validatedRequest = new ValidatedRequest();

            // validate request model binding
            if (request == null)
            {
                throw new AuthorizeRequestResourceOwnerException("Invalid request parameters.");
            }

            // make sure redirect uri is present
            if (string.IsNullOrWhiteSpace(request.redirect_uri))
            {
                throw new AuthorizeRequestResourceOwnerException("Missing redirect URI");
            }

            // validate client
            if (string.IsNullOrWhiteSpace(request.client_id))
            {
                throw new AuthorizeRequestResourceOwnerException("Missing client identifier");
            }


            var client = Clients.Get(request.client_id);

            if (client == null)
            {
                throw new AuthorizeRequestResourceOwnerException("Invalid client: " + request.client_id);
            }

            validatedRequest.Client = client;
            Tracing.InformationFormat("Client: {0} ({1})",
                                      validatedRequest.Client.Name,
                                      validatedRequest.Client.ClientId);

            // make sure redirect_uri is a valid uri, and in case of http is over ssl
            Uri redirectUri;

            if (Uri.TryCreate(request.redirect_uri, UriKind.Absolute, out redirectUri))
            {
                if (redirectUri.Scheme == Uri.UriSchemeHttp)
                {
                    throw new AuthorizeRequestClientException(
                              "Redirect URI not over SSL : " + request.redirect_uri,
                              new Uri(request.redirect_uri),
                              OAuth2Constants.Errors.InvalidRequest,
                              string.Empty,
                              validatedRequest.State);
                }

                // make sure redirect uri is registered with client
                if (!validatedRequest.Client.RedirectUris.Contains(request.redirect_uri))
                {
                    throw new AuthorizeRequestResourceOwnerException("Invalid redirect URI: " + request.redirect_uri);
                }

                validatedRequest.RedirectUri = request.redirect_uri;
                Tracing.InformationFormat("Redirect URI: {0}",
                                          validatedRequest.RedirectUri);
            }
            else
            {
                throw new AuthorizeRequestResourceOwnerException("Invalid redirect URI: " + request.redirect_uri);
            }

            // check state
            if (!string.IsNullOrWhiteSpace(request.state))
            {
                validatedRequest.State = request.state;
                Tracing.Information("State: " + validatedRequest.State);
            }
            else
            {
                Tracing.Information("No state supplied.");
            }

            // validate response type
            if (String.IsNullOrWhiteSpace(request.response_type))
            {
                throw new AuthorizeRequestClientException(
                          "response_type is null or empty",
                          new Uri(validatedRequest.RedirectUri),
                          OAuth2Constants.Errors.InvalidRequest,
                          string.Empty,
                          validatedRequest.State);
            }

            // check response type (only code and token are supported)
            if (!request.response_type.Equals(OAuth2Constants.ResponseTypes.Token, StringComparison.Ordinal) &&
                !request.response_type.Equals(OAuth2Constants.ResponseTypes.Code, StringComparison.Ordinal))
            {
                throw new AuthorizeRequestClientException(
                          "response_type is not token or code: " + request.response_type,
                          new Uri(validatedRequest.RedirectUri),
                          OAuth2Constants.Errors.UnsupportedResponseType,
                          string.Empty,
                          validatedRequest.State);
            }

            validatedRequest.ResponseType = request.response_type;
            Tracing.Information("Response type: " + validatedRequest.ResponseType);

            // scope is required
            if (string.IsNullOrWhiteSpace(request.scope))
            {
                throw new AuthorizeRequestClientException(
                          "Missing scope",
                          new Uri(validatedRequest.RedirectUri),
                          OAuth2Constants.Errors.InvalidScope,
                          validatedRequest.ResponseType,
                          validatedRequest.State);
            }

            // validate scopes
            if (!request.scope.StartsWith("openid"))
            {
                throw new AuthorizeRequestClientException(
                          "Invalid scope: " + request.scope,
                          new Uri(validatedRequest.RedirectUri),
                          OAuth2Constants.Errors.InvalidScope,
                          validatedRequest.ResponseType,
                          validatedRequest.State);
            }

            validatedRequest.Scopes = request.scope;

            if (request.response_type == OAuth2Constants.ResponseTypes.Code)
            {
                ValidateCodeResponseType(validatedRequest, request);
            }
            else if (request.response_type == OAuth2Constants.ResponseTypes.Token)
            {
                ValidateTokenResponseType(validatedRequest, request);
            }
            else
            {
                throw new AuthorizeRequestClientException(
                          "Invalid response_type: " + request.response_type,
                          new Uri(validatedRequest.RedirectUri),
                          OAuth2Constants.Errors.UnsupportedResponseType,
                          request.response_type,
                          validatedRequest.State);
            }

            return(validatedRequest);
        }
Exemple #6
0
        /// <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), CloudExceptionType.Json);
                        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();
                }
            }
        }
Exemple #7
0
 public Plugin()
 {
     Tracing.Trace("+--------------------------------");
     Tracing.Trace("Imgur::ctor ({0:X8})", this.GetHashCode());
 }
Exemple #8
0
 public override void Disconnect()
 {
     Tracing.Trace("Imgur::Disconnect");
     base.Disconnect();
 }
        /// <summary>
        /// The Create Store Item operation creates Windows Azure Store entries
        /// in a Windows Azure subscription.
        /// </summary>
        /// <param name='cloudServiceName'>
        /// The name of the cloud service to which this store item will be
        /// assigned.
        /// </param>
        /// <param name='resourceName'>
        /// The name of this resource.
        /// </param>
        /// <param name='addOnName'>
        /// The add on name.
        /// </param>
        /// <param name='parameters'>
        /// 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 <Microsoft.WindowsAzure.Management.Store.Models.AddOnOperationStatusResponse> BeginCreatingAsync(string cloudServiceName, string resourceName, string addOnName, AddOnCreateParameters parameters, CancellationToken cancellationToken)
        {
            // Validate
            if (cloudServiceName == null)
            {
                throw new ArgumentNullException("cloudServiceName");
            }
            if (resourceName == null)
            {
                throw new ArgumentNullException("resourceName");
            }
            if (addOnName == null)
            {
                throw new ArgumentNullException("addOnName");
            }
            if (parameters == null)
            {
                throw new ArgumentNullException("parameters");
            }
            if (parameters.Plan == null)
            {
                throw new ArgumentNullException("parameters.Plan");
            }
            if (parameters.Type == null)
            {
                throw new ArgumentNullException("parameters.Type");
            }

            // 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("cloudServiceName", cloudServiceName);
                tracingParameters.Add("resourceName", resourceName);
                tracingParameters.Add("addOnName", addOnName);
                tracingParameters.Add("parameters", parameters);
                Tracing.Enter(invocationId, this, "BeginCreatingAsync", tracingParameters);
            }

            // Construct URL
            string url = new Uri(this.Client.BaseUri, "/").ToString() + this.Client.Credentials.SubscriptionId + "/CloudServices/" + cloudServiceName + "/resources/" + parameters.Type + "/" + resourceName + "/" + addOnName;

            // 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 resourceElement = new XElement(XName.Get("Resource", "http://schemas.microsoft.com/windowsazure"));
                requestDoc.Add(resourceElement);

                XElement typeElement = new XElement(XName.Get("Type", "http://schemas.microsoft.com/windowsazure"));
                typeElement.Value = parameters.Type;
                resourceElement.Add(typeElement);

                XElement planElement = new XElement(XName.Get("Plan", "http://schemas.microsoft.com/windowsazure"));
                planElement.Value = parameters.Plan;
                resourceElement.Add(planElement);

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

                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
                    AddOnOperationStatusResponse result = null;
                    result            = new AddOnOperationStatusResponse();
                    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 Store Item operation deletes Windows Azure Store entries
        /// that re provisioned for a subscription.
        /// </summary>
        /// <param name='cloudServiceName'>
        /// The name of the cloud service to which this store item will be
        /// assigned.
        /// </param>
        /// <param name='resourceProviderNamespace'>
        /// The namespace in which this store item resides.
        /// </param>
        /// <param name='resourceProviderType'>
        /// The type of store item to be deleted.
        /// </param>
        /// <param name='resourceProviderName'>
        /// The name of this resource provider.
        /// </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 <Microsoft.WindowsAzure.Management.Store.Models.AddOnOperationStatusResponse> BeginDeletingAsync(string cloudServiceName, string resourceProviderNamespace, string resourceProviderType, string resourceProviderName, CancellationToken cancellationToken)
        {
            // Validate
            if (cloudServiceName == null)
            {
                throw new ArgumentNullException("cloudServiceName");
            }
            if (resourceProviderNamespace == null)
            {
                throw new ArgumentNullException("resourceProviderNamespace");
            }
            if (resourceProviderType == null)
            {
                throw new ArgumentNullException("resourceProviderType");
            }
            if (resourceProviderName == null)
            {
                throw new ArgumentNullException("resourceProviderName");
            }

            // 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("cloudServiceName", cloudServiceName);
                tracingParameters.Add("resourceProviderNamespace", resourceProviderNamespace);
                tracingParameters.Add("resourceProviderType", resourceProviderType);
                tracingParameters.Add("resourceProviderName", resourceProviderName);
                Tracing.Enter(invocationId, this, "BeginDeletingAsync", tracingParameters);
            }

            // Construct URL
            string url = new Uri(this.Client.BaseUri, "/").ToString() + this.Client.Credentials.SubscriptionId + "/CloudServices/" + cloudServiceName + "/resources/" + resourceProviderNamespace + "/" + resourceProviderType + "/" + resourceProviderName;

            // 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-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.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
                    AddOnOperationStatusResponse result = null;
                    result            = new AddOnOperationStatusResponse();
                    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();
                }
            }
        }
 public MemoryLayoutPacket(_DBG.BitStream stream) : base(Commands.c_Profiling_Memory_Layout)
 {
     m_heapAddress = ReadAndUnpackBits(stream);
     m_heapLength  = ReadAndUnpackBits(stream);
     Tracing.PacketTrace("layout {0}:{1}", m_heapAddress, m_heapLength);
 }
        /// <summary>
        /// The Begin Setting Network Configuration operation asynchronously
        /// configures the virtual network.  (see
        /// http://msdn.microsoft.com/en-us/library/windowsazure/jj157181.aspx
        /// for more information)
        /// </summary>
        /// <param name='parameters'>
        /// Required. Parameters supplied to the Set Network Configuration
        /// 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> BeginSettingConfigurationAsync(NetworkSetConfigurationParameters parameters, CancellationToken cancellationToken)
        {
            // Validate
            if (parameters == null)
            {
                throw new ArgumentNullException("parameters");
            }
            if (parameters.Configuration == null)
            {
                throw new ArgumentNullException("parameters.Configuration");
            }

            // 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, "BeginSettingConfigurationAsync", tracingParameters);
            }

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

            // 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.Put;
                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);

                // Serialize Request
                string requestContent = parameters.Configuration;
                httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
                httpRequest.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");

                // 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
                    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>
        /// The Set Network Configuration operation asynchronously configures
        /// the virtual network.  (see
        /// http://msdn.microsoft.com/en-us/library/windowsazure/jj157181.aspx
        /// for more information)
        /// </summary>
        /// <param name='parameters'>
        /// Required. Parameters supplied to the Set Network Configuration
        /// operation.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// The response body contains the status of the specified asynchronous
        /// operation, indicating whether it has succeeded, is inprogress, or
        /// has failed. Note that this status is distinct from the HTTP status
        /// code returned for the Get Operation Status operation itself. If
        /// the asynchronous operation succeeded, the response body includes
        /// the HTTP status code for the successful request. If the
        /// asynchronous operation failed, the response body includes the HTTP
        /// status code for the failed request, and also includes error
        /// information regarding the failure.
        /// </returns>
        public async System.Threading.Tasks.Task <OperationStatusResponse> SetConfigurationAsync(NetworkSetConfigurationParameters parameters, CancellationToken cancellationToken)
        {
            NetworkManagementClient 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, "SetConfigurationAsync", tracingParameters);
            }
            try
            {
                if (shouldTrace)
                {
                    client = this.Client.WithHandler(new ClientRequestTrackingHandler(invocationId));
                }

                cancellationToken.ThrowIfCancellationRequested();
                OperationResponse response = await client.Networks.BeginSettingConfigurationAsync(parameters, cancellationToken).ConfigureAwait(false);

                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();
                }
            }
        }
        /// <summary>
        /// The List Virtual network sites operation retrieves the virtual
        /// networks configured for the subscription.  (see
        /// http://msdn.microsoft.com/en-us/library/windowsazure/jj157185.aspx
        /// for more information)
        /// </summary>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// The response structure for the Network Operations List operation.
        /// </returns>
        public async System.Threading.Tasks.Task <Microsoft.WindowsAzure.Management.Network.Models.NetworkListResponse> 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/virtualnetwork";

            // 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", "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
                    NetworkListResponse result = null;
                    // Deserialize Response
                    cancellationToken.ThrowIfCancellationRequested();
                    string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

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

                    XElement virtualNetworkSitesSequenceElement = responseDoc.Element(XName.Get("VirtualNetworkSites", "http://schemas.microsoft.com/windowsazure"));
                    if (virtualNetworkSitesSequenceElement != null)
                    {
                        foreach (XElement virtualNetworkSitesElement in virtualNetworkSitesSequenceElement.Elements(XName.Get("VirtualNetworkSite", "http://schemas.microsoft.com/windowsazure")))
                        {
                            NetworkListResponse.VirtualNetworkSite virtualNetworkSiteInstance = new NetworkListResponse.VirtualNetworkSite();
                            result.VirtualNetworkSites.Add(virtualNetworkSiteInstance);

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

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

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

                            XElement affinityGroupElement = virtualNetworkSitesElement.Element(XName.Get("AffinityGroup", "http://schemas.microsoft.com/windowsazure"));
                            if (affinityGroupElement != null)
                            {
                                string affinityGroupInstance = affinityGroupElement.Value;
                                virtualNetworkSiteInstance.AffinityGroup = affinityGroupInstance;
                            }

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

                            XElement addressSpaceElement = virtualNetworkSitesElement.Element(XName.Get("AddressSpace", "http://schemas.microsoft.com/windowsazure"));
                            if (addressSpaceElement != null)
                            {
                                NetworkListResponse.AddressSpace addressSpaceInstance = new NetworkListResponse.AddressSpace();
                                virtualNetworkSiteInstance.AddressSpace = addressSpaceInstance;

                                XElement addressPrefixesSequenceElement = addressSpaceElement.Element(XName.Get("AddressPrefixes", "http://schemas.microsoft.com/windowsazure"));
                                if (addressPrefixesSequenceElement != null)
                                {
                                    foreach (XElement addressPrefixesElement in addressPrefixesSequenceElement.Elements(XName.Get("AddressPrefix", "http://schemas.microsoft.com/windowsazure")))
                                    {
                                        addressSpaceInstance.AddressPrefixes.Add(addressPrefixesElement.Value);
                                    }
                                }
                            }

                            XElement subnetsSequenceElement = virtualNetworkSitesElement.Element(XName.Get("Subnets", "http://schemas.microsoft.com/windowsazure"));
                            if (subnetsSequenceElement != null)
                            {
                                foreach (XElement subnetsElement in subnetsSequenceElement.Elements(XName.Get("Subnet", "http://schemas.microsoft.com/windowsazure")))
                                {
                                    NetworkListResponse.Subnet subnetInstance = new NetworkListResponse.Subnet();
                                    virtualNetworkSiteInstance.Subnets.Add(subnetInstance);

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

                                    XElement addressPrefixElement = subnetsElement.Element(XName.Get("AddressPrefix", "http://schemas.microsoft.com/windowsazure"));
                                    if (addressPrefixElement != null)
                                    {
                                        string addressPrefixInstance = addressPrefixElement.Value;
                                        subnetInstance.AddressPrefix = addressPrefixInstance;
                                    }
                                }
                            }

                            XElement dnsElement = virtualNetworkSitesElement.Element(XName.Get("Dns", "http://schemas.microsoft.com/windowsazure"));
                            if (dnsElement != null)
                            {
                                XElement dnsServersSequenceElement = dnsElement.Element(XName.Get("DnsServers", "http://schemas.microsoft.com/windowsazure"));
                                if (dnsServersSequenceElement != null)
                                {
                                    foreach (XElement dnsServersElement in dnsServersSequenceElement.Elements(XName.Get("DnsServer", "http://schemas.microsoft.com/windowsazure")))
                                    {
                                        NetworkListResponse.DnsServer dnsServerInstance = new NetworkListResponse.DnsServer();
                                        virtualNetworkSiteInstance.DnsServers.Add(dnsServerInstance);

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

                                        XElement addressElement = dnsServersElement.Element(XName.Get("Address", "http://schemas.microsoft.com/windowsazure"));
                                        if (addressElement != null)
                                        {
                                            string addressInstance = addressElement.Value;
                                            dnsServerInstance.Address = addressInstance;
                                        }
                                    }
                                }
                            }

                            XElement gatewayElement = virtualNetworkSitesElement.Element(XName.Get("Gateway", "http://schemas.microsoft.com/windowsazure"));
                            if (gatewayElement != null)
                            {
                                NetworkListResponse.Gateway gatewayInstance = new NetworkListResponse.Gateway();
                                virtualNetworkSiteInstance.Gateway = gatewayInstance;

                                XElement profileElement = gatewayElement.Element(XName.Get("Profile", "http://schemas.microsoft.com/windowsazure"));
                                if (profileElement != null)
                                {
                                    GatewayProfile profileInstance = ((GatewayProfile)Enum.Parse(typeof(GatewayProfile), profileElement.Value, true));
                                    gatewayInstance.Profile = profileInstance;
                                }

                                XElement sitesSequenceElement = gatewayElement.Element(XName.Get("Sites", "http://schemas.microsoft.com/windowsazure"));
                                if (sitesSequenceElement != null)
                                {
                                    foreach (XElement sitesElement in sitesSequenceElement.Elements(XName.Get("LocalNetworkSite", "http://schemas.microsoft.com/windowsazure")))
                                    {
                                        NetworkListResponse.LocalNetworkSite localNetworkSiteInstance = new NetworkListResponse.LocalNetworkSite();
                                        gatewayInstance.Sites.Add(localNetworkSiteInstance);

                                        XElement nameElement4 = sitesElement.Element(XName.Get("Name", "http://schemas.microsoft.com/windowsazure"));
                                        if (nameElement4 != null)
                                        {
                                            string nameInstance4 = nameElement4.Value;
                                            localNetworkSiteInstance.Name = nameInstance4;
                                        }

                                        XElement vpnGatewayAddressElement = sitesElement.Element(XName.Get("VpnGatewayAddress", "http://schemas.microsoft.com/windowsazure"));
                                        if (vpnGatewayAddressElement != null)
                                        {
                                            string vpnGatewayAddressInstance = vpnGatewayAddressElement.Value;
                                            localNetworkSiteInstance.VpnGatewayAddress = vpnGatewayAddressInstance;
                                        }

                                        XElement addressSpaceElement2 = sitesElement.Element(XName.Get("AddressSpace", "http://schemas.microsoft.com/windowsazure"));
                                        if (addressSpaceElement2 != null)
                                        {
                                            NetworkListResponse.AddressSpace addressSpaceInstance2 = new NetworkListResponse.AddressSpace();
                                            localNetworkSiteInstance.AddressSpace = addressSpaceInstance2;

                                            XElement addressPrefixesSequenceElement2 = addressSpaceElement2.Element(XName.Get("AddressPrefixes", "http://schemas.microsoft.com/windowsazure"));
                                            if (addressPrefixesSequenceElement2 != null)
                                            {
                                                foreach (XElement addressPrefixesElement2 in addressPrefixesSequenceElement2.Elements(XName.Get("AddressPrefix", "http://schemas.microsoft.com/windowsazure")))
                                                {
                                                    addressSpaceInstance2.AddressPrefixes.Add(addressPrefixesElement2.Value);
                                                }
                                            }
                                        }

                                        XElement connectionsSequenceElement = sitesElement.Element(XName.Get("Connections", "http://schemas.microsoft.com/windowsazure"));
                                        if (connectionsSequenceElement != null)
                                        {
                                            foreach (XElement connectionsElement in connectionsSequenceElement.Elements(XName.Get("Connection", "http://schemas.microsoft.com/windowsazure")))
                                            {
                                                NetworkListResponse.Connection connectionInstance = new NetworkListResponse.Connection();
                                                localNetworkSiteInstance.Connections.Add(connectionInstance);

                                                XElement typeElement = connectionsElement.Element(XName.Get("Type", "http://schemas.microsoft.com/windowsazure"));
                                                if (typeElement != null)
                                                {
                                                    LocalNetworkConnectionType typeInstance = NetworkManagementClient.ParseLocalNetworkConnectionType(typeElement.Value);
                                                    connectionInstance.Type = typeInstance;
                                                }
                                            }
                                        }
                                    }
                                }

                                XElement vPNClientAddressPoolElement = gatewayElement.Element(XName.Get("VPNClientAddressPool", "http://schemas.microsoft.com/windowsazure"));
                                if (vPNClientAddressPoolElement != null)
                                {
                                    NetworkListResponse.VPNClientAddressPool vPNClientAddressPoolInstance = new NetworkListResponse.VPNClientAddressPool();
                                    gatewayInstance.VPNClientAddressPool = vPNClientAddressPoolInstance;

                                    XElement addressPrefixesSequenceElement3 = vPNClientAddressPoolElement.Element(XName.Get("AddressPrefixes", "http://schemas.microsoft.com/windowsazure"));
                                    if (addressPrefixesSequenceElement3 != null)
                                    {
                                        foreach (XElement addressPrefixesElement3 in addressPrefixesSequenceElement3.Elements(XName.Get("AddressPrefix", "http://schemas.microsoft.com/windowsazure")))
                                        {
                                            vPNClientAddressPoolInstance.AddressPrefixes.Add(addressPrefixesElement3.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>
 /// Adds a new server-level Firewall Rule for an Azure SQL Database
 /// Server.
 /// </summary>
 /// <param name='serverName'>
 /// Required. The name of the Azure SQL Database Server to which this
 /// rule will be applied.
 /// </param>
 /// <param name='parameters'>
 /// Required. The parameters for the Create Firewall Rule operation.
 /// </param>
 /// <param name='cancellationToken'>
 /// Cancellation token.
 /// </param>
 /// <returns>
 /// Contains the response to a Create Firewall Rule operation.
 /// </returns>
 public async System.Threading.Tasks.Task<Microsoft.WindowsAzure.Management.Sql.Models.FirewallRuleCreateResponse> CreateAsync(string serverName, FirewallRuleCreateParameters parameters, CancellationToken cancellationToken)
 {
     // Validate
     if (serverName == null)
     {
         throw new ArgumentNullException("serverName");
     }
     if (parameters == null)
     {
         throw new ArgumentNullException("parameters");
     }
     if (parameters.EndIPAddress == null)
     {
         throw new ArgumentNullException("parameters.EndIPAddress");
     }
     if (parameters.Name == null)
     {
         throw new ArgumentNullException("parameters.Name");
     }
     if (parameters.StartIPAddress == null)
     {
         throw new ArgumentNullException("parameters.StartIPAddress");
     }
     
     // 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, "CreateAsync", tracingParameters);
     }
     
     // Construct URL
     string url = "/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/services/sqlservers/servers/" + serverName.Trim() + "/firewallrules";
     string baseUrl = this.Client.BaseUri.AbsoluteUri;
     // Trim '/' character from the end of baseUrl and beginning of url.
     if (baseUrl[baseUrl.Length - 1] == '/')
     {
         baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
     }
     if (url[0] == '/')
     {
         url = url.Substring(1);
     }
     url = baseUrl + "/" + url;
     url = url.Replace(" ", "%20");
     
     // Create HTTP transport objects
     HttpRequestMessage httpRequest = null;
     try
     {
         httpRequest = new HttpRequestMessage();
         httpRequest.Method = HttpMethod.Post;
         httpRequest.RequestUri = new Uri(url);
         
         // Set Headers
         httpRequest.Headers.Add("x-ms-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();
         
         XElement serviceResourceElement = new XElement(XName.Get("ServiceResource", "http://schemas.microsoft.com/windowsazure"));
         requestDoc.Add(serviceResourceElement);
         
         XElement nameElement = new XElement(XName.Get("Name", "http://schemas.microsoft.com/windowsazure"));
         nameElement.Value = parameters.Name;
         serviceResourceElement.Add(nameElement);
         
         XElement startIPAddressElement = new XElement(XName.Get("StartIPAddress", "http://schemas.microsoft.com/windowsazure"));
         startIPAddressElement.Value = parameters.StartIPAddress;
         serviceResourceElement.Add(startIPAddressElement);
         
         XElement endIPAddressElement = new XElement(XName.Get("EndIPAddress", "http://schemas.microsoft.com/windowsazure"));
         endIPAddressElement.Value = parameters.EndIPAddress;
         serviceResourceElement.Add(endIPAddressElement);
         
         requestContent = requestDoc.ToString();
         httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
         httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/xml");
         
         // Send Request
         HttpResponseMessage httpResponse = null;
         try
         {
             if (shouldTrace)
             {
                 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.Created)
             {
                 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
             FirewallRuleCreateResponse result = null;
             // Deserialize Response
             cancellationToken.ThrowIfCancellationRequested();
             string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
             result = new FirewallRuleCreateResponse();
             XDocument responseDoc = XDocument.Parse(responseContent);
             
             XElement serviceResourceElement2 = responseDoc.Element(XName.Get("ServiceResource", "http://schemas.microsoft.com/windowsazure"));
             if (serviceResourceElement2 != null)
             {
                 FirewallRule serviceResourceInstance = new FirewallRule();
                 result.FirewallRule = serviceResourceInstance;
                 
                 XElement startIPAddressElement2 = serviceResourceElement2.Element(XName.Get("StartIPAddress", "http://schemas.microsoft.com/windowsazure"));
                 if (startIPAddressElement2 != null)
                 {
                     string startIPAddressInstance = startIPAddressElement2.Value;
                     serviceResourceInstance.StartIPAddress = startIPAddressInstance;
                 }
                 
                 XElement endIPAddressElement2 = serviceResourceElement2.Element(XName.Get("EndIPAddress", "http://schemas.microsoft.com/windowsazure"));
                 if (endIPAddressElement2 != null)
                 {
                     string endIPAddressInstance = endIPAddressElement2.Value;
                     serviceResourceInstance.EndIPAddress = endIPAddressInstance;
                 }
                 
                 XElement nameElement2 = serviceResourceElement2.Element(XName.Get("Name", "http://schemas.microsoft.com/windowsazure"));
                 if (nameElement2 != null)
                 {
                     string nameInstance = nameElement2.Value;
                     serviceResourceInstance.Name = nameInstance;
                 }
                 
                 XElement typeElement = serviceResourceElement2.Element(XName.Get("Type", "http://schemas.microsoft.com/windowsazure"));
                 if (typeElement != null)
                 {
                     string typeInstance = typeElement.Value;
                     serviceResourceInstance.Type = typeInstance;
                 }
                 
                 XElement stateElement = serviceResourceElement2.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();
         }
     }
 }
        /// <summary>
        /// The List Management Certificates operation lists and returns basic
        /// information about all of the management certificates associated
        /// with the specified subscription. Management certificates, which
        /// are also known as subscription certificates, authenticate clients
        /// attempting to connect to resources associated with your Windows
        /// Azure subscription.  (see
        /// http://msdn.microsoft.com/en-us/library/windowsazure/jj154105.aspx
        /// for more information)
        /// </summary>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// The List Management Certificates operation response.
        /// </returns>
        public async System.Threading.Tasks.Task <Microsoft.WindowsAzure.Management.Models.ManagementCertificateListResponse> 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, "/").ToString() + this.Client.Credentials.SubscriptionId + "/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-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
                    ManagementCertificateListResponse result = null;
                    // Deserialize Response
                    cancellationToken.ThrowIfCancellationRequested();
                    string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

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

                    XElement subscriptionCertificatesSequenceElement = responseDoc.Element(XName.Get("SubscriptionCertificates", "http://schemas.microsoft.com/windowsazure"));
                    if (subscriptionCertificatesSequenceElement != null)
                    {
                        foreach (XElement subscriptionCertificatesElement in subscriptionCertificatesSequenceElement.Elements(XName.Get("SubscriptionCertificate", "http://schemas.microsoft.com/windowsazure")))
                        {
                            ManagementCertificateListResponse.SubscriptionCertificate subscriptionCertificateInstance = new ManagementCertificateListResponse.SubscriptionCertificate();
                            result.SubscriptionCertificates.Add(subscriptionCertificateInstance);

                            XElement subscriptionCertificatePublicKeyElement = subscriptionCertificatesElement.Element(XName.Get("SubscriptionCertificatePublicKey", "http://schemas.microsoft.com/windowsazure"));
                            if (subscriptionCertificatePublicKeyElement != null)
                            {
                                byte[] subscriptionCertificatePublicKeyInstance = Convert.FromBase64String(subscriptionCertificatePublicKeyElement.Value);
                                subscriptionCertificateInstance.PublicKey = subscriptionCertificatePublicKeyInstance;
                            }

                            XElement subscriptionCertificateThumbprintElement = subscriptionCertificatesElement.Element(XName.Get("SubscriptionCertificateThumbprint", "http://schemas.microsoft.com/windowsazure"));
                            if (subscriptionCertificateThumbprintElement != null)
                            {
                                string subscriptionCertificateThumbprintInstance = subscriptionCertificateThumbprintElement.Value;
                                subscriptionCertificateInstance.Thumbprint = subscriptionCertificateThumbprintInstance;
                            }

                            XElement subscriptionCertificateDataElement = subscriptionCertificatesElement.Element(XName.Get("SubscriptionCertificateData", "http://schemas.microsoft.com/windowsazure"));
                            if (subscriptionCertificateDataElement != null)
                            {
                                byte[] subscriptionCertificateDataInstance = Convert.FromBase64String(subscriptionCertificateDataElement.Value);
                                subscriptionCertificateInstance.Data = subscriptionCertificateDataInstance;
                            }

                            XElement createdElement = subscriptionCertificatesElement.Element(XName.Get("Created", "http://schemas.microsoft.com/windowsazure"));
                            if (createdElement != null)
                            {
                                DateTime createdInstance = DateTime.Parse(createdElement.Value, CultureInfo.InvariantCulture);
                                subscriptionCertificateInstance.Created = createdInstance;
                            }
                        }
                    }

                    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();
                }
            }
        }
Exemple #17
0
        public static bool TryGetValue(Tracing trace, IDictionary<string, string> source, string name, out string val)
        {
            if (source.TryGetValue(name, out val))
            {
                val = val ?? string.Empty;
                trace.Verbose($"Get '{name}': '{val}'");
                return true;
            }

            val = null;
            trace.Verbose($"Get '{name}' (not found)");
            return false;
        }
        public ActionResult HandleConsentResponse(string appName, string button, string[] scopes, AuthorizeRequest request, int?rememberDuration = null)
        {
            Tracing.Start("OAuth2 Authorize Endoint - Consent response");

            // make sure application is registered
            var application = _config.FindApplication(appName);

            if (application == null)
            {
                Tracing.Error("Application not found: " + appName);
                return(HttpNotFound());
            }

            if (button == "no")
            {
                Tracing.Information("User denies access token request.");
                return(new ClientErrorResult(new Uri(request.redirect_uri), OAuthConstants.Errors.AccessDenied, request.response_type, request.state));
            }

            if (button == "yes")
            {
                Tracing.Information("User allows access token request.");

                ValidatedRequest validatedRequest;
                try
                {
                    validatedRequest = new AuthorizeRequestValidator().Validate(application, request);
                    validatedRequest.RememberOptions = GetRememberOptions(application);
                }
                catch (AuthorizeRequestValidationException ex)
                {
                    Tracing.Error("Aborting OAuth2 authorization request");
                    return(this.AuthorizeValidationError(ex));
                }

                if (scopes == null || scopes.Length == 0)
                {
                    ModelState.AddModelError("", "Please choose at least one permission.");
                    return(View("Consent", validatedRequest));
                }

                if (rememberDuration != null)
                {
                    if (!application.RememberOptions.Any(r => r.Value == rememberDuration))
                    {
                        ModelState.AddModelError("", "Please choose a duration from the list.");
                        return(View("Consent", validatedRequest));
                    }
                }
                // parse scopes form post and substitue scopes
                validatedRequest.Scopes.RemoveAll(x => !scopes.Contains(x.Name));

                // store consent decision if
                //  checkbox was checked
                //  and storage is allowed
                //  and flow == implicit
                if (validatedRequest.Application.AllowRememberConsentDecision &&
                    validatedRequest.ResponseType == OAuthConstants.ResponseTypes.Token &&
                    rememberDuration == -1)
                {
                    var handle = StoredGrant.CreateConsentDecision(
                        ClaimsPrincipal.Current.GetSubject(),
                        validatedRequest.Client,
                        validatedRequest.Application,
                        validatedRequest.Scopes);

                    _handleManager.Add(handle);

                    Tracing.Information("Consent decision stored.");
                }

                // parse refresh token lifetime if
                // code flow is used
                // and refresh tokens are allowed
                if (validatedRequest.RequestingRefreshToken &&
                    rememberDuration != null &&
                    validatedRequest.Client.Flow == OAuthFlow.Code)
                {
                    if (rememberDuration == -1)
                    {
                        validatedRequest.RequestedRefreshTokenExpiration = DateTime.UtcNow.AddYears(50);
                    }
                    else
                    {
                        validatedRequest.RequestedRefreshTokenExpiration = DateTime.UtcNow.AddHours(rememberDuration.Value);
                    }

                    Tracing.Information("Selected refresh token lifetime in hours: " + rememberDuration);
                }

                var grantResult = PerformGrant(validatedRequest);
                if (grantResult != null)
                {
                    return(grantResult);
                }
            }

            return(new ClientErrorResult(
                       new Uri(request.redirect_uri),
                       OAuthConstants.Errors.InvalidRequest,
                       request.response_type,
                       request.state));
        }
Exemple #19
0
 // these methods are needed only for diagnostic purposes.
 public override void Connect(IPersistableOutput persistableOutput)
 {
     Tracing.Trace("Imgur::Connect");
     base.Connect(persistableOutput);
 }
Exemple #20
0
        private IExportService initializeAssembly()
        {
            if (this.serviceSetting == null)
            {
                return((IExportService)null);
            }
            string str1 = SystemSettings.EpassDataDir + this.serviceSetting.FilePath;

            Tracing.Log(ExportService.sw, TraceLevel.Verbose, nameof(ExportService), "Initialize Assembly: " + str1);
            if (!File.Exists(str1))
            {
                throw new FileNotFoundException();
            }
            string fullName1 = AssemblyName.GetAssemblyName(str1).FullName;

            Tracing.Log(ExportService.sw, TraceLevel.Verbose, nameof(ExportService), "Display Name: " + fullName1);
            Assembly assembly1 = (Assembly)null;

            foreach (Assembly assembly2 in AppDomain.CurrentDomain.GetAssemblies())
            {
                if (assembly2.FullName == fullName1)
                {
                    assembly1 = assembly2;
                }
            }
            if (assembly1 == (Assembly)null)
            {
                FileStream fileStream = File.OpenRead(str1);
                byte[]     numArray   = new byte[fileStream.Length];
                fileStream.Read(numArray, 0, numArray.Length);
                fileStream.Close();
                Tracing.Log(ExportService.sw, TraceLevel.Verbose, nameof(ExportService), "Loading Assembly");

                assembly1 = Assembly.Load(numArray);
            }
            string fullName2 = typeof(IExportService).FullName;
            string typeName  = (string)null;

            try
            {
                foreach (Type type in assembly1.GetTypes())
                {
                    if (type.GetInterface(fullName2) != (Type)null)
                    {
                        typeName = type.FullName;
                    }
                }
            }
            catch (ReflectionTypeLoadException ex)
            {
                string str2 = "ReflectionTypeLoadException occured:\r\n" + ex.Message + "\r\n\r\n" + "Assembly Types:\r\n";
                foreach (Type type in ex.Types)
                {
                    if (!(type == (Type)null))
                    {
                        str2 = str2 + "Assembly: " + (object)type.Assembly + "\r\n" + "AssemblyQualifiedName: " + type.AssemblyQualifiedName + "\r\n" + "FullName: " + type.FullName + "\r\n" + "\r\n";
                    }
                }
                string str3 = str2 + "LoaderException messages:\r\n";
                foreach (Exception loaderException in ex.LoaderExceptions)
                {
                    if (loaderException != null)
                    {
                        str3 = str3 + loaderException.Message + "\r\n";
                    }
                }
                string str4 = str3 + "\r\n";
                Tracing.Log(ExportService.sw, TraceLevel.Error, nameof(ExportService), str4 + "\r\n");
                throw;
            }
            catch (Exception ex)
            {
                string msg = "Exception trying to create instance:\r\n" + ex.Message + "\r\n\r\nInnerException: \r\n" + (object)ex.InnerException;
                Tracing.Log(ExportService.sw, TraceLevel.Error, nameof(ExportService), msg);
                throw;
            }
            Tracing.Log(ExportService.sw, TraceLevel.Verbose, nameof(ExportService), "Creating Instance: " + typeName);
            return((IExportService)assembly1.CreateInstance(typeName));
        }
Exemple #21
0
 protected override void OnImageFormatClick(object sender, ImageFormatEventArgs e)
 {
     Tracing.Trace("Imgur::MenuClick");
     base.OnImageFormatClick(sender, e);
 }
Exemple #22
0
            public override Stream Open()
            {
                Tracing.FrameworkInformation("EmbeddedResourceVirtualFile", "Open", "_resourceName={0}", _resourceName);

                return(_assembly.GetManifestResourceStream(_resourceName));
            }
Exemple #23
0
        public void CalculateServiceNameL0()
        {
            using (TestHostContext tc = CreateTestContext())
            {
                Tracing trace = tc.GetTrace();

                trace.Info("Creating service control manager");
                ServiceControlManager scm = new ServiceControlManager();
                scm.Initialize(tc);
                ServiceNameTest[] tests = new ServiceNameTest[] {
                    new ServiceNameTest {
                        TestName                   = "SystemD Test",
                        ServiceNamePattern         = "vsts.agent.{0}.{1}.{2}.service",
                        ServiceDisplayPattern      = "Azure Pipelines Agent ({0}.{1}.{2})",
                        AgentName                  = "foo",
                        PoolName                   = "pool1",
                        ServerUrl                  = "https://dev.azure.com/bar",
                        ExpectedServiceName        = "vsts.agent.bar.pool1.foo.service",
                        ExpectedServiceDisplayName = "Azure Pipelines Agent (bar.pool1.foo)"
                    },
                    new ServiceNameTest {
                        TestName                   = "Long Agent/Pool Test",
                        ServiceNamePattern         = "vsts.agent.{0}.{1}.{2}.service",
                        ServiceDisplayPattern      = "Azure Pipelines Agent ({0}.{1}.{2})",
                        AgentName                  = new string('X', 40),
                        PoolName                   = new string('Y', 40),
                        ServerUrl                  = "https://dev.azure.com/bar",
                        ExpectedServiceName        = "vsts.agent.bar.YYYYYYYYYYYYYYYYYYYYYYYYY.XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.service",
                        ExpectedServiceDisplayName = "Azure Pipelines Agent (bar.YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY.XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX)"
                    },
                    new ServiceNameTest {
                        TestName                   = "Pool With Unicode Dash Test",
                        ServiceNamePattern         = "vsts.agent.{0}.{1}.{2}.service",
                        ServiceDisplayPattern      = "Azure Pipelines Agent ({0}.{1}.{2})",
                        AgentName                  = "foo",
                        PoolName                   = "pool" + "\u002D" + "1",
                        ServerUrl                  = "https://dev.azure.com/bar",
                        ExpectedServiceName        = "vsts.agent.bar.pool-1.foo.service",
                        ExpectedServiceDisplayName = "Azure Pipelines Agent (bar.pool-1.foo)"
                    },
                    new ServiceNameTest {
                        TestName                   = "Agent For Environment Test",
                        ServiceNamePattern         = "vsts.agent.{0}.{1}.{2}.service",
                        ServiceDisplayPattern      = "Azure Pipelines Agent ({0}.{1}.{2})",
                        AgentName                  = new string('X', 40),
                        EnvironmentName            = new string('Y', 40),
                        ServerUrl                  = "https://dev.azure.com/bar",
                        ExpectedServiceName        = "vsts.agent.bar.YYYYYYYYYYYYYYYYYYYYYYYYY.XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.service",
                        ExpectedServiceDisplayName = "Azure Pipelines Agent (bar.YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY.XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX)"
                    },
                };
                foreach (var test in tests)
                {
                    AgentSettings settings = new AgentSettings();
                    settings.ServerUrl       = test.ServerUrl;
                    settings.AgentName       = test.AgentName;
                    settings.PoolName        = test.PoolName;
                    settings.EnvironmentName = test.EnvironmentName;

                    scm.CalculateServiceName(settings, test.ServiceNamePattern, test.ServiceDisplayPattern, out string serviceName, out string serviceDisplayName);

                    Assert.True(string.Equals(serviceName, test.ExpectedServiceName), $"{test.TestName} Service Name Expected: {test.ExpectedServiceName}, Got: {serviceName}");
                    Assert.True(serviceName.Length <= 80, $"{test.TestName} Service Name is <= 80");
                    Assert.True(string.Equals(serviceDisplayName, test.ExpectedServiceDisplayName), $"{test.TestName} Service Display Name Expected: {test.ExpectedServiceDisplayName}, Got: {serviceDisplayName}");
                }
            }
        }
        /// <param name='resourceId'>
        /// The resource ID.
        /// </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> DeleteAsync(string resourceId, CancellationToken cancellationToken)
        {
            // Validate
            if (resourceId == null)
            {
                throw new ArgumentNullException("resourceId");
            }

            // 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("resourceId", resourceId);
                Tracing.Enter(invocationId, this, "DeleteAsync", tracingParameters);
            }

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

            url = url + "resourceId=" + Uri.EscapeUriString(resourceId);

            // 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("Accept", "application/json");
                httpRequest.Headers.Add("x-ms-version", "2013-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.Json);
                        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();
                }
            }
        }
Exemple #25
0
        /// <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.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), CloudExceptionType.Json);
                        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();
                }
            }
        }
        /// <param name='resourceId'>
        /// The resource ID.
        /// </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 <Microsoft.WindowsAzure.Management.Monitoring.Autoscale.Models.AutoscaleSettingGetResponse> GetAsync(string resourceId, CancellationToken cancellationToken)
        {
            // Validate
            if (resourceId == null)
            {
                throw new ArgumentNullException("resourceId");
            }

            // 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("resourceId", resourceId);
                Tracing.Enter(invocationId, this, "GetAsync", tracingParameters);
            }

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

            url = url + "resourceId=" + Uri.EscapeUriString(resourceId);

            // Create HTTP transport objects
            HttpRequestMessage httpRequest = null;

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

                // Set Headers
                httpRequest.Headers.Add("Accept", "application/json");
                httpRequest.Headers.Add("x-ms-version", "2013-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.Json);
                        if (shouldTrace)
                        {
                            Tracing.Error(invocationId, ex);
                        }
                        throw ex;
                    }

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

                    result = new AutoscaleSettingGetResponse();
                    JToken responseDoc = JToken.Parse(responseContent);

                    if (responseDoc != null && responseDoc.Type != JTokenType.Null)
                    {
                        AutoscaleSetting settingInstance = new AutoscaleSetting();
                        result.Setting = settingInstance;

                        JToken profilesArray = responseDoc["Profiles"];
                        if (profilesArray != null && profilesArray.Type != JTokenType.Null)
                        {
                            foreach (JToken profilesValue in (JArray)profilesArray)
                            {
                                AutoscaleProfile autoscaleProfileInstance = new AutoscaleProfile();
                                settingInstance.Profiles.Add(autoscaleProfileInstance);

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

                                JToken capacityValue = profilesValue["Capacity"];
                                if (capacityValue != null && capacityValue.Type != JTokenType.Null)
                                {
                                    ScaleCapacity capacityInstance = new ScaleCapacity();
                                    autoscaleProfileInstance.Capacity = capacityInstance;

                                    JToken minimumValue = capacityValue["Minimum"];
                                    if (minimumValue != null && minimumValue.Type != JTokenType.Null)
                                    {
                                        string minimumInstance = (string)minimumValue;
                                        capacityInstance.Minimum = minimumInstance;
                                    }

                                    JToken maximumValue = capacityValue["Maximum"];
                                    if (maximumValue != null && maximumValue.Type != JTokenType.Null)
                                    {
                                        string maximumInstance = (string)maximumValue;
                                        capacityInstance.Maximum = maximumInstance;
                                    }

                                    JToken defaultValue = capacityValue["Default"];
                                    if (defaultValue != null && defaultValue.Type != JTokenType.Null)
                                    {
                                        string defaultInstance = (string)defaultValue;
                                        capacityInstance.Default = defaultInstance;
                                    }
                                }

                                JToken rulesArray = profilesValue["Rules"];
                                if (rulesArray != null && rulesArray.Type != JTokenType.Null)
                                {
                                    foreach (JToken rulesValue in (JArray)rulesArray)
                                    {
                                        ScaleRule scaleRuleInstance = new ScaleRule();
                                        autoscaleProfileInstance.Rules.Add(scaleRuleInstance);

                                        JToken metricTriggerValue = rulesValue["MetricTrigger"];
                                        if (metricTriggerValue != null && metricTriggerValue.Type != JTokenType.Null)
                                        {
                                            MetricTrigger metricTriggerInstance = new MetricTrigger();
                                            scaleRuleInstance.MetricTrigger = metricTriggerInstance;

                                            JToken metricNameValue = metricTriggerValue["MetricName"];
                                            if (metricNameValue != null && metricNameValue.Type != JTokenType.Null)
                                            {
                                                string metricNameInstance = (string)metricNameValue;
                                                metricTriggerInstance.MetricName = metricNameInstance;
                                            }

                                            JToken metricNamespaceValue = metricTriggerValue["MetricNamespace"];
                                            if (metricNamespaceValue != null && metricNamespaceValue.Type != JTokenType.Null)
                                            {
                                                string metricNamespaceInstance = (string)metricNamespaceValue;
                                                metricTriggerInstance.MetricNamespace = metricNamespaceInstance;
                                            }

                                            JToken metricSourceValue = metricTriggerValue["MetricSource"];
                                            if (metricSourceValue != null && metricSourceValue.Type != JTokenType.Null)
                                            {
                                                string metricSourceInstance = (string)metricSourceValue;
                                                metricTriggerInstance.MetricSource = metricSourceInstance;
                                            }

                                            JToken timeGrainValue = metricTriggerValue["TimeGrain"];
                                            if (timeGrainValue != null && timeGrainValue.Type != JTokenType.Null)
                                            {
                                                TimeSpan timeGrainInstance = TypeConversion.From8601TimeSpan((string)timeGrainValue);
                                                metricTriggerInstance.TimeGrain = timeGrainInstance;
                                            }

                                            JToken statisticValue = metricTriggerValue["Statistic"];
                                            if (statisticValue != null && statisticValue.Type != JTokenType.Null)
                                            {
                                                MetricStatisticType statisticInstance = (MetricStatisticType)Enum.Parse(typeof(MetricStatisticType), (string)statisticValue, false);
                                                metricTriggerInstance.Statistic = statisticInstance;
                                            }

                                            JToken timeWindowValue = metricTriggerValue["TimeWindow"];
                                            if (timeWindowValue != null && timeWindowValue.Type != JTokenType.Null)
                                            {
                                                TimeSpan timeWindowInstance = TypeConversion.From8601TimeSpan((string)timeWindowValue);
                                                metricTriggerInstance.TimeWindow = timeWindowInstance;
                                            }

                                            JToken timeAggregationValue = metricTriggerValue["TimeAggregation"];
                                            if (timeAggregationValue != null && timeAggregationValue.Type != JTokenType.Null)
                                            {
                                                TimeAggregationType timeAggregationInstance = (TimeAggregationType)Enum.Parse(typeof(TimeAggregationType), (string)timeAggregationValue, false);
                                                metricTriggerInstance.TimeAggregation = timeAggregationInstance;
                                            }

                                            JToken operatorValue = metricTriggerValue["Operator"];
                                            if (operatorValue != null && operatorValue.Type != JTokenType.Null)
                                            {
                                                ComparisonOperationType operatorInstance = (ComparisonOperationType)Enum.Parse(typeof(ComparisonOperationType), (string)operatorValue, false);
                                                metricTriggerInstance.Operator = operatorInstance;
                                            }

                                            JToken thresholdValue = metricTriggerValue["Threshold"];
                                            if (thresholdValue != null && thresholdValue.Type != JTokenType.Null)
                                            {
                                                double thresholdInstance = (double)thresholdValue;
                                                metricTriggerInstance.Threshold = thresholdInstance;
                                            }
                                        }

                                        JToken scaleActionValue = rulesValue["ScaleAction"];
                                        if (scaleActionValue != null && scaleActionValue.Type != JTokenType.Null)
                                        {
                                            ScaleAction scaleActionInstance = new ScaleAction();
                                            scaleRuleInstance.ScaleAction = scaleActionInstance;

                                            JToken directionValue = scaleActionValue["Direction"];
                                            if (directionValue != null && directionValue.Type != JTokenType.Null)
                                            {
                                                ScaleDirection directionInstance = (ScaleDirection)Enum.Parse(typeof(ScaleDirection), (string)directionValue, false);
                                                scaleActionInstance.Direction = directionInstance;
                                            }

                                            JToken typeValue = scaleActionValue["Type"];
                                            if (typeValue != null && typeValue.Type != JTokenType.Null)
                                            {
                                                ScaleType typeInstance = (ScaleType)Enum.Parse(typeof(ScaleType), (string)typeValue, false);
                                                scaleActionInstance.Type = typeInstance;
                                            }

                                            JToken valueValue = scaleActionValue["Value"];
                                            if (valueValue != null && valueValue.Type != JTokenType.Null)
                                            {
                                                string valueInstance = (string)valueValue;
                                                scaleActionInstance.Value = valueInstance;
                                            }

                                            JToken cooldownValue = scaleActionValue["Cooldown"];
                                            if (cooldownValue != null && cooldownValue.Type != JTokenType.Null)
                                            {
                                                TimeSpan cooldownInstance = TypeConversion.From8601TimeSpan((string)cooldownValue);
                                                scaleActionInstance.Cooldown = cooldownInstance;
                                            }
                                        }
                                    }
                                }

                                JToken fixedDateValue = profilesValue["FixedDate"];
                                if (fixedDateValue != null && fixedDateValue.Type != JTokenType.Null)
                                {
                                    TimeWindow fixedDateInstance = new TimeWindow();
                                    autoscaleProfileInstance.FixedDate = fixedDateInstance;

                                    JToken timeZoneValue = fixedDateValue["TimeZone"];
                                    if (timeZoneValue != null && timeZoneValue.Type != JTokenType.Null)
                                    {
                                        string timeZoneInstance = (string)timeZoneValue;
                                        fixedDateInstance.TimeZone = timeZoneInstance;
                                    }

                                    JToken startValue = fixedDateValue["Start"];
                                    if (startValue != null && startValue.Type != JTokenType.Null)
                                    {
                                        DateTime startInstance = (DateTime)startValue;
                                        fixedDateInstance.Start = startInstance;
                                    }

                                    JToken endValue = fixedDateValue["End"];
                                    if (endValue != null && endValue.Type != JTokenType.Null)
                                    {
                                        DateTime endInstance = (DateTime)endValue;
                                        fixedDateInstance.End = endInstance;
                                    }
                                }

                                JToken recurrenceValue = profilesValue["Recurrence"];
                                if (recurrenceValue != null && recurrenceValue.Type != JTokenType.Null)
                                {
                                    Recurrence recurrenceInstance = new Recurrence();
                                    autoscaleProfileInstance.Recurrence = recurrenceInstance;

                                    JToken frequencyValue = recurrenceValue["Frequency"];
                                    if (frequencyValue != null && frequencyValue.Type != JTokenType.Null)
                                    {
                                        RecurrenceFrequency frequencyInstance = (RecurrenceFrequency)Enum.Parse(typeof(RecurrenceFrequency), (string)frequencyValue, false);
                                        recurrenceInstance.Frequency = frequencyInstance;
                                    }

                                    JToken scheduleValue = recurrenceValue["Schedule"];
                                    if (scheduleValue != null && scheduleValue.Type != JTokenType.Null)
                                    {
                                        RecurrentSchedule scheduleInstance = new RecurrentSchedule();
                                        recurrenceInstance.Schedule = scheduleInstance;

                                        JToken timeZoneValue2 = scheduleValue["TimeZone"];
                                        if (timeZoneValue2 != null && timeZoneValue2.Type != JTokenType.Null)
                                        {
                                            string timeZoneInstance2 = (string)timeZoneValue2;
                                            scheduleInstance.TimeZone = timeZoneInstance2;
                                        }

                                        JToken daysArray = scheduleValue["Days"];
                                        if (daysArray != null && daysArray.Type != JTokenType.Null)
                                        {
                                            foreach (JToken daysValue in (JArray)daysArray)
                                            {
                                                scheduleInstance.Days.Add((string)daysValue);
                                            }
                                        }

                                        JToken hoursArray = scheduleValue["Hours"];
                                        if (hoursArray != null && hoursArray.Type != JTokenType.Null)
                                        {
                                            foreach (JToken hoursValue in (JArray)hoursArray)
                                            {
                                                scheduleInstance.Hours.Add((int)hoursValue);
                                            }
                                        }

                                        JToken minutesArray = scheduleValue["Minutes"];
                                        if (minutesArray != null && minutesArray.Type != JTokenType.Null)
                                        {
                                            foreach (JToken minutesValue in (JArray)minutesArray)
                                            {
                                                scheduleInstance.Minutes.Add((int)minutesValue);
                                            }
                                        }
                                    }
                                }
                            }
                        }

                        JToken enabledValue = responseDoc["Enabled"];
                        if (enabledValue != null && enabledValue.Type != JTokenType.Null)
                        {
                            bool enabledInstance = (bool)enabledValue;
                            settingInstance.Enabled = enabledInstance;
                        }
                    }

                    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();
                }
            }
        }
Exemple #27
0
        /// <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, "/").AbsoluteUri + 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();
                }
            }
        }
        /// <param name='resourceId'>
        /// The resource ID.
        /// </param>
        /// <param name='parameters'>
        /// Parameters supplied to the 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> CreateOrUpdateAsync(string resourceId, AutoscaleSettingCreateOrUpdateParameters parameters, CancellationToken cancellationToken)
        {
            // Validate
            if (resourceId == null)
            {
                throw new ArgumentNullException("resourceId");
            }
            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("resourceId", resourceId);
                tracingParameters.Add("parameters", parameters);
                Tracing.Enter(invocationId, this, "CreateOrUpdateAsync", tracingParameters);
            }

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

            url = url + "resourceId=" + Uri.EscapeUriString(resourceId);

            // 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("Accept", "application/json");
                httpRequest.Headers.Add("x-ms-version", "2013-10-01");

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

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

                if (parameters.Setting != null)
                {
                    JObject settingValue = new JObject();
                    requestDoc            = new JObject();
                    requestDoc["Setting"] = settingValue;

                    if (parameters.Setting.Profiles != null)
                    {
                        JArray profilesArray = new JArray();
                        foreach (AutoscaleProfile profilesItem in parameters.Setting.Profiles)
                        {
                            JObject autoscaleProfileValue = new JObject();
                            profilesArray.Add(autoscaleProfileValue);

                            if (profilesItem.Name != null)
                            {
                                autoscaleProfileValue["Name"] = profilesItem.Name;
                            }

                            if (profilesItem.Capacity != null)
                            {
                                JObject capacityValue = new JObject();
                                autoscaleProfileValue["Capacity"] = capacityValue;

                                if (profilesItem.Capacity.Minimum != null)
                                {
                                    capacityValue["Minimum"] = profilesItem.Capacity.Minimum;
                                }

                                if (profilesItem.Capacity.Maximum != null)
                                {
                                    capacityValue["Maximum"] = profilesItem.Capacity.Maximum;
                                }

                                if (profilesItem.Capacity.Default != null)
                                {
                                    capacityValue["Default"] = profilesItem.Capacity.Default;
                                }
                            }

                            if (profilesItem.Rules != null)
                            {
                                JArray rulesArray = new JArray();
                                foreach (ScaleRule rulesItem in profilesItem.Rules)
                                {
                                    JObject scaleRuleValue = new JObject();
                                    rulesArray.Add(scaleRuleValue);

                                    if (rulesItem.MetricTrigger != null)
                                    {
                                        JObject metricTriggerValue = new JObject();
                                        scaleRuleValue["MetricTrigger"] = metricTriggerValue;

                                        if (rulesItem.MetricTrigger.MetricName != null)
                                        {
                                            metricTriggerValue["MetricName"] = rulesItem.MetricTrigger.MetricName;
                                        }

                                        if (rulesItem.MetricTrigger.MetricNamespace != null)
                                        {
                                            metricTriggerValue["MetricNamespace"] = rulesItem.MetricTrigger.MetricNamespace;
                                        }

                                        if (rulesItem.MetricTrigger.MetricSource != null)
                                        {
                                            metricTriggerValue["MetricSource"] = rulesItem.MetricTrigger.MetricSource;
                                        }

                                        metricTriggerValue["TimeGrain"] = TypeConversion.To8601String(rulesItem.MetricTrigger.TimeGrain);

                                        metricTriggerValue["Statistic"] = rulesItem.MetricTrigger.Statistic.ToString();

                                        metricTriggerValue["TimeWindow"] = TypeConversion.To8601String(rulesItem.MetricTrigger.TimeWindow);

                                        metricTriggerValue["TimeAggregation"] = rulesItem.MetricTrigger.TimeAggregation.ToString();

                                        metricTriggerValue["Operator"] = rulesItem.MetricTrigger.Operator.ToString();

                                        metricTriggerValue["Threshold"] = rulesItem.MetricTrigger.Threshold;
                                    }

                                    if (rulesItem.ScaleAction != null)
                                    {
                                        JObject scaleActionValue = new JObject();
                                        scaleRuleValue["ScaleAction"] = scaleActionValue;

                                        scaleActionValue["Direction"] = rulesItem.ScaleAction.Direction.ToString();

                                        scaleActionValue["Type"] = rulesItem.ScaleAction.Type.ToString();

                                        if (rulesItem.ScaleAction.Value != null)
                                        {
                                            scaleActionValue["Value"] = rulesItem.ScaleAction.Value;
                                        }

                                        scaleActionValue["Cooldown"] = TypeConversion.To8601String(rulesItem.ScaleAction.Cooldown);
                                    }
                                }
                                autoscaleProfileValue["Rules"] = rulesArray;
                            }

                            if (profilesItem.FixedDate != null)
                            {
                                JObject fixedDateValue = new JObject();
                                autoscaleProfileValue["FixedDate"] = fixedDateValue;

                                if (profilesItem.FixedDate.TimeZone != null)
                                {
                                    fixedDateValue["TimeZone"] = profilesItem.FixedDate.TimeZone;
                                }

                                fixedDateValue["Start"] = profilesItem.FixedDate.Start;

                                fixedDateValue["End"] = profilesItem.FixedDate.End;
                            }

                            if (profilesItem.Recurrence != null)
                            {
                                JObject recurrenceValue = new JObject();
                                autoscaleProfileValue["Recurrence"] = recurrenceValue;

                                recurrenceValue["Frequency"] = profilesItem.Recurrence.Frequency.ToString();

                                if (profilesItem.Recurrence.Schedule != null)
                                {
                                    JObject scheduleValue = new JObject();
                                    recurrenceValue["Schedule"] = scheduleValue;

                                    if (profilesItem.Recurrence.Schedule.TimeZone != null)
                                    {
                                        scheduleValue["TimeZone"] = profilesItem.Recurrence.Schedule.TimeZone;
                                    }

                                    if (profilesItem.Recurrence.Schedule.Days != null)
                                    {
                                        JArray daysArray = new JArray();
                                        foreach (string daysItem in profilesItem.Recurrence.Schedule.Days)
                                        {
                                            daysArray.Add(daysItem);
                                        }
                                        scheduleValue["Days"] = daysArray;
                                    }

                                    if (profilesItem.Recurrence.Schedule.Hours != null)
                                    {
                                        JArray hoursArray = new JArray();
                                        foreach (int hoursItem in profilesItem.Recurrence.Schedule.Hours)
                                        {
                                            hoursArray.Add(hoursItem);
                                        }
                                        scheduleValue["Hours"] = hoursArray;
                                    }

                                    if (profilesItem.Recurrence.Schedule.Minutes != null)
                                    {
                                        JArray minutesArray = new JArray();
                                        foreach (int minutesItem in profilesItem.Recurrence.Schedule.Minutes)
                                        {
                                            minutesArray.Add(minutesItem);
                                        }
                                        scheduleValue["Minutes"] = minutesArray;
                                    }
                                }
                            }
                        }
                        settingValue["Profiles"] = profilesArray;
                    }

                    settingValue["Enabled"] = parameters.Setting.Enabled;
                }

                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.OK && statusCode != HttpStatusCode.Created)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false), CloudExceptionType.Json);
                        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();
                }
            }
        }
Exemple #29
0
        /// <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, "/").AbsoluteUri + 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();
                }
            }
        }
Exemple #30
0
 /// <summary>
 /// returns a new entry for this feed
 /// </summary>
 /// <returns>AtomEntry</returns>
 public override AtomEntry CreateFeedEntry()
 {
     Tracing.TraceMsg("Construcing new AclEntry");
     return(new AclEntry());
 }
 /// <summary>
 /// Deletes a server-level Firewall Rule from an Azure SQL Database
 /// Server.
 /// </summary>
 /// <param name='serverName'>
 /// Required. The name of the Azure SQL Database Server that will have
 /// the Firewall Fule removed from it.
 /// </param>
 /// <param name='ruleName'>
 /// Required. The name of the Firewall Fule to delete.
 /// </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> DeleteAsync(string serverName, string ruleName, CancellationToken cancellationToken)
 {
     // Validate
     if (serverName == null)
     {
         throw new ArgumentNullException("serverName");
     }
     if (ruleName == null)
     {
         throw new ArgumentNullException("ruleName");
     }
     
     // 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("ruleName", ruleName);
         Tracing.Enter(invocationId, this, "DeleteAsync", tracingParameters);
     }
     
     // Construct URL
     string url = "/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/services/sqlservers/servers/" + serverName.Trim() + "/firewallrules/" + ruleName.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.Delete;
         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
             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();
         }
     }
 }
Exemple #32
0
 /// <summary>
 /// gets called after we already handled the custom entry, to handle all
 /// other potential parsing tasks
 /// </summary>
 /// <param name="e">the Event arguments</param>
 /// <param name="parser">the atom feed parser used</param>
 protected override void HandleExtensionElements(ExtensionElementEventArgs e, AtomFeedParser parser)
 {
     Tracing.TraceMsg("\t HandleExtensionElements for Access Control feed called");
 }
 public CapabilitiesBuilder(IHostContext hostContext, CancellationToken cancellationToken)
 {
     ArgUtil.NotNull(hostContext, nameof(hostContext));
     _hostContext = hostContext;
     _cancellationToken = cancellationToken;
     _trace = _hostContext.GetTrace(this.GetType().Name);
     _whichUtil = _hostContext.GetService<IWhichUtil>();
 }
Exemple #34
0
        /// <summary>
        ///  This does the real work of the plugin - uploading to imgur.com.
        /// </summary>
        ///
        /// <remarks>
        ///   First upload the main image, and then place the raw
        ///   image URL onto the clipboard for easy reference/paste.
        /// </remarks>
        private void UploadImage()
        {
            Tracing.Trace("Imgur::UploadImage");

            if (!VerifyBasicSettings())
            {
                return;
            }

            Hacks.BootstrapSettings(PluginSettings);

            try
            {
                var http = new HttpClient(Plugin._baseUri);
                var form = new HttpMultipartMimeForm();
                using (var fs = File.Open(this._fileName, FileMode.Open, FileAccess.Read))
                {
                    form.Add("key", PluginSettings.Key);
                    form.Add("image",
                             this._fileName,
                             HttpContent.Create(fs, "application/octet-stream", fs.Length));
                    form.Add("type", "file");
                    form.Add("title", "uploaded by Cropper SendToImgur plugin"); // optional
                    form.Add("caption", "http://cropper.codeplex.com");          // optional
                    var response = http.Post("upload.xml", form.CreateHttpContent());
                    response.EnsureStatusIsSuccessful();
                    var foo = response.Content.ReadAsXmlSerializable <UploadResponse>();
                    if (foo.links == null)
                    {
                        throw new InvalidOperationException("Successful response, but link is empty.");
                    }

                    string rawImageUri = foo.links.original;

                    if (PluginSettings.PopBrowser)
                    {
                        System.Diagnostics.Process.Start(rawImageUri);
                    }

                    Clipboard.SetDataObject(rawImageUri, true);
                    if (this._logger != null)
                    {
                        try
                        {
                            this._logger.Log(rawImageUri);
                        }
                        catch (Exception ex2)
                        {
                            MessageBox.Show("There's been an exception writing the ImgUr log?" +
                                            Environment.NewLine +
                                            ex2.Message +
                                            Environment.NewLine,
                                            "This isn't serious",
                                            MessageBoxButtons.OK,
                                            MessageBoxIcon.Information);
                        }
                    }
                }
            }
            catch (Exception exception2)
            {
                Tracing.Trace("Exception: {0}", exception2.StackTrace);
                Tracing.Trace("---------------------------------");
                MessageBox.Show("There's been an exception uploading your image:" +
                                Environment.NewLine +
                                exception2.Message +
                                Environment.NewLine +
                                Environment.NewLine +
                                "You will have to upload this file manually: " +
                                Environment.NewLine +
                                this._fileName,
                                "Upload to Imgur failed",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Error);
            }
            return;
        }
 public DiagnosticsTraceListener(Tracing.Trace trace)
 {
     _trace = trace;
 }
Exemple #36
0
        // Return code definition: (this will be used by service host to determine whether it will re-launch agent.listener)
        // 0: Agent exit
        // 1: Terminate failure
        // 2: Retriable failure
        // 3: Exit for self update
        public async static Task<int> MainAsync(string[] args)
        {
            using (HostContext context = new HostContext("Agent"))
            {
                s_trace = context.GetTrace("AgentProcess");
                s_trace.Info($"Agent is built for {Constants.Agent.Platform} - {BuildConstants.AgentPackage.PackageName}.");
                s_trace.Info($"RuntimeInformation: {RuntimeInformation.OSDescription}.");

                // Validate the binaries intended for one OS are not running on a different OS.
                switch (Constants.Agent.Platform)
                {
                    case Constants.OSPlatform.Linux:
                        if (!RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
                        {
                            Console.WriteLine(StringUtil.Loc("NotLinux"));
                            return Constants.Agent.ReturnCode.TerminatedError;
                        }
                        break;
                    case Constants.OSPlatform.OSX:
                        if (!RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
                        {
                            Console.WriteLine(StringUtil.Loc("NotOSX"));
                            return Constants.Agent.ReturnCode.TerminatedError;
                        }
                        break;
                    case Constants.OSPlatform.Windows:
                        if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                        {
                            Console.WriteLine(StringUtil.Loc("NotWindows"));
                            return Constants.Agent.ReturnCode.TerminatedError;
                        }
                        break;
                    default:
                        Console.WriteLine(StringUtil.Loc("PlatformNotSupport", RuntimeInformation.OSDescription, Constants.Agent.Platform.ToString()));
                        return Constants.Agent.ReturnCode.TerminatedError;
                }

                int rc = Constants.Agent.ReturnCode.Success;
                try
                {
                    s_trace.Info($"Version: {Constants.Agent.Version}");
                    s_trace.Info($"Commit: {BuildConstants.Source.CommitHash}");
                    s_trace.Info($"Culture: {CultureInfo.CurrentCulture.Name}");
                    s_trace.Info($"UI Culture: {CultureInfo.CurrentUICulture.Name}");

                    //
                    // TODO (bryanmac): Need VsoAgent.exe compat shim for SCM
                    //                  That shim will also provide a compat arg parse 
                    //                  and translate / to -- etc...
                    //

                    // Parse the command line args.
                    var command = new CommandSettings(context, args);
                    s_trace.Info("Arguments parsed");

                    // Defer to the Agent class to execute the command.
                    IAgent agent = context.GetService<IAgent>();
                    using (agent.TokenSource = new CancellationTokenSource())
                    {
                        try
                        {
                            rc = await agent.ExecuteCommand(command);
                        }
                        catch (OperationCanceledException) when (agent.TokenSource.IsCancellationRequested)
                        {
                            s_trace.Info("Agent execution been cancelled.");
                        }
                    }
                }
                catch (Exception e)
                {
                    Console.Error.WriteLine(StringUtil.Format("An error occured.  {0}", e.Message));
                    s_trace.Error(e);
                    rc = Constants.Agent.ReturnCode.RetryableError;
                }

                return rc;
            }
        }