public static JobResponse CreateJobResponse(long ID, string name)
 {
     JobResponse jobResponse = new JobResponse();
     jobResponse.Id = ID;
     jobResponse.Name = name;
     return jobResponse;
 }
示例#2
0
 public static PSIotHubJobResponse ToPSIotHubJobResponse(JobResponse jobResponse)
 {
     return(ConvertObject <JobResponse, PSIotHubJobResponse>(jobResponse));
 }
 public void AddToJobResponses(JobResponse jobResponse)
 {
     base.AddObject("JobResponses", jobResponse);
 }
        public JobServiceModel(JobResponse jobResponse, IEnumerable <DeviceJob> deviceJobs = null)
        {
            this.JobId                     = jobResponse.JobId;
            this.QueryCondition            = jobResponse.QueryCondition;
            this.CreatedTimeUtc            = jobResponse.CreatedTimeUtc;
            this.StartTimeUtc              = jobResponse.StartTimeUtc;
            this.MaxExecutionTimeInSeconds = jobResponse.MaxExecutionTimeInSeconds;

            switch (jobResponse.Type)
            {
            case Microsoft.Azure.Devices.JobType.ScheduleDeviceMethod:
            case Microsoft.Azure.Devices.JobType.ScheduleUpdateTwin:
                this.Type = (JobType)jobResponse.Type;
                break;

            default:
                this.Type = JobType.Unknown;
                break;
            }

            switch (jobResponse.Status)
            {
            case Microsoft.Azure.Devices.JobStatus.Completed:
            case Microsoft.Azure.Devices.JobStatus.Failed:
            case Microsoft.Azure.Devices.JobStatus.Cancelled:
                // If job is complete return end time
                this.EndTimeUtc = jobResponse.EndTimeUtc;
                this.Status     = (JobStatus)jobResponse.Status;
                break;

            case Microsoft.Azure.Devices.JobStatus.Enqueued:
            case Microsoft.Azure.Devices.JobStatus.Queued:
            case Microsoft.Azure.Devices.JobStatus.Running:
            case Microsoft.Azure.Devices.JobStatus.Scheduled:
                // IoT Hub will return a date of 12/30/9999 if job hasn't completed yet
                this.EndTimeUtc = null;
                this.Status     = (JobStatus)jobResponse.Status;
                break;

            default:
                this.Status = JobStatus.Unknown;
                break;
            }

            if (jobResponse.CloudToDeviceMethod != null)
            {
                this.MethodParameter = new MethodParameterServiceModel(jobResponse.CloudToDeviceMethod);
            }

            if (jobResponse.UpdateTwin != null)
            {
                this.UpdateTwin = new TwinServiceModel(jobResponse.UpdateTwin);
            }

            this.FailureReason = jobResponse.FailureReason;
            this.StatusMessage = jobResponse.StatusMessage;

            if (jobResponse.DeviceJobStatistics != null)
            {
                this.ResultStatistics = new JobStatistics(jobResponse.DeviceJobStatistics);
            }

            this.Devices = deviceJobs?.Select(j => new DeviceJobServiceModel(j));
        }
示例#5
0
        //The main function which is performed each time a document is sent to the workflow
        void ITheWorkflowSyncEvtEx.ProcAutomaticInst(int nInstanceNo, int nTokenNo, string bstrParams)
        {
            try
            {
                TheServer server = new TheServer();
                server.Connect(TheClientType.CustomApplication);

                //create a TheWFInstance object and load the workflow item by using the instance number
                TheWFInstance wfInstance = new TheWFInstance();
                wfInstance.Load(server, nInstanceNo);

                //the GetLinkedDocAt method gives back the document number
                //of the document this workflow item belongs to
                TheWFDocument wfDoc = wfInstance.GetLinkedDocAt(0);

                int nDocNo = wfInstance.GetLinkedDocAt(0).DocNo;

                //with the document number you can retrieve the document
                TheDocument theDoc    = new TheDocument();
                string      strTheDoc = theDoc.Retrieve(wfDoc.DocNo, "", server);

                //A temporary location for storing files which are extracted from Therefore (and will be sent for signing).

                string extractFile = theDoc.ExtractStream(0, Path.GetTempPath());

                string sOrganizationNo;
                string sCertThumbprint;
                string sRecieverEmail, vRecieverEmail = null;
                string sRecieverNIN, vRecieverNIN = null;
                string sRecieverPhone, vRecieverPhone = null;
                string sSubject, vSubject;
                string sTitle, vTitle;
                string vReference;
                string sStatus;
                string sMStatus = "";
                string sJobId;
                string sTableFieldNo = "";
                string sNINInSignature;
                string sEnvironment;
                string sDebugMode;
                int    iDebugMode           = 0;
                int    sDefaultAvailability = 4;
                string sFAvailability       = "";

                //Load information about which fields to use in the category from the Registry
                RegistryKey key = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32);
                key = key.OpenSubKey("SOFTWARE").OpenSubKey("Canon");


                sOrganizationNo = key.GetValue("OrganizationNo").ToString();
                sCertThumbprint = key.GetValue("CertThumbprint").ToString();
                sEnvironment    = key.GetValue("Environment").ToString();
                sDebugMode      = key.GetValue("DebugMode").ToString();
                if (sDebugMode != "")
                {
                    iDebugMode = Convert.ToInt32(sDebugMode);
                }
                key            = key.OpenSubKey(wfInstance.ProcessName);
                sRecieverEmail = key.GetValue("RecieverEmailFieldName").ToString();
                sRecieverNIN   = key.GetValue("RecieverNINFieldName").ToString();

                sRecieverPhone = key.GetValue("RecieverPhoneFieldName").ToString();
                sSubject       = key.GetValue("SubjectFieldName").ToString();
                sTitle         = key.GetValue("TitleFieldName").ToString();

                sStatus              = key.GetValue("StatusFieldName").ToString();
                sJobId               = key.GetValue("JobIDFieldName").ToString();
                sNINInSignature      = key.GetValue("NINInSignature").ToString();
                sDefaultAvailability = Convert.ToInt32(key.GetValue("DefaultAvailablity").ToString());
                sFAvailability       = key.GetValue("AvailabilityFieldName").ToString();

                //If there are multiple signers, we need to use a table for storing the data
                sTableFieldNo = key.GetValue("M_TableFieldNo").ToString();
                if (sTableFieldNo != "")
                {
                    sRecieverEmail = key.GetValue("M_MailFieldName").ToString();
                    sMStatus       = key.GetValue("M_StatusFieldName").ToString();
                    sRecieverPhone = key.GetValue("M_PhoneFieldName").ToString();
                    sRecieverNIN   = key.GetValue("M_NINFieldName").ToString();
                }

                //Creating a list which contains all Signers (POSTEN)
                List <Signer> listOfSigners = new List <Signer>();

                //loading the indexdata related to the document
                TheIndexData     indata   = new TheIndexData();
                TheTableDataType inTddata = new TheTableDataType();
                indata = theDoc.IndexData;

                //If only one signer:
                if (sTableFieldNo == "")
                {
                    if (!String.IsNullOrEmpty(sRecieverEmail))
                    {
                        vRecieverEmail = indata.GetValueByColName(sRecieverEmail);
                    }
                    if (!String.IsNullOrEmpty(sRecieverPhone))
                    {
                        vRecieverPhone = indata.GetValueByColName(sRecieverPhone);
                    }
                    if (!String.IsNullOrEmpty(sRecieverNIN))
                    {
                        vRecieverNIN = indata.GetValueByColName(sRecieverNIN);
                    }
                    if (!string.IsNullOrEmpty(vRecieverNIN) && !string.IsNullOrEmpty(vRecieverEmail) && !string.IsNullOrEmpty(vRecieverPhone))
                    {
                        listOfSigners.Add(new Signer(new PersonalIdentificationNumber(vRecieverNIN), new Notifications(
                                                         new Email(vRecieverEmail),
                                                         new Sms(vRecieverPhone))));
                    }
                    else if (!string.IsNullOrEmpty(vRecieverEmail) && !string.IsNullOrEmpty(vRecieverPhone))
                    {
                        listOfSigners.Add(new Signer(new ContactInformation {
                            Email = new Email(vRecieverEmail), Sms = new Sms(vRecieverPhone)
                        }));
                    }
                    else if (!string.IsNullOrEmpty(vRecieverEmail))
                    {
                        listOfSigners.Add(new Signer(new ContactInformation {
                            Email = new Email(vRecieverEmail)
                        }));
                    }
                    if (iDebugMode > 0)
                    {
                        foreach (Signer logSigner in listOfSigners)
                        {
                            Library.WriteErrorLog("Signatør lagt til: " + logSigner.Identifier.ToString() + System.Environment.NewLine);
                        }
                    }
                }
                //IF multiple signers:
                else
                {
                    inTddata = indata.GetTableValue(Convert.ToInt32(sTableFieldNo));
                    for (int l = 0; l < inTddata.RowCount; l++)
                    {
                        vRecieverEmail = inTddata.GetValue(sRecieverEmail, l);
                        vRecieverPhone = inTddata.GetValue(sRecieverPhone, l).ToString();
                        vRecieverNIN   = inTddata.GetValue(sRecieverNIN, l);
                        if (!string.IsNullOrEmpty(vRecieverNIN) && !string.IsNullOrEmpty(vRecieverEmail) && !string.IsNullOrEmpty(vRecieverPhone))
                        {
                            listOfSigners.Add(new Signer(new PersonalIdentificationNumber(vRecieverNIN), new Notifications(
                                                             new Email(vRecieverEmail),
                                                             new Sms(vRecieverPhone))));
                        }
                        else if (!string.IsNullOrEmpty(vRecieverEmail) && !string.IsNullOrEmpty(vRecieverPhone))
                        {
                            listOfSigners.Add(new Signer(new ContactInformation {
                                Email = new Email(vRecieverEmail), Sms = new Sms(vRecieverPhone)
                            }));
                        }
                        else if (!string.IsNullOrEmpty(vRecieverEmail))
                        {
                            listOfSigners.Add(new Signer(new ContactInformation {
                                Email = new Email(vRecieverEmail)
                            }));
                        }
                        if (l == 9)
                        {
                            break;
                        }
                    }
                }

                //Get information from the category which is needed to create a signing job

                vReference = indata.DocNo.ToString();
                vTitle     = indata.GetValueByColName(sTitle);
                vSubject   = indata.GetValueByColName(sSubject);


                //Get the certificate from the sigature store on the locale computer
                X509Store        storeMy = new X509Store(StoreName.My, StoreLocation.LocalMachine);
                X509Certificate2 tekniskAvsenderSertifikat;
                try
                {
                    storeMy.Open(OpenFlags.ReadOnly);
                    var certs = storeMy.Certificates;

                    tekniskAvsenderSertifikat = certs.Find(
                        X509FindType.FindByThumbprint, CleanThumbprint(sCertThumbprint), false)[0];
                    if (iDebugMode > 0)
                    {
                        Library.WriteErrorLog("Certificate found: " + tekniskAvsenderSertifikat.ToString() + System.Environment.NewLine);
                    }
                }
                finally
                {
                    storeMy.Close();
                }
                //POSTEN: Portalclient
                PortalClient portalClient = null;

                Digipost.Signature.Api.Client.Core.Environment env = Digipost.Signature.Api.Client.Core.Environment.DifiTest;
                if (sEnvironment == "Production")
                {
                    env = Digipost.Signature.Api.Client.Core.Environment.Production;
                }

                //POSTEN: Create Client Configuration
                ClientConfiguration clientconfiguration = new ClientConfiguration(
                    env,
                    CleanThumbprint(sCertThumbprint),
                    new Sender(sOrganizationNo.Trim()));
                if (iDebugMode > 0)
                {
                    Library.WriteErrorLog("Client configured : " + clientconfiguration.ToString() + System.Environment.NewLine);
                }

                portalClient = new PortalClient(clientconfiguration);
                if (iDebugMode > 0)
                {
                    Library.WriteErrorLog("Portal configured : " + portalClient.ToString() + System.Environment.NewLine);
                }

                //POSTEN: Document
                Document documentToSign = new Document(
                    vTitle,
                    vSubject,
                    FileType.Pdf,
                    extractFile);
                if (iDebugMode > 0)
                {
                    Library.WriteErrorLog("Document configured : " + documentToSign.ToString() + System.Environment.NewLine);
                    Library.WriteErrorLog("PDF Path : " + extractFile + System.Environment.NewLine);
                }
                //POSTEN: Job
                Job job = new Job(
                    documentToSign,
                    listOfSigners,
                    vReference
                    );
                TimeSpan aTS = new TimeSpan(4 * 7, 0, 0, 0, 0);
                Library.WriteErrorLog("SF Availability : " + sFAvailability.ToString() + System.Environment.NewLine);
                if (!String.IsNullOrEmpty(sFAvailability))
                {
                    string aValue = "";
                    if (sFAvailability.Contains("|"))
                    {
                        Library.WriteErrorLog("SF Availability contains  pipe" + System.Environment.NewLine);
                        char[] splits = { '|' };
                        aValue = indata.GetValueByFieldNo(Convert.ToInt32(sFAvailability.Split(splits)[0].Trim()));
                        Library.WriteErrorLog("SF Availability is " + aValue + System.Environment.NewLine);
                    }
                    else
                    {
                        aValue = indata.GetValueByColName(sFAvailability);
                    }
                    if (!String.IsNullOrEmpty(aValue))
                    {
                        char[] cH       = { ' ' };
                        string aMeaning = aValue.Split(cH)[1];
                        int    iValue   = Convert.ToInt32(aValue.Split(cH)[0]);
                        if (aMeaning == "timer")
                        {
                            aTS = new TimeSpan(0, iValue, 0, 0, 0);
                        }
                        else if (aMeaning == "hour")
                        {
                            aTS = new TimeSpan(0, iValue, 0, 0, 0);
                        }
                        else if (aMeaning == "time")
                        {
                            aTS = new TimeSpan(0, iValue, 0, 0, 0);
                        }
                        else if (aMeaning == "hours")
                        {
                            aTS = new TimeSpan(0, iValue, 0, 0, 0);
                        }
                        else if (aMeaning == "uker")
                        {
                            aTS = new TimeSpan(iValue * 7, 0, 0, 0, 0);
                        }
                        else if (aMeaning == "uke")
                        {
                            aTS = new TimeSpan(iValue * 7, 0, 0, 0, 0);
                        }
                        else if (aMeaning == "week")
                        {
                            aTS = new TimeSpan(iValue * 7, 0, 0, 0, 0);
                        }
                        else if (aMeaning == "weeks")
                        {
                            aTS = new TimeSpan(iValue * 7, 0, 0, 0, 0);
                        }
                        else if (aMeaning == "dager")
                        {
                            aTS = new TimeSpan(iValue, 0, 0, 0, 0);
                        }
                        else if (aMeaning == "dag")
                        {
                            aTS = new TimeSpan(iValue, 0, 0, 0, 0);
                        }
                        else if (aMeaning == "day")
                        {
                            aTS = new TimeSpan(iValue, 0, 0, 0, 0);
                        }
                        else if (aMeaning == "days")
                        {
                            aTS = new TimeSpan(iValue, 0, 0, 0, 0);
                        }
                    }
                }
                else
                {
                    aTS = new TimeSpan(sDefaultAvailability * 7, 0, 0, 0, 0);
                }
                job.Availability = new Availability();

                job.Availability.AvailableFor = aTS;


                if (iDebugMode > 0)
                {
                    Library.WriteErrorLog("List of Signers : " + listOfSigners.ToString() + System.Environment.NewLine);

                    Library.WriteErrorLog("job configured : " + job.ToString() + System.Environment.NewLine);
                }

                //POSTEN: A job Response which acutally creates the signing job.


                JobResponse x = portalClient.Create(job).Result;
                if (iDebugMode > 0)
                {
                    Library.WriteErrorLog("JobResponse created : " + x.ToString() + System.Environment.NewLine);
                }


                //If multiple signers:
                if (sTableFieldNo != "")
                {
                    for (int l = 0; l < inTddata.RowCount; l++)
                    {
                        inTddata.SetValue(sMStatus, l, "Sendt for signering: " + x.ToString());
                        if (l == 9)
                        {
                            break;
                        }
                    }
                    indata.SetTableValue(Convert.ToInt32(sTableFieldNo), inTddata);
                    indata.SetValueByColName(sJobId, x.JobId.ToString());
                }
                //Update the status of the signing job in Therefore
                indata.SetValueByColName(sStatus, "Sendt for signering: " + x.ToString());
                indata.SetValueByColName(sJobId, x.JobId.ToString());
                indata.SaveChanges(server);

                if (System.IO.File.Exists(extractFile))
                {
                    try
                    {
                        System.IO.File.Delete(extractFile);
                    }
                    catch (Exception ex)
                    {
                        Library.WriteErrorLog("Could not delete file: " + ex.Message);
                    }
                }


                //get the next task in the workflow and finish the current task
                TheWFTask wfTask = wfInstance.GetNextTaskAt(0);
                wfInstance.ClaimInstance(server);
                wfInstance.FinishCurrentTask(server, wfTask.TaskNo, "");
            }
            catch (Exception ex)
            {
                //IF something goes wrong - write it to a log file.
                //Console.WriteLine(ex.Message);
                if (ex.InnerException != null)
                {
                    Library.WriteErrorLog("Base: " + ex.GetBaseException().Message + "|| Inner Base: " + ex.GetBaseException().InnerException.Message + " || Message: " + ex.Message + "  || INNER: " + ex.InnerException.Message + System.Environment.NewLine);
                }
                else
                {
                    Library.WriteErrorLog("Base: " + ex.GetBaseException().Message + "|| Inner Base: " + ex.GetBaseException().InnerException.Message + " || Message: " + ex.Message + System.Environment.NewLine);
                }
            }
        }
        /// <summary>
        /// ProcessRecord of the command.
        /// </summary>
        protected override void ProcessRecord()
        {
            this.targetNameOrId = this.ProtectionEntity.FriendlyName;
            this.ConfirmAction(
                this.Force.IsPresent || 0 != string.CompareOrdinal(this.Protection, Constants.DisableProtection),
                string.Format(Properties.Resources.DisableProtectionWarning, this.targetNameOrId),
                string.Format(Properties.Resources.DisableProtectionWhatIfMessage, this.Protection),
                this.targetNameOrId,
                () =>
            {
                try
                {
                    if (this.Protection == Constants.EnableProtection)
                    {
                        if (string.Compare(this.ParameterSetName, ASRParameterSets.DisableDR, StringComparison.OrdinalIgnoreCase) == 0)
                        {
                            throw new PSArgumentException(Properties.Resources.PassingPolicyMandatoryForEnablingDR);
                        }

                        EnableProtectionProviderSpecificInput enableProtectionProviderSpecificInput = new EnableProtectionProviderSpecificInput();

                        EnableProtectionInputProperties inputProperties = new EnableProtectionInputProperties()
                        {
                            PolicyId                = this.Policy.ID,
                            ProtectableItemId       = this.ProtectionEntity.ID,
                            ProviderSpecificDetails = enableProtectionProviderSpecificInput
                        };

                        EnableProtectionInput input = new EnableProtectionInput()
                        {
                            Properties = inputProperties
                        };

                        // Process if block only if policy is not null, policy is created for E2A or B2A and parameter set is for enable DR of E2A or B2A
                        if (this.Policy != null &&
                            0 == string.Compare(this.Policy.ReplicationProvider, Constants.HyperVReplicaAzure, StringComparison.OrdinalIgnoreCase) &&
                            (0 == string.Compare(this.ParameterSetName, ASRParameterSets.EnterpriseToAzure, StringComparison.OrdinalIgnoreCase) ||
                             0 == string.Compare(this.ParameterSetName, ASRParameterSets.HyperVSiteToAzure, StringComparison.OrdinalIgnoreCase)))
                        {
                            HyperVReplicaAzureEnableProtectionInput providerSettings = new HyperVReplicaAzureEnableProtectionInput();
                            providerSettings.HvHostVmId = this.ProtectionEntity.FabricObjectId;
                            providerSettings.VmName     = this.ProtectionEntity.FriendlyName;

                            // Id disk details are missing in input PE object, get the latest PE.
                            if (string.IsNullOrEmpty(this.ProtectionEntity.OS))
                            {
                                // Just checked for OS to see whether the disk details got filled up or not
                                ProtectableItemResponse protectableItemResponse =
                                    RecoveryServicesClient.GetAzureSiteRecoveryProtectableItem(
                                        Utilities.GetValueFromArmId(this.ProtectionEntity.ID, ARMResourceTypeConstants.ReplicationFabrics),
                                        this.ProtectionEntity.ProtectionContainerId,
                                        this.ProtectionEntity.Name);

                                this.ProtectionEntity = new ASRProtectionEntity(protectableItemResponse.ProtectableItem);
                            }

                            if (string.IsNullOrWhiteSpace(this.OS))
                            {
                                providerSettings.OSType = ((string.Compare(this.ProtectionEntity.OS, Constants.OSWindows) == 0) || (string.Compare(this.ProtectionEntity.OS, Constants.OSLinux) == 0)) ? this.ProtectionEntity.OS : Constants.OSWindows;
                            }
                            else
                            {
                                providerSettings.OSType = this.OS;
                            }

                            if (string.IsNullOrWhiteSpace(this.OSDiskName))
                            {
                                providerSettings.VhdId = this.ProtectionEntity.OSDiskId;
                            }
                            else
                            {
                                foreach (var disk in this.ProtectionEntity.Disks)
                                {
                                    if (0 == string.Compare(disk.Name, this.OSDiskName, true))
                                    {
                                        providerSettings.VhdId = disk.Id;
                                        break;
                                    }
                                }
                            }

                            if (RecoveryAzureStorageAccountId != null)
                            {
                                providerSettings.TargetStorageAccountId = RecoveryAzureStorageAccountId;
                            }

                            input.Properties.ProviderSpecificDetails = providerSettings;
                        }
                        else if (this.Policy != null &&
                                 0 == string.Compare(this.Policy.ReplicationProvider, Constants.HyperVReplicaAzure, StringComparison.OrdinalIgnoreCase) &&
                                 0 == string.Compare(this.ParameterSetName, ASRParameterSets.EnterpriseToEnterprise, StringComparison.OrdinalIgnoreCase))
                        {
                            throw new PSArgumentException(Properties.Resources.PassingStorageMandatoryForEnablingDRInAzureScenarios);
                        }

                        this.response =
                            RecoveryServicesClient.EnableProtection(
                                Utilities.GetValueFromArmId(this.ProtectionEntity.ID, ARMResourceTypeConstants.ReplicationFabrics),
                                Utilities.GetValueFromArmId(this.ProtectionEntity.ID, ARMResourceTypeConstants.ReplicationProtectionContainers),
                                this.ProtectionEntity.Name,
                                input);
                    }
                    else
                    {
                        DisableProtectionInput input = new DisableProtectionInput();
                        input.Properties             = new DisableProtectionInputProperties()
                        {
                            ProviderSettings = new DisableProtectionProviderSpecificInput()
                        };

                        // fetch the latest PE object
                        ProtectableItemListResponse protectableItemListResponse =
                            RecoveryServicesClient.GetAzureSiteRecoveryProtectableItem(Utilities.GetValueFromArmId(this.ProtectionEntity.ID, ARMResourceTypeConstants.ReplicationFabrics),
                                                                                       this.ProtectionEntity.ProtectionContainerId);
                        ProtectableItem protectableItem = protectableItemListResponse.ProtectableItems.SingleOrDefault(t => t.Name.CompareTo(this.ProtectionEntity.Name) == 0);

                        this.response =
                            RecoveryServicesClient.DisableProtection(
                                Utilities.GetValueFromArmId(this.ProtectionEntity.ID, ARMResourceTypeConstants.ReplicationFabrics),
                                Utilities.GetValueFromArmId(this.ProtectionEntity.ID, ARMResourceTypeConstants.ReplicationProtectionContainers),
                                Utilities.GetValueFromArmId(protectableItem.Properties.ReplicationProtectedItemId, ARMResourceTypeConstants.ReplicationProtectedItems),
                                input);
                    }

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

                    WriteObject(new ASRJob(jobResponse.Job));

                    if (this.WaitForCompletion.IsPresent)
                    {
                        this.WaitForJobCompletion(this.jobResponse.Job.Name);

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

                        WriteObject(new ASRJob(jobResponse.Job));
                    }
                }
                catch (Exception exception)
                {
                    this.HandleException(exception);
                }
            });
        }
        /// <summary>
        /// ProcessRecord of the command.
        /// </summary>
        public override void ExecuteSiteRecoveryCmdlet()
        {
            base.ExecuteSiteRecoveryCmdlet();

            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));

            // Check for Replication Provider type HyperVReplicaAzure
            if (0 != string.Compare(
                    replicationProtectedItemResponse.ReplicationProtectedItem.Properties.ProviderSpecificDetails.InstanceType,
                    Constants.HyperVReplicaAzure,
                    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))
            {
                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;
            }

            List <VMNicInputDetails> vMNicInputDetailsList = new List <VMNicInputDetails>();
            VMNicDetails             vMNicDetailsToBeUpdated;

            if (!string.IsNullOrEmpty(this.PrimaryNic))
            {
                HyperVReplicaAzureReplicationDetails providerSpecificDetails =
                    (HyperVReplicaAzureReplicationDetails)replicationProtectedItemResponse.ReplicationProtectedItem.Properties.ProviderSpecificDetails;

                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);
                    }
                }
            }

            UpdateReplicationProtectedItemInputProperties updateReplicationProtectedItemInputProperties = new UpdateReplicationProtectedItemInputProperties()
            {
                RecoveryAzureVMName            = this.Name,
                RecoveryAzureVMSize            = this.Size,
                SelectedRecoveryAzureNetworkId = this.RecoveryNetworkId,
                VmNics = vMNicInputDetailsList
            };

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

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

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

            WriteObject(new ASRJob(jobResponse.Job));
        }
示例#8
0
 public RefreshViewModel(JobResponse jobResponse)
 {
     JobId       = jobResponse.Id;
     JobResponse = jobResponse;
 }