/// <summary>
 /// Reprotect operation for the given protection entity.
 /// </summary>
 /// <param name='operations'>
 /// Reference to the
 /// Microsoft.WindowsAzure.Management.SiteRecovery.IProtectionEntityOperations.
 /// </param>
 /// <param name='protectionContainerId'>
 /// Required. Parent Protection Container ID.
 /// </param>
 /// <param name='protectionEntityId'>
 /// Required. Protection entity ID.
 /// </param>
 /// <param name='parameters'>
 /// Required. Reprotect request after failover.
 /// </param>
 /// <param name='customRequestHeaders'>
 /// Optional. Request header parameters.
 /// </param>
 /// <returns>
 /// The response model for the Job details object.
 /// </returns>
 public static JobResponse Reprotect(this IProtectionEntityOperations operations, string protectionContainerId, string protectionEntityId, ReprotectRequest parameters, CustomRequestHeaders customRequestHeaders)
 {
     return Task.Factory.StartNew((object s) => 
     {
         return ((IProtectionEntityOperations)s).ReprotectAsync(protectionContainerId, protectionEntityId, parameters, customRequestHeaders);
     }
     , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
 }
 /// <summary>
 /// Reprotect operation for the given protection entity.
 /// </summary>
 /// <param name='operations'>
 /// Reference to the
 /// Microsoft.WindowsAzure.Management.SiteRecovery.IProtectionEntityOperations.
 /// </param>
 /// <param name='protectionContainerId'>
 /// Required. Parent Protection Container ID.
 /// </param>
 /// <param name='protectionEntityId'>
 /// Required. Protection entity ID.
 /// </param>
 /// <param name='parameters'>
 /// Required. Reprotect request after failover.
 /// </param>
 /// <param name='customRequestHeaders'>
 /// Optional. Request header parameters.
 /// </param>
 /// <returns>
 /// The response model for the Job details object.
 /// </returns>
 public static Task<JobResponse> ReprotectAsync(this IProtectionEntityOperations operations, string protectionContainerId, string protectionEntityId, ReprotectRequest parameters, CustomRequestHeaders customRequestHeaders)
 {
     return operations.ReprotectAsync(protectionContainerId, protectionEntityId, parameters, customRequestHeaders, CancellationToken.None);
 }
 /// <summary>
 /// Re-protects the Azure Site Recovery protection entity.
 /// </summary>
 /// <param name="protectionContainerId">Protection Container ID</param>
 /// <param name="protectionEntityId">Recovery Plan ID</param>
 /// <param name="request">Re-protect request.</param>
 /// <returns>Job response</returns>
 public JobResponse StartAzureSiteRecoveryReprotection(
     string protectionContainerId,
     string protectionEntityId,
     ReprotectRequest request)
 {
     return this.GetSiteRecoveryClient().ProtectionEntity.Reprotect(
         protectionContainerId,
         protectionEntityId,
         request,
         this.GetRequestHeaders());
 }
        /// <summary>
        /// Set PE protection.
        /// </summary>
        private void SetPEReprotect()
        {
            if ((this.Direction == Constants.PrimaryToRecovery &&
                    this.ProtectionEntity.ActiveLocation == Constants.RecoveryLocation) ||
                (this.Direction == Constants.RecoveryToPrimary &&
                    this.ProtectionEntity.ActiveLocation == Constants.PrimaryLocation))
            {
                throw new ArgumentException("Parameter value is not correct.", "Direction");
            }

            var request = new ReprotectRequest();

            if (this.ProtectionEntity == null)
            {
                var pe = RecoveryServicesClient.GetAzureSiteRecoveryProtectionEntity(
                    this.ProtectionContainerId,
                    this.ProtectionEntityId);
                this.ProtectionEntity = new ASRProtectionEntity(pe.ProtectionEntity);

                this.ValidateUsageById(
                    this.ProtectionEntity.ReplicationProvider,
                    this.ProtectionEntityId);
            }

            request.ReplicationProviderSettings = string.Empty;

            if (this.ProtectionEntity.ReplicationProvider == Constants.HyperVReplicaAzure)
            {
                if (this.Direction == Constants.PrimaryToRecovery)
                {
                    var blob = new AzureReProtectionInput();
                    blob.HvHostVmId = this.ProtectionEntity.FabricObjectId;
                    blob.VmName = this.ProtectionEntity.Name;

                    blob.OSType = this.ProtectionEntity.OS;
                    blob.VHDId = this.ProtectionEntity.OSDiskId;

                    request.ReplicationProviderSettings = DataContractUtils.Serialize<AzureReProtectionInput>(blob);
                }
            }

            request.ReplicationProvider = this.ProtectionEntity.ReplicationProvider;
            request.FailoverDirection = this.Direction;

            this.jobResponse = RecoveryServicesClient.StartAzureSiteRecoveryReprotection(
                this.ProtectionContainerId,
                this.ProtectionEntityId,
                request);

            this.WriteJob(this.jobResponse.Job);

            if (this.WaitForCompletion.IsPresent)
            {
                this.WaitForJobCompletion(this.jobResponse.Job.ID);
            }
        }
        /// <summary>
        /// Sets RP Recovery protection.
        /// </summary>
        private void SetRpReprotect()
        {
            var request = new ReprotectRequest();

            if (this.RecoveryPlan == null)
            {
                var rp = RecoveryServicesClient.GetAzureSiteRecoveryRecoveryPlan(
                    this.RPId);
                this.RecoveryPlan = new ASRRecoveryPlan(rp.RecoveryPlan);

                this.ValidateUsageById(
                    this.RecoveryPlan.ReplicationProvider,
                    Constants.RPId);
            }

            request.ReplicationProvider = this.RecoveryPlan.ReplicationProvider;
            request.ReplicationProviderSettings = string.Empty;

            request.FailoverDirection = this.Direction; 
            
            this.jobResponse = RecoveryServicesClient.UpdateAzureSiteRecoveryProtection(
                this.RPId);

            this.WriteJob(this.jobResponse.Job);

            if (this.WaitForCompletion.IsPresent)
            {
                this.WaitForJobCompletion(this.jobResponse.Job.ID);
            }
        }
        public void SanE2ETest()
        {
            using (UndoContext context = UndoContext.Current)
            {
                try
                {
                    context.Start();
                    var client = GetSiteRecoveryClient(CustomHttpHandler);

                    var requestHeaders = RequestHeaders;
                    requestHeaders.AgentAuthenticationHeader = GenerateAgentAuthenticationHeader(requestHeaders.ClientRequestId);

                    string containerId = "fc1e58ee-b96a-46fe-8afe-330f7ea545a1_d6a83495-5a6a-4ceb-9dc3-2829f6719032";
                    string entityId = "a7b4f73c-7a02-4fa2-b895-ddfcfceb0d7d";
                    string primaryServerId = "fc1e58ee-b96a-46fe-8afe-330f7ea545a1";
                    string recoveryServerId = "e19be056-3a6b-4239-8d01-b0820bc1aeaf";

                    //var responseServer = client.Servers.List(requestHeaders);

                    //var responsePE = client.ProtectionEntity.Get(containerId, entityId, RequestHeaders);

                    var responseStoragePoolPaired = client.StoragePoolMappings.List(primaryServerId, recoveryServerId, requestHeaders);

                    var responseStoragePrimary = client.Storages.List(primaryServerId, requestHeaders);
                    AsrStorage storagePoolPrimary = null;
                    foreach (var storage in responseStoragePrimary.Storages)
                    {
                        if (storage.Type == "Pool")
                        {
                            if (storage.StoragePools.Count > 0)
                            {
                                storagePoolPrimary = storage;
                            }
                        }
                    }

                    var responseStorageRecovery = client.Storages.List(recoveryServerId, requestHeaders);
                    AsrStorage storagePoolRecovery = null;
                    foreach (var storage in responseStorageRecovery.Storages)
                    {
                        if (storage.Type == "Pool")
                        {
                            if (storage.StoragePools.Count > 0)
                            {
                                storagePoolRecovery = storage;
                            }
                        }
                    }

                    StoragePoolMappingInput storagePoolMappingInput = new StoragePoolMappingInput();
                    storagePoolMappingInput.PrimaryServerId = primaryServerId;
                    storagePoolMappingInput.RecoveryServerId = recoveryServerId;
                    storagePoolMappingInput.PrimaryArrayId = storagePoolPrimary.ID;
                    storagePoolMappingInput.RecoveryArrayId = storagePoolRecovery.ID;
                    storagePoolMappingInput.PrimaryStoragePoolId = storagePoolPrimary.StoragePools[0].ID;
                    storagePoolMappingInput.RecoveryStoragePoolId = storagePoolRecovery.StoragePools[0].ID;
                    var responseStoragePoolPair = client.StoragePoolMappings.Create(storagePoolMappingInput, requestHeaders);
                    var responseStoragePoolUnpair = client.StoragePoolMappings.Delete(storagePoolMappingInput, requestHeaders);

                    FailoverRequest request = new FailoverRequest();

                    // Planned Failover RG
                    request = new PlannedFailoverRequest();
                    request.ReplicationProvider = "San";
                    request.FailoverDirection = "PrimaryToRecovery";
                    var response = client.ProtectionEntity.PlannedFailover(containerId, entityId, (PlannedFailoverRequest)request, requestHeaders);
                    ValidateResponse(response);
                    WaitForJobToComplete(client, response.Job.ID);

                    // Reverse protect RG
                    request = new ReprotectRequest();
                    request.ReplicationProvider = "San";
                    request.FailoverDirection = "RecoveryToPrimary";
                    response = client.ProtectionEntity.Reprotect(containerId, entityId, (ReprotectRequest)request, requestHeaders);
                    ValidateResponse(response);
                    WaitForJobToComplete(client, response.Job.ID);

                    // UnPlanned Failover RG
                    request = new UnplannedFailoverRequest();
                    request.ReplicationProvider = "San";
                    request.FailoverDirection = "RecoveryToPrimary";
                    response = client.ProtectionEntity.UnplannedFailover(containerId, entityId, (UnplannedFailoverRequest)request, requestHeaders);
                    ValidateResponse(response);
                    WaitForJobToComplete(client, response.Job.ID);

                    // Reverse protect RG
                    request = new ReprotectRequest();
                    request.ReplicationProvider = "San";
                    request.FailoverDirection = "PrimaryToRecovery";
                    response = client.ProtectionEntity.Reprotect(containerId, entityId, (ReprotectRequest)request, requestHeaders);
                    ValidateResponse(response);
                    WaitForJobToComplete(client, response.Job.ID);

                    // Test Failover RG
                    request = new TestFailoverRequest();
                    request.ReplicationProvider = "San";
                    request.FailoverDirection = "PrimaryToRecovery";
                    ((TestFailoverRequest)request).NetworkType = "NoNetworkAttachAsInput";
                    ((TestFailoverRequest)request).NetworkID = "xxx";
                    response = client.ProtectionEntity.TestFailover(containerId, entityId, (TestFailoverRequest)request, requestHeaders);
                    ValidateResponse(response);
                }
                catch
                {
                    //skip
                }
            }
        }
        public void ReprotectProtectionEntityTest()
        {
            using (UndoContext context = UndoContext.Current)
            {
                context.Start();
                var client = GetSiteRecoveryClient(CustomHttpHandler);

                var requestHeaders = RequestHeaders;
                requestHeaders.AgentAuthenticationHeader = GenerateAgentAuthenticationHeader(requestHeaders.ClientRequestId);

                var responsePC = client.ProtectionContainer.List(RequestHeaders);
                JobResponse response = new JobResponse();
                bool desiredPEFound = false;
                foreach (var pc in responsePC.ProtectionContainers)
                {
                    var responsePEs = client.ProtectionEntity.List(pc.ID, RequestHeaders);

                    ReprotectRequest request = new ReprotectRequest();
                    request.ReplicationProvider = "";
                    request.ReplicationProviderSettings = "";


                    foreach (var pe in responsePEs.ProtectionEntities)
                    {
                        if (pe.CanReverseReplicate == true)
                        {
                            if (pe.ActiveLocation == "Primary")
                            {
                                request.FailoverDirection = "PrimaryToRecovery";
                            }
                            else
                            {
                                request.FailoverDirection = "RecoveryToPrimary";
                            }

                            response = client.ProtectionEntity.Reprotect(
                                pe.ProtectionContainerId,
                                pe.ID,
                                request,
                                requestHeaders);
                            desiredPEFound = true;
                            break;
                        }
                    }

                    if (desiredPEFound)
                    {
                        break;
                    }
                }

                Assert.NotNull(response.Job);
                Assert.NotNull(response.Job.ID);
                Assert.True(response.Job.Errors.Count < 1, "Errors found while doing unplanned failover operation");
                Assert.Equal(HttpStatusCode.OK, response.StatusCode);
            }
        }