/// <summary>
 /// Update Azure VM Properties
 /// </summary>
 /// <param name="fabricName">Fabric Name</param>
 /// <param name="protectionContainerName">Protection Container Name</param>
 /// <param name="replicationProtectedItemName">Replication Protected Item</param>
 /// <param name="input">Update Replication Protected Item Input</param>
 /// <returns></returns>
 public LongRunningOperationResponse UpdateVmProperties(string fabricName,
     string protectionContainerName,
     string replicationProtectedItemName,
     UpdateReplicationProtectedItemInput input)
 {
     return this.GetSiteRecoveryClient().ReplicationProtectedItem.BeginUpdateProtection(
         fabricName,
         protectionContainerName,
         replicationProtectedItemName,
         input,
         this.GetRequestHeaders());
 }
        /// <summary>
        /// ProcessRecord of the command.
        /// </summary>
        public override void ExecuteCmdlet()
        {
            try
            {
                ProtectableItemResponse protectableItemResponse =
                                                    RecoveryServicesClient.GetAzureSiteRecoveryProtectableItem(Utilities.GetValueFromArmId(this.VirtualMachine.ID, ARMResourceTypeConstants.ReplicationFabrics),
                                                    this.VirtualMachine.ProtectionContainerId, this.VirtualMachine.Name);

                if (protectableItemResponse.ProtectableItem.Properties.ReplicationProtectedItemId == null)
                {
                    this.WriteWarning(Properties.Resources.ProtectionIsNotEnabledForVM.ToString());
                    return;
                }

                ReplicationProtectedItemResponse replicationProtectedItemResponse =
                            RecoveryServicesClient.GetAzureSiteRecoveryReplicationProtectedItem(Utilities.GetValueFromArmId(this.VirtualMachine.ID, ARMResourceTypeConstants.ReplicationFabrics),
                            this.VirtualMachine.ProtectionContainerId, Utilities.GetValueFromArmId(protectableItemResponse.ProtectableItem.Properties.ReplicationProtectedItemId, ARMResourceTypeConstants.ReplicationProtectedItems));

                string provider =
                    replicationProtectedItemResponse.ReplicationProtectedItem.Properties.ProviderSpecificDetails.InstanceType;

                // Check for Replication Provider type HyperVReplicaAzure/InMageAzure/InMageAzureV2
                if (!(0 == string.Compare(provider, Constants.HyperVReplicaAzure, StringComparison.OrdinalIgnoreCase) ||
                    0 == string.Compare(provider, Constants.InMageAzure, StringComparison.OrdinalIgnoreCase) ||
                    0 == string.Compare(provider, Constants.InMageAzureV2, StringComparison.OrdinalIgnoreCase)))
                {
                    this.WriteWarning(Properties.Resources.UnsupportedReplicationProvidedForUpdateVmProperties.ToString());
                    return;
                }

                // Check for at least one option
                if (string.IsNullOrEmpty(this.Name) &&
                    string.IsNullOrEmpty(this.Size) &&
                    string.IsNullOrEmpty(this.PrimaryNic) &&
                    string.IsNullOrEmpty(this.RecoveryNetworkId) &&
                    string.IsNullOrEmpty(this.LicenseType))
                {
                    this.WriteWarning(Properties.Resources.ArgumentsMissingForUpdateVmProperties.ToString());
                    return;
                }

                // Both primary & recovery inputs should be present
                if (string.IsNullOrEmpty(this.PrimaryNic) ^
                    string.IsNullOrEmpty(this.RecoveryNetworkId))
                {
                    this.WriteWarning(Properties.Resources.NetworkArgumentsMissingForUpdateVmProperties.ToString());
                    return;
                }
                string vmName = this.Name;
                string vmSize = this.Size;
                string vmRecoveryNetworkId = this.RecoveryNetworkId;
                string licenseType = this.LicenseType;
                List<VMNicInputDetails> vMNicInputDetailsList = new List<VMNicInputDetails>();
                VMNicDetails vMNicDetailsToBeUpdated;


                if (0 == string.Compare(provider, Constants.HyperVReplicaAzure, StringComparison.OrdinalIgnoreCase))
                {
                    HyperVReplicaAzureReplicationDetails providerSpecificDetails =
                            (HyperVReplicaAzureReplicationDetails)replicationProtectedItemResponse.ReplicationProtectedItem.Properties.ProviderSpecificDetails;
                    if (string.IsNullOrEmpty(this.Name))
                    {
                        vmName = providerSpecificDetails.RecoveryAzureVMName;
                    }

                    if (string.IsNullOrEmpty(this.Size))
                    {
                        vmSize = providerSpecificDetails.RecoveryAzureVMSize;
                    }

                    if (string.IsNullOrEmpty(this.RecoveryNetworkId))
                    {
                        vmRecoveryNetworkId = providerSpecificDetails.SelectedRecoveryAzureNetworkId;
                    }

                    if (string.IsNullOrEmpty(this.LicenseType))
                    {
                        licenseType = providerSpecificDetails.LicenseType;
                    }

                    if (!string.IsNullOrEmpty(this.PrimaryNic))
                    {
                        if (providerSpecificDetails.VMNics != null)
                        {
                            vMNicDetailsToBeUpdated = providerSpecificDetails.VMNics.SingleOrDefault(n => string.Compare(n.NicId, this.PrimaryNic, StringComparison.OrdinalIgnoreCase) == 0);
                            if (vMNicDetailsToBeUpdated != null)
                            {
                                VMNicInputDetails vMNicInputDetails = new VMNicInputDetails();

                                vMNicInputDetails.NicId = this.PrimaryNic;
                                vMNicInputDetails.RecoveryVMSubnetName = this.RecoveryNicSubnetName;
                                vMNicInputDetails.ReplicaNicStaticIPAddress = this.RecoveryNicStaticIPAddress;
                                vMNicInputDetails.SelectionType = string.IsNullOrEmpty(this.NicSelectionType) ? Constants.SelectedByUser : this.NicSelectionType;
                                vMNicInputDetailsList.Add(vMNicInputDetails);

                                IEnumerable<VMNicDetails> vMNicDetailsListRemaining = providerSpecificDetails.VMNics.Where(n => string.Compare(n.NicId, this.PrimaryNic, StringComparison.OrdinalIgnoreCase) != 0);
                                foreach (VMNicDetails nDetails in vMNicDetailsListRemaining)
                                {
                                    vMNicInputDetails = new VMNicInputDetails();

                                    vMNicInputDetails.NicId = nDetails.NicId;
                                    vMNicInputDetails.RecoveryVMSubnetName = nDetails.RecoveryVMSubnetName;
                                    vMNicInputDetails.ReplicaNicStaticIPAddress = nDetails.ReplicaNicStaticIPAddress;
                                    vMNicInputDetails.SelectionType = nDetails.SelectionType;
                                    vMNicInputDetailsList.Add(vMNicInputDetails);
                                }
                            }
                            else
                            {
                                throw new PSInvalidOperationException(Properties.Resources.NicNotFoundInVMForUpdateVmProperties);
                            }
                        }
                    }
                    else
                    {
                        VMNicInputDetails vMNicInputDetails = new VMNicInputDetails();
                        foreach (VMNicDetails nDetails in providerSpecificDetails.VMNics)
                        {
                            vMNicInputDetails = new VMNicInputDetails();

                            vMNicInputDetails.NicId = nDetails.NicId;
                            vMNicInputDetails.RecoveryVMSubnetName = nDetails.RecoveryVMSubnetName;
                            vMNicInputDetails.ReplicaNicStaticIPAddress = nDetails.ReplicaNicStaticIPAddress;
                            vMNicInputDetails.SelectionType = nDetails.SelectionType;
                            vMNicInputDetailsList.Add(vMNicInputDetails);
                        }
                    }
                }
                else if (0 == string.Compare(provider, Constants.InMageAzure, StringComparison.OrdinalIgnoreCase) ||
                    0 == string.Compare(provider, Constants.InMageAzureV2, StringComparison.OrdinalIgnoreCase))
                {
                    InMageAzureV2ProviderSpecificSettings providerSpecificDetails =
                            (InMageAzureV2ProviderSpecificSettings)replicationProtectedItemResponse.ReplicationProtectedItem.Properties.ProviderSpecificDetails;
                    if (string.IsNullOrEmpty(this.Name))
                    {
                        vmName = providerSpecificDetails.RecoveryAzureVMName;
                    }

                    if (string.IsNullOrEmpty(this.Size))
                    {
                        vmSize = providerSpecificDetails.RecoveryAzureVMSize;
                    }

                    if (string.IsNullOrEmpty(this.RecoveryNetworkId))
                    {
                        vmRecoveryNetworkId = providerSpecificDetails.SelectedRecoveryAzureNetworkId;
                    }

                    if (string.IsNullOrEmpty(this.LicenseType))
                    {
                        licenseType = providerSpecificDetails.LicenseType;
                    }

                    if (!string.IsNullOrEmpty(this.PrimaryNic))
                    {
                        if (providerSpecificDetails.VMNics != null)
                        {
                            vMNicDetailsToBeUpdated = providerSpecificDetails.VMNics.SingleOrDefault(n => string.Compare(n.NicId, this.PrimaryNic, StringComparison.OrdinalIgnoreCase) == 0);
                            if (vMNicDetailsToBeUpdated != null)
                            {
                                VMNicInputDetails vMNicInputDetails = new VMNicInputDetails();

                                vMNicInputDetails.NicId = this.PrimaryNic;
                                vMNicInputDetails.RecoveryVMSubnetName = this.RecoveryNicSubnetName;
                                vMNicInputDetails.ReplicaNicStaticIPAddress = this.RecoveryNicStaticIPAddress;
                                vMNicInputDetails.SelectionType = string.IsNullOrEmpty(this.NicSelectionType) ? Constants.SelectedByUser : this.NicSelectionType;
                                vMNicInputDetailsList.Add(vMNicInputDetails);

                                IEnumerable<VMNicDetails> vMNicDetailsListRemaining = providerSpecificDetails.VMNics.Where(n => string.Compare(n.NicId, this.PrimaryNic, StringComparison.OrdinalIgnoreCase) != 0);
                                foreach (VMNicDetails nDetails in vMNicDetailsListRemaining)
                                {
                                    vMNicInputDetails = new VMNicInputDetails();

                                    vMNicInputDetails.NicId = nDetails.NicId;
                                    vMNicInputDetails.RecoveryVMSubnetName = nDetails.RecoveryVMSubnetName;
                                    vMNicInputDetails.ReplicaNicStaticIPAddress = nDetails.ReplicaNicStaticIPAddress;
                                    vMNicInputDetails.SelectionType = nDetails.SelectionType;
                                    vMNicInputDetailsList.Add(vMNicInputDetails);
                                }
                            }
                            else
                            {
                                throw new PSInvalidOperationException(Properties.Resources.NicNotFoundInVMForUpdateVmProperties);
                            }
                        }
                    }
                    else
                    {
                        VMNicInputDetails vMNicInputDetails = new VMNicInputDetails();
                        foreach (VMNicDetails nDetails in providerSpecificDetails.VMNics)
                        {
                            vMNicInputDetails = new VMNicInputDetails();

                            vMNicInputDetails.NicId = nDetails.NicId;
                            vMNicInputDetails.RecoveryVMSubnetName = nDetails.RecoveryVMSubnetName;
                            vMNicInputDetails.ReplicaNicStaticIPAddress = nDetails.ReplicaNicStaticIPAddress;
                            vMNicInputDetails.SelectionType = nDetails.SelectionType;
                            vMNicInputDetailsList.Add(vMNicInputDetails);
                        }
                    }
                }

                UpdateReplicationProtectedItemInputProperties updateReplicationProtectedItemInputProperties = new UpdateReplicationProtectedItemInputProperties()
                {
                    RecoveryAzureVMName = vmName,
                    RecoveryAzureVMSize = vmSize,
                    SelectedRecoveryAzureNetworkId = vmRecoveryNetworkId,
                    VmNics = vMNicInputDetailsList,
                    LicenseType = licenseType,
                };

                UpdateReplicationProtectedItemInput input = new UpdateReplicationProtectedItemInput()
                {
                    Properties = updateReplicationProtectedItemInputProperties
                };

                LongRunningOperationResponse response = RecoveryServicesClient.UpdateVmProperties(
                    Utilities.GetValueFromArmId(this.VirtualMachine.ID, ARMResourceTypeConstants.ReplicationFabrics),
                    Utilities.GetValueFromArmId(this.VirtualMachine.ID, ARMResourceTypeConstants.ReplicationProtectionContainers),
                    this.VirtualMachine.Name,
                    input);

                JobResponse jobResponse =
                    RecoveryServicesClient
                    .GetAzureSiteRecoveryJobDetails(PSRecoveryServicesClient.GetJobIdFromReponseLocation(response.Location));

                WriteObject(new ASRJob(jobResponse.Job));
            }
            catch (Exception exception)
            {
                this.HandleException(exception);
            }
        }
        public void UpdateProtection()
        {
            using (UndoContext context = UndoContext.Current)
            {
                context.Start();
                var client = GetSiteRecoveryClient(CustomHttpHandler);

                string replicationProtectedItemName = "PE1447651278";
                string fabricName = "Vmm;b6d8b350-2ee5-40c0-b777-2158a87c2aee";
                string containerName = "cloud_b6d8b350-2ee5-40c0-b777-2158a87c2aee";

                Network vmNic = client.Network.List(fabricName, RequestHeaders).NetworksList[0];

                var protectedItem = client.ReplicationProtectedItem.Get(fabricName, containerName, replicationProtectedItemName, RequestHeaders);

                UpdateReplicationProtectedItemInputProperties inputProps = new UpdateReplicationProtectedItemInputProperties()
                {
                    RecoveryAzureVMSize = "Basic_A0",
                    RecoveryAzureVMName = "B2AVM4NewName",
                    //SelectedPrimaryNicId = (protectedItem.ReplicationProtectedItem.Properties.ProviderSpecificDetails as HyperVReplicaAzureReplicationDetails).VMNics[0].NicId,
                    SelectedRecoveryAzureNetworkId = "/subscriptions/19b823e2-d1f3-4805-93d7-401c5d8230d5/resourceGroups/Default-Networking/providers/Microsoft.ClassicNetwork/virtualNetworks/ramjsingNetwork1"
                };

                UpdateReplicationProtectedItemInput input = new UpdateReplicationProtectedItemInput()
                {
                    Properties = inputProps
                };

                var resp = client.ReplicationProtectedItem.UpdateProtection(fabricName, containerName, replicationProtectedItemName, input, RequestHeaders);
            }
        }
 /// <summary>
 /// Updates the given Replication protected item.
 /// </summary>
 /// <param name='operations'>
 /// Reference to the
 /// Microsoft.Azure.Management.SiteRecovery.IReplicationProtectedItemOperations.
 /// </param>
 /// <param name='fabricName'>
 /// Required. Fabric name.
 /// </param>
 /// <param name='protectionContainerName'>
 /// Required. Protection container name.
 /// </param>
 /// <param name='replicationProtectedItemName'>
 /// Required. Replication protected item name.
 /// </param>
 /// <param name='input'>
 /// Required. Updation input
 /// </param>
 /// <param name='customRequestHeaders'>
 /// Optional. Request header parameters.
 /// </param>
 /// <returns>
 /// A standard service response for long running operations.
 /// </returns>
 public static Task<LongRunningOperationResponse> BeginUpdateProtectionAsync(this IReplicationProtectedItemOperations operations, string fabricName, string protectionContainerName, string replicationProtectedItemName, UpdateReplicationProtectedItemInput input, CustomRequestHeaders customRequestHeaders)
 {
     return operations.BeginUpdateProtectionAsync(fabricName, protectionContainerName, replicationProtectedItemName, input, customRequestHeaders, CancellationToken.None);
 }
 /// <summary>
 /// Updates the given Replication protected item.
 /// </summary>
 /// <param name='operations'>
 /// Reference to the
 /// Microsoft.Azure.Management.SiteRecovery.IReplicationProtectedItemOperations.
 /// </param>
 /// <param name='fabricName'>
 /// Required. Fabric name.
 /// </param>
 /// <param name='protectionContainerName'>
 /// Required. Protection container name.
 /// </param>
 /// <param name='replicationProtectedItemName'>
 /// Required. Replication protected item name.
 /// </param>
 /// <param name='input'>
 /// Required. Updation input
 /// </param>
 /// <param name='customRequestHeaders'>
 /// Optional. Request header parameters.
 /// </param>
 /// <returns>
 /// A standard service response for long running operations.
 /// </returns>
 public static LongRunningOperationResponse BeginUpdateProtection(this IReplicationProtectedItemOperations operations, string fabricName, string protectionContainerName, string replicationProtectedItemName, UpdateReplicationProtectedItemInput input, CustomRequestHeaders customRequestHeaders)
 {
     return Task.Factory.StartNew((object s) => 
     {
         return ((IReplicationProtectedItemOperations)s).BeginUpdateProtectionAsync(fabricName, protectionContainerName, replicationProtectedItemName, input, customRequestHeaders);
     }
     , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
 }
        public void UpdateProtectionOfInMageAzureV2ProtectedItem()
        {
            using (UndoContext context = UndoContext.Current)
            {
                context.Start();
                var client = GetSiteRecoveryClient(CustomHttpHandler);

                string vmId = "7192c867-b38e-11e5-af2b-0050569e66ab";
                var responseServers = client.Fabrics.List(RequestHeaders);

                Assert.True(
                    responseServers.Fabrics.Count > 0,
                    "Servers count can't be less than 1");

                var vmWareFabric = responseServers.Fabrics.First(
                    fabric => fabric.Properties.CustomDetails.InstanceType == "VMware");
                Assert.NotNull(vmWareFabric);

                var containersResponse = client.ProtectionContainer.List(
                    vmWareFabric.Name,
                    RequestHeaders);
                Assert.NotNull(containersResponse);
                Assert.True(
                    containersResponse.ProtectionContainers.Count > 0,
                    "Containers count can't be less than 1.");

                var protectedItemResponse = client.ReplicationProtectedItem.Get(
                    vmWareFabric.Name,
                    containersResponse.ProtectionContainers[0].Name,
                    vmId + "-Protected",
                    RequestHeaders);

                var replicationProtectedItem = protectedItemResponse.ReplicationProtectedItem;
                Assert.NotNull(replicationProtectedItem);

                var nics = new List<VMNicInputDetails>();
                nics.Add(
                    new VMNicInputDetails
                    {
                        NicId = "00:50:56:9E:3E:F2",
                        RecoveryVMSubnetName = "TenantSubnet",
                        SelectionType = "SelectedByUser",
                    });
                UpdateReplicationProtectedItemInputProperties inputProps = new UpdateReplicationProtectedItemInputProperties()
                {
                    RecoveryAzureVMName = replicationProtectedItem.Properties.FriendlyName,
                    VmNics = nics,
                    SelectedRecoveryAzureNetworkId = "/subscriptions/c183865e-6077-46f2-a3b1-deb0f4f4650a/resourceGroups/Default-Networking/providers/Microsoft.ClassicNetwork/virtualNetworks/ExpressRouteVNet-WUS-1"
                };

                UpdateReplicationProtectedItemInput input = new UpdateReplicationProtectedItemInput()
                {
                    Properties = inputProps
                };

                var updateResponse =
                    client.ReplicationProtectedItem.UpdateProtection(
                        vmWareFabric.Name,
                        containersResponse.ProtectionContainers[0].Name,
                        replicationProtectedItem.Name,
                        input,
                        RequestHeaders);

                Assert.NotNull(updateResponse);
                Assert.Equal(OperationStatus.Succeeded, updateResponse.Status);
            }
        }