Exemple #1
0
        /// <summary>
        /// Method to Either find or create the cloud service.
        /// </summary>
        /// <param name="cloudServiceName">name of the cloud service to be created</param>
        /// <param name="cloudServiceInput">cloud service input to create the service.</param>
        public void FindOrCreateCloudService(string cloudServiceName, CloudServiceCreateArgs cloudServiceInput)
        {
            bool cloudServicePresent = this.DoesCloudServiceExits(cloudServiceName);

            if (!cloudServicePresent)
            {
                this.GetRecoveryServicesClient.CloudServices.Create(cloudServiceName, cloudServiceInput);
            }
        }
        /// <summary>
        /// ProcessRecord of the command.
        /// </summary>
        public override void ExecuteCmdlet()
        {
            try
            {
                this.WriteWarningWithTimestamp(
                    string.Format(
                        Properties.Resources.CmdletWillBeDeprecatedSoon,
                        this.MyInvocation.MyCommand.Name));

                string cloudServiceName = Utilities.GenerateCloudServiceName(this.Location);
                byte[] bytes            = System.Text.Encoding.UTF8.GetBytes(cloudServiceName);
                string base64Label      = Convert.ToBase64String(bytes);

                CloudServiceCreateArgs cloudServiceCreateArgs = new CloudServiceCreateArgs()
                {
                    GeoRegion   = this.Location,
                    Label       = base64Label,
                    Description = base64Label
                };

                RecoveryServicesClient.FindOrCreateCloudService(cloudServiceName, cloudServiceCreateArgs);

                VaultCreateArgs vaultCreateArgs = new VaultCreateArgs()
                {
                    Name = this.Name,
                    Plan = string.Empty,
                    ResourceProviderNamespace = Constants.ResourceNamespace,
                    Type          = Constants.ASRVaultType,
                    ETag          = Guid.NewGuid().ToString(),
                    SchemaVersion = Constants.RpSchemaVersion
                };

                RecoveryServicesOperationStatusResponse response = RecoveryServicesClient.CreateVault(cloudServiceName, this.Name, vaultCreateArgs);

                VaultOperationOutput output = new VaultOperationOutput()
                {
                    Response = response.StatusCode == HttpStatusCode.OK ? Resources.VaultCreationSuccessMessage : response.StatusCode.ToString()
                };

                this.WriteObject(output, true);
            }
            catch (Exception exception)
            {
                this.HandleException(exception);
            }
        }
        /// <summary>
        /// Creates a Cloud services
        /// </summary>
        /// <param name='cloudServiceName'>
        /// Required. The cloud service name.
        /// </param>
        /// <param name='cloudService'>
        /// Required. Parameters supplied to the Create cloud service operation.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// A standard service response including an HTTP status code and
        /// request ID.
        /// </returns>
        public async Task <AzureOperationResponse> BeginCreatingAsync(string cloudServiceName, CloudServiceCreateArgs cloudService, CancellationToken cancellationToken)
        {
            // Validate
            if (cloudServiceName == null)
            {
                throw new ArgumentNullException("cloudServiceName");
            }
            if (cloudServiceName.Length > 100)
            {
                throw new ArgumentOutOfRangeException("cloudServiceName");
            }
            if (cloudService == null)
            {
                throw new ArgumentNullException("cloudService");
            }
            if (cloudService.Description == null)
            {
                throw new ArgumentNullException("cloudService.Description");
            }
            if (cloudService.Description.Length > 1024)
            {
                throw new ArgumentOutOfRangeException("cloudService.Description");
            }
            if (cloudService.GeoRegion == null)
            {
                throw new ArgumentNullException("cloudService.GeoRegion");
            }
            if (cloudService.Label == null)
            {
                throw new ArgumentNullException("cloudService.Label");
            }
            if (cloudService.Label.Length > 100)
            {
                throw new ArgumentOutOfRangeException("cloudService.Label");
            }

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

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

            // Construct URL
            string url = "";

            if (this.Client.Credentials.SubscriptionId != null)
            {
                url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
            }
            url = url + "/cloudservices/";
            url = url + Uri.EscapeDataString(cloudServiceName);
            string baseUrl = this.Client.BaseUri.AbsoluteUri;

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

            // Create HTTP transport objects
            HttpRequestMessage httpRequest = null;

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

                // Set Headers
                httpRequest.Headers.Add("Accept", "application/xml");
                httpRequest.Headers.Add("x-ms-version", "2013-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 cloudServiceElement = new XElement(XName.Get("CloudService", "http://schemas.microsoft.com/windowsazure"));
                requestDoc.Add(cloudServiceElement);

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

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

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

                if (cloudService.Email != null)
                {
                    XElement emailElement = new XElement(XName.Get("Email", "http://schemas.microsoft.com/windowsazure"));
                    emailElement.Value = cloudService.Email;
                    cloudServiceElement.Add(emailElement);
                }

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

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

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

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

                    if (shouldTrace)
                    {
                        TracingAdapter.Exit(invocationId, result);
                    }
                    return(result);
                }
                finally
                {
                    if (httpResponse != null)
                    {
                        httpResponse.Dispose();
                    }
                }
            }
            finally
            {
                if (httpRequest != null)
                {
                    httpRequest.Dispose();
                }
            }
        }
        /// <summary>
        /// Create a cloud service.
        /// </summary>
        /// <param name='cloudServiceName'>
        /// Required. The cloud service name.
        /// </param>
        /// <param name='cloudService'>
        /// Required. Parameters supplied to the Create cloud service 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 Task <RecoveryServicesOperationStatusResponse> CreateAsync(string cloudServiceName, CloudServiceCreateArgs cloudService, CancellationToken cancellationToken)
        {
            RecoveryServicesManagementClient client = this.Client;
            bool   shouldTrace  = TracingAdapter.IsEnabled;
            string invocationId = null;

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

            cancellationToken.ThrowIfCancellationRequested();
            AzureOperationResponse response = await client.CloudServices.BeginCreatingAsync(cloudServiceName, cloudService, cancellationToken).ConfigureAwait(false);

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

            int delayInSeconds = 10;

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

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

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

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

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

            return(result);
        }
Exemple #5
0
 /// <summary>
 /// Creates a Cloud services
 /// </summary>
 /// <param name='operations'>
 /// Reference to the
 /// Microsoft.WindowsAzure.Management.RecoveryServices.ICloudServiceOperations.
 /// </param>
 /// <param name='cloudServiceName'>
 /// Required. The cloud service name.
 /// </param>
 /// <param name='cloudService'>
 /// Required. Parameters supplied to the Create cloud service operation.
 /// </param>
 /// <returns>
 /// A standard service response including an HTTP status code and
 /// request ID.
 /// </returns>
 public static Task <AzureOperationResponse> BeginCreatingAsync(this ICloudServiceOperations operations, string cloudServiceName, CloudServiceCreateArgs cloudService)
 {
     return(operations.BeginCreatingAsync(cloudServiceName, cloudService, CancellationToken.None));
 }
Exemple #6
0
 /// <summary>
 /// Creates a Cloud services
 /// </summary>
 /// <param name='operations'>
 /// Reference to the
 /// Microsoft.WindowsAzure.Management.RecoveryServices.ICloudServiceOperations.
 /// </param>
 /// <param name='cloudServiceName'>
 /// Required. The cloud service name.
 /// </param>
 /// <param name='cloudService'>
 /// Required. Parameters supplied to the Create cloud service operation.
 /// </param>
 /// <returns>
 /// A standard service response including an HTTP status code and
 /// request ID.
 /// </returns>
 public static AzureOperationResponse BeginCreating(this ICloudServiceOperations operations, string cloudServiceName, CloudServiceCreateArgs cloudService)
 {
     return(Task.Factory.StartNew((object s) =>
     {
         return ((ICloudServiceOperations)s).BeginCreatingAsync(cloudServiceName, cloudService);
     }
                                  , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult());
 }
Exemple #7
0
 /// <summary>
 /// Create a cloud service.
 /// </summary>
 /// <param name='operations'>
 /// Reference to the
 /// Microsoft.WindowsAzure.Management.RecoveryServices.ICloudServiceOperations.
 /// </param>
 /// <param name='cloudServiceName'>
 /// Required. The cloud service name.
 /// </param>
 /// <param name='cloudService'>
 /// Required. Parameters supplied to the Create cloud service operation.
 /// </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 static Task <RecoveryServicesOperationStatusResponse> CreateAsync(this ICloudServiceOperations operations, string cloudServiceName, CloudServiceCreateArgs cloudService)
 {
     return(operations.CreateAsync(cloudServiceName, cloudService, CancellationToken.None));
 }