/// <summary>
 /// Planned failover of a 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. Planned failover request.
 /// </param>
 /// <param name='customRequestHeaders'>
 /// Optional. Request header parameters.
 /// </param>
 /// <returns>
 /// The response model for the Job details object.
 /// </returns>
 public static JobResponse PlannedFailover(this IProtectionEntityOperations operations, string protectionContainerId, string protectionEntityId, PlannedFailoverRequest parameters, CustomRequestHeaders customRequestHeaders)
 {
     return Task.Factory.StartNew((object s) => 
     {
         return ((IProtectionEntityOperations)s).PlannedFailoverAsync(protectionContainerId, protectionEntityId, parameters, customRequestHeaders);
     }
     , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
 }
 /// <summary>
 /// Planned failover of a 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. Planned failover request.
 /// </param>
 /// <param name='customRequestHeaders'>
 /// Optional. Request header parameters.
 /// </param>
 /// <returns>
 /// The response model for the Job details object.
 /// </returns>
 public static Task<JobResponse> PlannedFailoverAsync(this IProtectionEntityOperations operations, string protectionContainerId, string protectionEntityId, PlannedFailoverRequest parameters, CustomRequestHeaders customRequestHeaders)
 {
     return operations.PlannedFailoverAsync(protectionContainerId, protectionEntityId, parameters, customRequestHeaders, CancellationToken.None);
 }
 /// <summary>
 /// Starts Azure Site Recovery Planned failover.
 /// </summary>
 /// <param name="protectionContainerId">Protection Container ID</param>
 /// <param name="protectionEntityId">Protection entity ID</param>
 /// <param name="plannedFailoverRequest">Planned failover request</param>
 /// <returns>Job response</returns>
 public JobResponse StartAzureSiteRecoveryPlannedFailover(
     string protectionContainerId,
     string protectionEntityId,
     PlannedFailoverRequest plannedFailoverRequest)
 {
     return this.GetSiteRecoveryClient().ProtectionEntity.PlannedFailover(
         protectionContainerId,
         protectionEntityId,
         plannedFailoverRequest,
         this.GetRequestHeaders());
 }
        /// <summary>
        /// Starts PE Planned failover.
        /// </summary>
        private void StartPEPlannedFailover()
        {
            var request = new PlannedFailoverRequest();

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

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

            if (this.ProtectionEntity.ReplicationProvider == Constants.HyperVReplicaAzure)
            {
                if (this.Direction == Constants.PrimaryToRecovery)
                {
                    var blob = new AzureFailoverInput();
                    blob.VaultLocation = this.GetCurrentValutLocation();
                    request.ReplicationProviderSettings = DataContractUtils.Serialize<AzureFailoverInput>(blob);
                }
                else
                {
                    var blob = new AzureFailbackInput();
                    blob.CreateRecoveryVmIfDoesntExist = false;
                    blob.SkipDataSync = this.Optimize == Constants.ForDowntime ? true : false;
                    request.ReplicationProviderSettings = DataContractUtils.Serialize<AzureFailbackInput>(blob);
                }
            }
            else
            {
                request.ReplicationProviderSettings = string.Empty;
            }

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

            this.jobResponse =
                RecoveryServicesClient.StartAzureSiteRecoveryPlannedFailover(
                this.ProtectionContainerId,
                this.ProtectionEntityId,
                request);
            this.WriteJob(this.jobResponse.Job);

            if (this.WaitForCompletion.IsPresent)
            {
                this.WaitForJobCompletion(this.jobResponse.Job.ID);
            }
        }
        /// <summary>
        /// Starts PE Planned failover.
        /// </summary>
        private void StartPEPlannedFailover()
        {
            var pfoReqeust = new PlannedFailoverRequest();
            pfoReqeust.FailoverDirection = this.Direction;
            this.jobResponse =
                RecoveryServicesClient.StartAzureSiteRecoveryPlannedFailover(
                this.ProtectionContainerId,
                this.ProtectionEntityId,
                pfoReqeust);
            this.WriteJob(this.jobResponse.Job);

            if (this.WaitForCompletion.IsPresent)
            {
                this.WaitForJobCompletion(this.jobResponse.Job.ID);
            }
        }
        public void E2A_PlannedFailoverTest()
        {
            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)
                {
                    if (pc.Role != "Primary")
                    {
                        continue;
                    }

                    var responsePEs = client.ProtectionEntity.List(pc.ID, RequestHeaders);
                    response = null;
                    foreach (var pe in responsePEs.ProtectionEntities)
                    {
                        if (pe.CanFailover == true && pe.ActiveLocation == "Recovery" && pe.ReplicationProvider == "HyperVReplicaAzure")
                        {
                            PlannedFailoverRequest request = new PlannedFailoverRequest();
                            request.ReplicationProvider = pe.ReplicationProvider;
                            if (pe.ActiveLocation == "Primary")
                            {
                                request.FailoverDirection = "PrimaryToRecovery";
                                AzureFailoverInput blob = new AzureFailoverInput();
                                blob.VaultLocation = VaultLocation;
                                request.ReplicationProviderSettings = DataContractUtils.Serialize<AzureFailoverInput>(blob);
                            }
                            else
                            {
                                request.FailoverDirection = "RecoveryToPrimary";
                                var blob = new AzureFailbackInput();
                                blob.CreateRecoveryVmIfDoesntExist = false;
                                blob.SkipDataSync = false;
                                request.ReplicationProviderSettings = DataContractUtils.Serialize<AzureFailbackInput>(blob);
                            }

                            response = client.ProtectionEntity.PlannedFailover(
                                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 failback operation");
                Assert.Equal(HttpStatusCode.OK, response.StatusCode);
            }
        }
        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
                }
            }
        }