Пример #1
0
 /// <summary>
 /// ProcessRecord of the command.
 /// </summary>
 public override void ExecuteCmdlet()
 {
     if (ShouldProcess(Resources.VaultTarget, "set"))
     {
         try
         {
             if (this.BackupStorageRedundancy.HasValue)
             {
                 BackupResourceConfigResource vaultStorageRequest = new BackupResourceConfigResource();
                 BackupResourceConfig         properties          = new BackupResourceConfig();
                 vaultStorageRequest.Properties = properties;
                 vaultStorageRequest.Properties.StorageModelType = BackupStorageRedundancy.ToString();
                 RecoveryServicesClient.UpdateVaultStorageType(
                     this.Vault.ResourceGroupName, this.Vault.Name, vaultStorageRequest);
             }
             else
             {
                 throw new Exception(Properties.Resources.NoBackupPropertiesProvided);
             }
         }
         catch (Exception exception)
         {
             this.HandleException(exception);
         }
     }
 }
        public override void ExecuteCmdlet()
        {
            ExecutionBlock(() =>
            {
                // fetch source vault and target vault subscription
                Dictionary <CmdletModel.UriEnums, string> TargetVaultDict = HelperUtils.ParseUri(TargetVault.ID);
                string targetSub = TargetVaultDict[CmdletModel.UriEnums.Subscriptions];

                // set target subscription
                string subscriptionContext = ServiceClientAdapter.BmsAdapter.Client.SubscriptionId;
                ServiceClientAdapter.BmsAdapter.Client.SubscriptionId = targetSub;


                // Check if the Target vault is empty
                /// Check the containers count in target vault
                var protectionContainersCount = BackupUtils.GetProtectionContainersCount(TargetVault.Name, TargetVault.ResourceGroupName, ServiceClientAdapter);

                Logger.Instance.WriteDebug("Protection Containers within vault: " + TargetVault.Name + " and resource Group: "
                                           + TargetVault.ResourceGroupName + " are " + protectionContainersCount);

                if (protectionContainersCount > 0)
                {
                    throw new ArgumentException(string.Format(Resources.TargetVaultNotEmptyException));
                }

                /// check the count for VM backupItems

                int vmItemsCount = BackupUtils.GetProtectedItems(TargetVault.Name, TargetVault.ResourceGroupName,
                                                                 BackupManagementType.AzureIaasVM, WorkloadType.VM, ServiceClientAdapter).Count;

                Logger.Instance.WriteDebug("Protected VMs within vault: " + TargetVault.Name + " and resource Group: "
                                           + TargetVault.ResourceGroupName + " are " + vmItemsCount);

                if (vmItemsCount > 0)
                {
                    throw new ArgumentException(string.Format(Resources.TargetVaultNotEmptyException));
                }

                // Confirm the target vault storage type
                BackupResourceConfigResource getStorageResponse = ServiceClientAdapter.GetVaultStorageType(
                    TargetVault.ResourceGroupName, TargetVault.Name);

                Logger.Instance.WriteDebug("Target vault storage type: " + getStorageResponse.Properties.StorageType);

                // set subscription to original
                ServiceClientAdapter.BmsAdapter.Client.SubscriptionId = subscriptionContext;

                ConfirmAction(
                    Force.IsPresent,
                    string.Format(Resources.TargetVaultStorageRedundancy, TargetVault.Name, getStorageResponse.Properties.StorageType),
                    Resources.TargetVaultStorageRedundancy,
                    getStorageResponse.Properties.StorageType, () =>
                {
                    base.ExecuteCmdlet();

                    WriteObject(true);
                }
                    );
            }, ShouldProcess(TargetVault.Name, VerbsCommon.Set));
        }
Пример #3
0
 /// <summary>
 /// ProcessRecord of the command.
 /// </summary>
 public override void ExecuteCmdlet()
 {
     try
     {
         BackupResourceConfigResource getStorageResponse = RecoveryServicesClient.GetVaultStorageType(
             this.Vault.ResourceGroupName, this.Vault.Name);
         ASRVaultBackupProperties vaultBackupProperties = new ASRVaultBackupProperties();
         vaultBackupProperties.BackupStorageRedundancy = getStorageResponse.Properties.StorageType;
         this.WriteObject(vaultBackupProperties);
     }
     catch (Exception exception)
     {
         this.HandleException(exception);
     }
 }
 /// <summary>
 /// Updates vault storage model type.
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='vaultName'>
 /// The name of the recovery services vault.
 /// </param>
 /// <param name='resourceGroupName'>
 /// The name of the resource group where the recovery services vault is
 /// present.
 /// </param>
 /// <param name='parameters'>
 /// Vault storage config request
 /// </param>
 public static BackupResourceConfigResource Update(this IBackupResourceStorageConfigsOperations operations, string vaultName, string resourceGroupName, BackupResourceConfigResource parameters)
 {
     return(operations.UpdateAsync(vaultName, resourceGroupName, parameters).GetAwaiter().GetResult());
 }
 /// <summary>
 /// Updates vault storage model type.
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='vaultName'>
 /// The name of the recovery services vault.
 /// </param>
 /// <param name='resourceGroupName'>
 /// The name of the resource group where the recovery services vault is
 /// present.
 /// </param>
 /// <param name='parameters'>
 /// Vault storage config request
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async Task PatchAsync(this IBackupResourceStorageConfigsOperations operations, string vaultName, string resourceGroupName, BackupResourceConfigResource parameters, CancellationToken cancellationToken = default(CancellationToken))
 {
     (await operations.PatchWithHttpMessagesAsync(vaultName, resourceGroupName, parameters, null, cancellationToken).ConfigureAwait(false)).Dispose();
 }
 /// <summary>
 /// Updates vault storage model type.
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='vaultName'>
 /// The name of the recovery services vault.
 /// </param>
 /// <param name='resourceGroupName'>
 /// The name of the resource group where the recovery services vault is
 /// present.
 /// </param>
 /// <param name='parameters'>
 /// Vault storage config request
 /// </param>
 public static void Patch(this IBackupResourceStorageConfigsOperations operations, string vaultName, string resourceGroupName, BackupResourceConfigResource parameters)
 {
     operations.PatchAsync(vaultName, resourceGroupName, parameters).GetAwaiter().GetResult();
 }
 /// <summary>
 /// Updates vault storage model type.
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='vaultName'>
 /// The name of the recovery services vault.
 /// </param>
 /// <param name='resourceGroupName'>
 /// The name of the resource group where the recovery services vault is
 /// present.
 /// </param>
 /// <param name='parameters'>
 /// Vault storage config request
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async Task <BackupResourceConfigResource> UpdateAsync(this IBackupResourceStorageConfigsOperations operations, string vaultName, string resourceGroupName, BackupResourceConfigResource parameters, CancellationToken cancellationToken = default(CancellationToken))
 {
     using (var _result = await operations.UpdateWithHttpMessagesAsync(vaultName, resourceGroupName, parameters, null, cancellationToken).ConfigureAwait(false))
     {
         return(_result.Body);
     }
 }
Пример #8
0
        public override void ExecuteCmdlet()
        {
            ExecutionBlock(() =>
            {
                // fetch source vault and target vault subscription
                Dictionary <CmdletModel.UriEnums, string> SourceVaultDict = HelperUtils.ParseUri(SourceVault.ID);
                string sourceSub = SourceVaultDict[CmdletModel.UriEnums.Subscriptions];

                Dictionary <CmdletModel.UriEnums, string> TargetVaultDict = HelperUtils.ParseUri(TargetVault.ID);
                string targetSub = TargetVaultDict[CmdletModel.UriEnums.Subscriptions];

                // change subscription for HTTP requests
                string subscriptionContext = ServiceClientAdapter.BmsAdapter.Client.SubscriptionId;
                ServiceClientAdapter.BmsAdapter.Client.SubscriptionId = targetSub;

                // Check if the Target vault is empty
                // Check the containers count in target vault
                var protectionContainersCount = BackupUtils.GetProtectionContainersCount(TargetVault.Name, TargetVault.ResourceGroupName, ServiceClientAdapter);

                Logger.Instance.WriteDebug("Protection Containers within vault: " + TargetVault.Name + " and resource Group: "
                                           + TargetVault.ResourceGroupName + " are " + protectionContainersCount);

                if (protectionContainersCount > 0)
                {
                    throw new ArgumentException(string.Format(Resources.TargetVaultNotEmptyException));
                }

                // check the count for VM backupItems
                int vmItemsCount = BackupUtils.GetProtectedItems(TargetVault.Name, TargetVault.ResourceGroupName,
                                                                 BackupManagementType.AzureIaasVM, WorkloadType.VM, ServiceClientAdapter).Count;

                Logger.Instance.WriteDebug("Protected VMs within vault: " + TargetVault.Name + " and resource Group: "
                                           + TargetVault.ResourceGroupName + " are " + vmItemsCount);

                if (vmItemsCount > 0)
                {
                    throw new ArgumentException(string.Format(Resources.TargetVaultNotEmptyException));
                }

                // Confirm the target vault storage type
                BackupResourceConfigResource getStorageResponse = ServiceClientAdapter.GetVaultStorageType(
                    TargetVault.ResourceGroupName, TargetVault.Name);

                Logger.Instance.WriteDebug("Storage Type: " + getStorageResponse.Properties.StorageType);

                string correlationId = "";
                ConfirmAction(
                    Force.IsPresent,
                    string.Format(Resources.TargetVaultStorageRedundancy, TargetVault.Name, getStorageResponse.Properties.StorageType),
                    Resources.TargetVaultStorageRedundancy,
                    getStorageResponse.Properties.StorageType, () =>
                {
                    base.ExecuteCmdlet();

                    if (string.Compare(ParameterSetName, AzureRSVaultDataMoveParameterSet) == 0)
                    {
                        // Prepare Data Move
                        ServiceClientAdapter.BmsAdapter.Client.SubscriptionId = sourceSub;
                        PrepareDataMoveRequest prepareMoveRequest             = new PrepareDataMoveRequest();
                        prepareMoveRequest.TargetResourceId = TargetVault.ID;
                        prepareMoveRequest.TargetRegion     = TargetVault.Location;

                        // currently only allowing vault level data move
                        prepareMoveRequest.DataMoveLevel = "Vault";

                        if (RetryOnlyFailed.IsPresent)
                        {
                            prepareMoveRequest.IgnoreMoved = true;
                        }
                        else
                        {
                            prepareMoveRequest.IgnoreMoved = false;
                        }

                        Logger.Instance.WriteDebug("Retry only with failed items : " + prepareMoveRequest.IgnoreMoved);
                        Logger.Instance.WriteDebug("Location of Target vault: " + TargetVault.Location);

                        correlationId = ServiceClientAdapter.PrepareDataMove(SourceVault.Name, SourceVault.ResourceGroupName, prepareMoveRequest);
                    }
                    else
                    {
                        correlationId = CorrelationIdForDataMove;
                    }

                    // Trigger Data Move
                    ServiceClientAdapter.BmsAdapter.Client.SubscriptionId = targetSub;
                    TriggerDataMoveRequest triggerMoveRequest             = new TriggerDataMoveRequest();
                    triggerMoveRequest.SourceResourceId = SourceVault.ID;
                    triggerMoveRequest.SourceRegion     = SourceVault.Location;

                    // currently only allowing vault level data move
                    triggerMoveRequest.DataMoveLevel = "Vault";
                    triggerMoveRequest.CorrelationId = correlationId;
                    triggerMoveRequest.PauseGC       = false;

                    Logger.Instance.WriteDebug("Location of Source vault: " + SourceVault.Location);
                    ServiceClientAdapter.TriggerDataMove(TargetVault.Name, TargetVault.ResourceGroupName, triggerMoveRequest);

                    // set subscription to original
                    ServiceClientAdapter.BmsAdapter.Client.SubscriptionId = subscriptionContext;

                    WriteObject(ParamHelpMsgs.DSMove.CmdletOutput);
                }
                    );
            }, ShouldProcess(TargetVault.Name, VerbsCommon.Set));
        }
Пример #9
0
        public override void ExecuteCmdlet()
        {
            ExecutionBlock(() =>
            {
                base.ExecuteCmdlet();

                ResourceIdentifier resourceIdentifier = new ResourceIdentifier(VaultId);
                string vaultName         = resourceIdentifier.ResourceName;
                string resourceGroupName = resourceIdentifier.ResourceGroupName;
                Dictionary <Enum, object> providerParameters = new Dictionary <Enum, object>();

                string secondaryRegion = "";
                if (RestoreToSecondaryRegion.IsPresent)
                {
                    ARSVault vault  = ServiceClientAdapter.GetVault(resourceGroupName, vaultName);
                    secondaryRegion = BackupUtils.regionMap[vault.Location];
                    providerParameters.Add(CRRParams.SecondaryRegion, secondaryRegion);
                }

                providerParameters.Add(VaultParams.VaultName, vaultName);
                providerParameters.Add(VaultParams.ResourceGroupName, resourceGroupName);
                providerParameters.Add(VaultParams.VaultLocation, VaultLocation);
                providerParameters.Add(RestoreBackupItemParams.RecoveryPoint, RecoveryPoint);
                providerParameters.Add(RestoreVMBackupItemParams.OsaOption, UseOriginalStorageAccount.IsPresent);
                providerParameters.Add(RestoreFSBackupItemParams.ResolveConflict, ResolveConflict.ToString());
                providerParameters.Add(RestoreFSBackupItemParams.SourceFilePath, SourceFilePath);
                providerParameters.Add(RestoreFSBackupItemParams.TargetStorageAccountName, TargetStorageAccountName);
                providerParameters.Add(RestoreFSBackupItemParams.TargetFileShareName, TargetFileShareName);
                providerParameters.Add(RestoreFSBackupItemParams.TargetFolder, TargetFolder);
                providerParameters.Add(RestoreWLBackupItemParams.WLRecoveryConfig, WLRecoveryConfig);
                providerParameters.Add(RestoreVMBackupItemParams.RestoreDiskList, RestoreDiskList);
                providerParameters.Add(RestoreVMBackupItemParams.RestoreOnlyOSDisk, RestoreOnlyOSDisk);
                providerParameters.Add(RestoreVMBackupItemParams.RestoreAsUnmanagedDisks, RestoreAsUnmanagedDisks);
                providerParameters.Add(CRRParams.UseSecondaryRegion, RestoreToSecondaryRegion.IsPresent);
                providerParameters.Add(RestoreVMBackupItemParams.RestoreAsManagedDisk, RestoreAsManagedDisk.IsPresent);

                if (DiskEncryptionSetId != null)
                {
                    AzureVmRecoveryPoint rp = (AzureVmRecoveryPoint)RecoveryPoint;

                    BackupResourceEncryptionConfigResource vaultEncryptionSettings = ServiceClientAdapter.GetVaultEncryptionConfig(resourceGroupName, vaultName);

                    if ((vaultEncryptionSettings.Properties.EncryptionAtRestType == "CustomerManaged") && rp.IsManagedVirtualMachine && !(rp.EncryptionEnabled) && !(RestoreToSecondaryRegion.IsPresent))
                    {
                        providerParameters.Add(RestoreVMBackupItemParams.DiskEncryptionSetId, DiskEncryptionSetId);
                    }
                }

                if (TargetZoneNumber != null)
                {
                    // get storage type
                    BackupResourceConfigResource getStorageResponse = ServiceClientAdapter.GetVaultStorageType(resourceGroupName, vaultName);
                    string storageType = getStorageResponse.Properties.StorageType;
                    bool crrEnabled    = (bool)getStorageResponse.Properties.CrossRegionRestoreFlag;

                    if (storageType == AzureRmRecoveryServicesBackupStorageRedundancyType.ZoneRedundant.ToString() ||
                        (storageType == AzureRmRecoveryServicesBackupStorageRedundancyType.GeoRedundant.ToString() && crrEnabled))
                    {
                        AzureVmRecoveryPoint rp = (AzureVmRecoveryPoint)RecoveryPoint;
                        if (rp.RecoveryPointTier == RecoveryPointTier.VaultStandard)  // RP recovery type should be vault only
                        {
                            if (rp.Zones != null)
                            {
                                //target region should support Zones

                                /*if (RestoreToSecondaryRegion.IsPresent)
                                 * {
                                 *  FeatureSupportRequest iaasvmFeatureRequest = new FeatureSupportRequest();
                                 *  ServiceClientAdapter.BmsAdapter.Client.FeatureSupport.ValidateWithHttpMessagesAsync(secondaryRegion, iaasvmFeatureRequest);
                                 * }*/
                                providerParameters.Add(RecoveryPointParams.TargetZone, TargetZoneNumber);
                            }
                            else
                            {
                                throw new ArgumentException(string.Format(Resources.RecoveryPointZonePinnedException));
                            }
                        }
                        else
                        {
                            throw new ArgumentException(string.Format(Resources.RecoveryPointVaultRecoveryTypeException));
                        }
                    }
                    else
                    {
                        throw new ArgumentException(string.Format(Resources.ZonalRestoreVaultStorageRedundancyException));
                    }
                }

                if (StorageAccountName != null)
                {
                    providerParameters.Add(RestoreBackupItemParams.StorageAccountName, StorageAccountName);
                }

                if (StorageAccountResourceGroupName != null)
                {
                    providerParameters.Add(RestoreBackupItemParams.StorageAccountResourceGroupName, StorageAccountResourceGroupName);
                }

                if (TargetResourceGroupName != null)
                {
                    providerParameters.Add(RestoreVMBackupItemParams.TargetResourceGroupName, TargetResourceGroupName);
                }

                if (SourceFileType != null)
                {
                    providerParameters.Add(RestoreFSBackupItemParams.SourceFileType, SourceFileType.ToString());
                }

                if (MultipleSourceFilePath != null)
                {
                    providerParameters.Add(RestoreFSBackupItemParams.MultipleSourceFilePath, MultipleSourceFilePath);
                }

                PsBackupProviderManager providerManager =
                    new PsBackupProviderManager(providerParameters, ServiceClientAdapter);
                IPsBackupProvider psBackupProvider = null;
                if (string.Compare(ParameterSetName, AzureWorkloadParameterSet) != 0)
                {
                    psBackupProvider = providerManager.GetProviderInstance(
                        RecoveryPoint.WorkloadType, RecoveryPoint.BackupManagementType);
                }
                else
                {
                    psBackupProvider = providerManager.GetProviderInstance(
                        WorkloadType.MSSQL, BackupManagementType.AzureWorkload);
                }
                var jobResponse = psBackupProvider.TriggerRestore();

                if (RestoreToSecondaryRegion.IsPresent)
                {
                    var operationId = jobResponse.Request.RequestUri.Segments.Last();
                    var response    = ServiceClientAdapter.GetCrrOperationStatus(secondaryRegion, operationId);

                    string jobIdJson   = JsonConvert.SerializeObject(response.Body.Properties);
                    string[] jobSplits = jobIdJson.Split(new char[] { '\"' });
                    string jobId       = jobSplits[jobSplits.Length - 2];
                    WriteObject(GetCrrJobObject(secondaryRegion, VaultId, jobId));
                }
                else
                {
                    HandleCreatedJob(
                        jobResponse,
                        Resources.RestoreOperation,
                        vaultName: vaultName,
                        resourceGroupName: resourceGroupName);
                }
            }, ShouldProcess(RecoveryPoint != null ? RecoveryPoint.ItemName : WLRecoveryConfig.ToString(), VerbsData.Restore));
        }
Пример #10
0
        /// <summary>
        /// Updates vault storage model type.
        /// </summary>
        /// <param name='vaultName'>
        /// The name of the recovery services vault.
        /// </param>
        /// <param name='resourceGroupName'>
        /// The name of the resource group where the recovery services vault is
        /// present.
        /// </param>
        /// <param name='parameters'>
        /// Vault storage config request
        /// </param>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="CloudException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <exception cref="System.ArgumentNullException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public async Task <AzureOperationResponse> PatchWithHttpMessagesAsync(string vaultName, string resourceGroupName, BackupResourceConfigResource parameters, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (vaultName == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "vaultName");
            }
            if (resourceGroupName == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
            }
            if (Client.SubscriptionId == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
            }
            if (parameters == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "parameters");
            }
            string apiVersion = "2016-12-01";
            // Tracing
            bool   _shouldTrace  = ServiceClientTracing.IsEnabled;
            string _invocationId = null;

            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("apiVersion", apiVersion);
                tracingParameters.Add("vaultName", vaultName);
                tracingParameters.Add("resourceGroupName", resourceGroupName);
                tracingParameters.Add("parameters", parameters);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "Patch", tracingParameters);
            }
            // Construct URL
            var _baseUrl = Client.BaseUri.AbsoluteUri;
            var _url     = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{vaultName}/backupstorageconfig/vaultstorageconfig").ToString();

            _url = _url.Replace("{vaultName}", System.Uri.EscapeDataString(vaultName));
            _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
            _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
            List <string> _queryParameters = new List <string>();

            if (apiVersion != null)
            {
                _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
            }
            if (_queryParameters.Count > 0)
            {
                _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
            }
            // Create HTTP transport objects
            var _httpRequest = new HttpRequestMessage();
            HttpResponseMessage _httpResponse = null;

            _httpRequest.Method     = new HttpMethod("PATCH");
            _httpRequest.RequestUri = new System.Uri(_url);
            // Set Headers
            if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
            {
                _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
            }
            if (Client.AcceptLanguage != null)
            {
                if (_httpRequest.Headers.Contains("accept-language"))
                {
                    _httpRequest.Headers.Remove("accept-language");
                }
                _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
            }


            if (customHeaders != null)
            {
                foreach (var _header in customHeaders)
                {
                    if (_httpRequest.Headers.Contains(_header.Key))
                    {
                        _httpRequest.Headers.Remove(_header.Key);
                    }
                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
                }
            }

            // Serialize Request
            string _requestContent = null;

            if (parameters != null)
            {
                _requestContent      = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings);
                _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
                _httpRequest.Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
            }
            // Set Credentials
            if (Client.Credentials != null)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            }
            // Send Request
            if (_shouldTrace)
            {
                ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);

            if (_shouldTrace)
            {
                ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
            }
            System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
            cancellationToken.ThrowIfCancellationRequested();
            string _responseContent = null;

            if ((int)_statusCode != 204)
            {
                var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                try
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                    CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject <CloudError>(_responseContent, Client.DeserializationSettings);
                    if (_errorBody != null)
                    {
                        ex      = new CloudException(_errorBody.Message);
                        ex.Body = _errorBody;
                    }
                }
                catch (JsonException)
                {
                    // Ignore the exception
                }
                ex.Request  = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
                ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
                if (_httpResponse.Headers.Contains("x-ms-request-id"))
                {
                    ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
                }
                if (_shouldTrace)
                {
                    ServiceClientTracing.Error(_invocationId, ex);
                }
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            // Create Result
            var _result = new AzureOperationResponse();

            _result.Request  = _httpRequest;
            _result.Response = _httpResponse;
            if (_httpResponse.Headers.Contains("x-ms-request-id"))
            {
                _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
            }
            if (_shouldTrace)
            {
                ServiceClientTracing.Exit(_invocationId, _result);
            }
            return(_result);
        }
Пример #11
0
 /// <summary>
 /// Method to Update Azure Recovery Services Vault Backup Properties
 /// </summary>
 /// <param name="resouceGroupName">Name of the resouce group</param>
 /// <param name="vaultName">Name of the vault</param>
 /// <param name="vaultStorageUpdateRequest">Backup Properties Update</param>
 /// <returns>Azure Operation response object.</returns>
 public void UpdateVaultStorageType(string resouceGroupName, string vaultName,
                                    BackupResourceConfigResource backupStorageConfig)
 {
     GetRecoveryServicesBackupClient.BackupResourceStorageConfigs.UpdateWithHttpMessagesAsync(
         vaultName, resouceGroupName, backupStorageConfig, GetRequestHeaders());
 }
 /// <summary>
 /// Method to Patch Azure Recovery Services Vault Backup Properties
 /// </summary>
 /// <param name="resouceGroupName">Name of the resouce group</param>
 /// <param name="vaultName">Name of the vault</param>
 /// <param name="vaultStorageUpdateRequest">Backup Properties Update</param>
 /// <returns>Azure Operation response object.</returns>
 public void PatchVaultStorageConfigProperties(string resouceGroupName, string vaultName,
                                               BackupResourceConfigResource backupStorageConfig)
 {
     GetRecoveryServicesBackupClient.BackupResourceStorageConfigs.PatchWithHttpMessagesAsync(
         vaultName, resouceGroupName, backupStorageConfig, GetRequestHeaders());
 }