Exemplo n.º 1
0
        /// <summary>
        /// Performs a firmware update on Omni and WindJammer Devices
        /// </summary>
        /// <param name="asset"></param>
        /// <returns>A <see cref="PluginExecutionResult" /> indicating the outcome of the execution.</returns>
        public PluginExecutionResult UpgradeFirmware(IDeviceInfo asset)
        {
            IDevice device    = DeviceConstructor.Create(asset);
            string  sessionId = GetSessionId(device.Address);

            _activityExecutionDetailLog = new ActivityExecutionDetailLog(_executionData, "FirmwareFlashMethod", "EWS");
            ExecutionServices.DataLogger.Submit(_activityExecutionDetailLog);


            PluginExecutionResult result = new PluginExecutionResult(PluginResult.Failed, "Failed to Update Firmware");
            string startingFW            = device.GetDeviceInfo().FirmwareRevision;

            device_textBox.InvokeIfRequired(c => { c.Text = device.Address; });
            currentRevision_textBox.InvokeIfRequired(c => { c.Text = startingFW; });

            UpdateStatus($"Firmware upgrade for device {device.Address} is in progress, please wait...");
            bool downgrade = false;

            if (device is JediWindjammerDevice)
            {
                result = SignInWJ(device.Address, device.AdminPassword, sessionId);

                _performanceLogger.RecordEvent(DeviceWorkflowMarker.FirmwareUpdateBegin);
                result = FlashFirmwareWJ(asset, sessionId);
            }
            else if (device is JediOmniDevice)
            {
                sessionId = SignInOmni(device.Address, device.AdminPassword);

                _performanceLogger.RecordEvent(DeviceWorkflowMarker.FirmwareUpdateBegin);
                result    = FlashOmniFirmware(asset, ref sessionId);
                downgrade = result.Message == "True" ? true : false;
            }
            ExecutionServices.SystemTrace.LogInfo($"FW Update Complete");
            _activityExecutionDetailLog = new ActivityExecutionDetailLog(_executionData, "FirmwareFlashUpgrade", downgrade ? "false" : "true");
            ExecutionServices.DataLogger.Submit(_activityExecutionDetailLog);

            //Wait for device to finish rebooting or end

            //if (!_activityData.ValidateFlash || downgrade)
            //{
            //    _performanceLogger.RecordEvent(DeviceWorkflowMarker.FirmwareUpdateEnd);
            //    return result;
            //}

            if (result.Result == PluginResult.Failed)
            {
                return(result);
            }

            int maxRetries = (int)_activityData.ValidateTimeOut.TotalSeconds / 10;

            if (Retry.UntilTrue(() => HasDeviceRebooted(device), maxRetries / 5, TimeSpan.FromSeconds(5)))
            {
                _performanceLogger.RecordEvent(DeviceWorkflowMarker.DeviceRebootBegin);
                UpdateStatus("Device has Rebooted. Waiting for device to boot up...");
            }
            else
            {
                result = new PluginExecutionResult(PluginResult.Failed, $"Device did not reboot after firmware was uploaded. Please check the device for pending jobs and try again.");
                return(result);
            }


            ExecutionServices.SystemTrace.LogInfo($"Starting Reboot");
            UpdateStatus("Waiting for device to boot up...");
            //_performanceLogger.RecordEvent(DeviceWorkflowMarker.DeviceRebootBegin);
            //We're probably not up and running right away.
            Thread.Sleep(TimeSpan.FromSeconds(30));

            //int maxRetries = (int)_activityData.ValidateTimeOut.TotalSeconds / 10;
            ExecutionServices.SystemTrace.LogDebug($"Max Retries: {maxRetries}");
            int    retry            = 0;
            string fwRevision       = string.Empty;
            bool   controlPanelUp   = false; //Actually webservices, but close enough.
            bool   embeddedServerUp = false;

            if (Retry.UntilTrue(() => IsDeviceRunning(device, retry++, ref controlPanelUp, ref embeddedServerUp), maxRetries, TimeSpan.FromSeconds(10)))
            {
                try
                {
                    if (downgrade)
                    {
                        SetDefaultPassword(device.Address, device.AdminPassword);
                    }

                    fwRevision = device.GetDeviceInfo().FirmwareRevision;
                    postRevision_textBox.InvokeIfRequired(c => { c.Text = fwRevision; });
                }
                catch
                {
                    fwRevision = string.Empty;
                }
                //Validate update passed by comparing starting and ending FW
                result = startingFW != fwRevision ? new PluginExecutionResult(PluginResult.Passed, $"Firmware upgraded for device {device.Address}") : new PluginExecutionResult(PluginResult.Failed, "The device firmware upgrade validation failed");
            }
            else
            {
                result = new PluginExecutionResult(PluginResult.Failed,
                                                   $"Device firmware could not be validated for device:{device.Address} within {_activityData.ValidateTimeOut}");
            }
            _performanceLogger.RecordEvent(DeviceWorkflowMarker.DeviceRebootEnd);
            _performanceLogger.RecordEvent(DeviceWorkflowMarker.FirmwareUpdateEnd);

            ExecutionServices.SystemTrace.LogInfo($"Reboot End");

            _activityExecutionDetailLog = new ActivityExecutionDetailLog(_executionData, "PostUpgradeFirmware", fwRevision);
            ExecutionServices.DataLogger.Submit(_activityExecutionDetailLog);

            return(result);
        }
Exemplo n.º 2
0
        /// <summary>
        /// Executes this plugin's workflow using the specified <see cref="PluginExecutionData" />.
        /// </summary>
        /// <param name="executionData">The execution data.</param>
        /// <returns>A <see cref="PluginExecutionResult" /> indicating the outcome of the execution.</returns>
        public PluginExecutionResult Execute(PluginExecutionData executionData)
        {
            _executionData     = executionData;
            _performanceLogger = new DeviceWorkflowLogger(_executionData);
            _activityData      = executionData.GetMetadata <USBFirmwarePerformanceActivityData>();

            TimeSpan lockTimeout = TimeSpan.FromMinutes(10);
            TimeSpan holdTimeout = TimeSpan.FromMinutes(60);

            PluginExecutionResult result = new PluginExecutionResult(PluginResult.Failed, "Failed to Start Upgrade");


            ///Dictionary<string, PluginExecutionResult> results = new Dictionary<string, PluginExecutionResult>();
            if (_executionData.Assets.OfType <IDeviceInfo>().Count() == 0)
            {
                return(new PluginExecutionResult(PluginResult.Failed, $"There were no assets retrieved.  If this is a count-based run, your reservation in asset inventory may have expired.", "DeviceInfo Asset error"));
            }

            try
            {
                var assetTokens = _executionData.Assets.OfType <IDeviceInfo>().Select(n => new AssetLockToken(n, lockTimeout, holdTimeout));
                _performanceLogger.RecordEvent(DeviceWorkflowMarker.DeviceLockBegin);
                ExecutionServices.CriticalSection.Run(assetTokens, selectedToken =>
                {
                    _performanceLogger.RecordEvent(DeviceWorkflowMarker.ActivityBegin);

                    IDeviceInfo asset = (selectedToken as AssetLockToken).AssetInfo as IDeviceInfo;
                    IDevice device    = DeviceConstructor.Create(asset);
                    ExecutionServices.DataLogger.Submit(new ActivityExecutionAssetUsageLog(_executionData, asset));

                    ExecutionServices.SystemTrace.LogDebug($"Performing update on device {asset.AssetId} at address {asset.Address}");

                    result = UpgradeFirmware(asset);


                    if (result.Result != PluginResult.Passed)
                    {
                        //the update process failed, just return
                        return;
                    }

                    if (!_activityData.ValidateFlash)
                    {
                        _performanceLogger.RecordExecutionDetail(DeviceWorkflowMarker.FirmwareUpdateEnd, device.GetDeviceInfo().FirmwareRevision);
                        return;
                    }

                    int maxRetries = (int)_activityData.ValidateTimeOut.TotalSeconds / 5;
                    if (Retry.UntilTrue(() => HasDeviceRebooted(device), maxRetries, TimeSpan.FromSeconds(5)))
                    {
                        _performanceLogger.RecordEvent(DeviceWorkflowMarker.DeviceRebootBegin);
                        UpdateStatus("Device has Rebooted. Waiting for device to boot up...");
                    }
                    else
                    {
                        result = new PluginExecutionResult(PluginResult.Failed, $"Device did not reboot after firmware was uploaded. Please check the device for pending jobs and try again.");
                        return;
                    }


                    ExecutionServices.SystemTrace.LogInfo($"FW Update Complete");

                    //Wait for device to finish rebooting or end
                    ExecutionServices.SystemTrace.LogInfo($"Starting Reboot");
                    UpdateStatus("Waiting for device to boot up...");
                    //_performanceLogger.RecordEvent(DeviceWorkflowMarker.DeviceRebootBegin);
                    //We're probably not up and running right away.
                    Thread.Sleep(TimeSpan.FromSeconds(30));


                    ExecutionServices.SystemTrace.LogDebug($"Max Retries: {maxRetries}");
                    int retry             = 0;
                    string fwRevision     = string.Empty;
                    bool controlPanelUp   = false; //Actually webservices, but close enough.
                    bool embeddedServerUp = false;
                    if (Retry.UntilTrue(() => IsDeviceRunning(device, retry++, ref controlPanelUp, ref embeddedServerUp), maxRetries, TimeSpan.FromSeconds(10)))
                    {
                        try
                        {
                            fwRevision = device.GetDeviceInfo().FirmwareRevision;
                            postRevision_textBox.InvokeIfRequired(c => { c.Text = fwRevision; });
                        }
                        catch
                        {
                            fwRevision = string.Empty;
                        }
                        //Validate update passed by comparing starting and ending FW
                        //result = startingFW != fwRevision ? new PluginExecutionResult(PluginResult.Passed, $"Firmware upgraded for device {device.Address}") : new PluginExecutionResult(PluginResult.Failed, "The device firmware upgrade validation failed");
                        result = new PluginExecutionResult(PluginResult.Passed);
                    }
                    else
                    {
                        result = new PluginExecutionResult(PluginResult.Failed,
                                                           $"Device firmware could not be validated for device:{device.Address} within {_activityData.ValidateTimeOut}");
                    }
                    _performanceLogger.RecordEvent(DeviceWorkflowMarker.DeviceRebootEnd);
                    _performanceLogger.RecordEvent(DeviceWorkflowMarker.FirmwareUpdateEnd);

                    ExecutionServices.SystemTrace.LogInfo($"Reboot End");

                    _activityExecutionDetailLog = new ActivityExecutionDetailLog(_executionData, "PostUpgradeFirmware", fwRevision);
                    ExecutionServices.DataLogger.Submit(_activityExecutionDetailLog);

                    //return result;
                });
            }
            catch (Exception e)
            {
                ExecutionServices.SystemTrace.LogDebug(e);
                UpdateStatus(e.Message);
                result = new PluginExecutionResult(PluginResult.Failed, e.Message);
            }
            _performanceLogger.RecordEvent(DeviceWorkflowMarker.ActivityEnd);
            _performanceLogger.RecordEvent(DeviceWorkflowMarker.DeviceLockEnd);
            return(result);
        }
Exemplo n.º 3
0
        //public static void PUTCDM(string url)
        //{
        //    string final = $@"https://{url}/hp/network/ioConfig/v1/networkInterfaces/wired1/snmpv1v2Config";
        //    string jsonContent = @"{""snmpv1v2Enabled"": ""true"",""accessOption"": ""readWrite"",""readOnlyPublicAllowed"": ""true"",""readOnlyCommunityNameSet"": ""false"",""writeOnlyCommunitryNameSet"": ""false""}";
        //    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(final);
        //    request.Method = "PUT";
        //    request.ContentType = "access-control-allow-headers";
        //    request.Proxy = null;
        //    request.Credentials = new NetworkCredential("admin", "!QAZ2wsx");

        //    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
        //    ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
        //    UTF8Encoding encoding = new System.Text.UTF8Encoding();
        //    Byte[] byteArray = encoding.GetBytes(jsonContent);

        //    request.ContentLength = byteArray.Length;
        //    request.ContentType = @"application/json";

        //    using (Stream dataStream = request.GetRequestStream())
        //    {
        //        dataStream.Write(byteArray, 0, byteArray.Length);
        //    }
        //    long length = 0;
        //    try
        //    {
        //        using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
        //        {
        //            Stream receiveStream = response.GetResponseStream();
        //            length = response.ContentLength;
        //            Console.WriteLine(response.StatusCode);

        //        }
        //    }
        //    catch (WebException ex)
        //    {
        //        throw ex;
        //        // Log exception and throw as for GET example above
        //    }
        //}
        #endregion


        private PluginExecutionResult UpgradeFirmware(IDeviceInfo deviceInfo)
        {
            TimeSpan              waitTimeSpan = TimeSpan.FromSeconds(4);
            Pacekeeper            pacekeeper   = new Pacekeeper(TimeSpan.FromSeconds(7));
            PluginExecutionResult result       = new PluginExecutionResult(PluginResult.Passed);

            IDevice device     = DeviceConstructor.Create(deviceInfo);
            var     omniDevice = device as JediOmniDevice;

            _preparationManager = new JediOmniPreparationManager(omniDevice);

            if (omniDevice == null)
            {
                result = new PluginExecutionResult(PluginResult.Failed, "This plugin supports only Jedi Omni devices");
                throw new DeviceWorkflowException("This plugin supports only Jedi Omni devices");
            }

            device_textBox.InvokeIfRequired(x => x.Text          = device.Address);
            currentRevision_textBox.InvokeIfRequired(x => x.Text = device.GetDeviceInfo().FirmwareRevision);
            _activityExecutionDetailLog = new ActivityExecutionDetailLog(_executionData, "FirmwareFlashMethod", "USB");
            ExecutionServices.DataLogger.Submit(_activityExecutionDetailLog);
            //_activityExecutionDetailLog = new ActivityExecutionDetailLog(_executionData, "FirmwareFlashUpgrade", _activityData.IsDowngrade ? "false" : "true");
            //ExecutionServices.DataLogger.Submit(_activityExecutionDetailLog);

            UpdateProgressBar(0);

            _preparationManager.InitializeDevice(true);
            omniDevice.ControlPanel.ScrollPressWait("#hpid-supportTools-homescreen-button",
                                                    "#hpid-supporttools-app-screen", waitTimeSpan);
            pacekeeper.Pause();



            #region handle maintanance popup
            JediOmniPopupManager popupManager = new JediOmniPopupManager(omniDevice);
            bool maintananceWindowNotSolved   = false;
            int  maintananceretries           = 0;
            while (!maintananceWindowNotSolved && maintananceretries < 2)
            {
                if (omniDevice.ControlPanel.WaitForAvailable("#hpid-tree-node-listitem-maintenance", TimeSpan.FromSeconds(5)))
                {
                    Thread.Sleep(5);

                    omniDevice.ControlPanel.PressWait("#hpid-tree-node-listitem-maintenance", "#hpid-settings-app-menu-panel", waitTimeSpan);
                }

                if (omniDevice.ControlPanel.CheckState("#hpid-maintenancemode-failed-feedback-popup", OmniElementState.VisibleCompletely)) // TimeSpan.FromSeconds(4)))
                {
                    popupManager.HandleMaintananceUnavailablePopUp();
                    maintananceWindowNotSolved = true;
                }

                maintananceretries++;
            }

            if (maintananceWindowNotSolved)
            {
                if (omniDevice.ControlPanel.WaitForAvailable("#hpid-tree-node-listitem-maintenance", TimeSpan.FromSeconds(5)))
                {
                    omniDevice.ControlPanel.PressWait("#hpid-tree-node-listitem-maintenance", "#hpid-settings-app-menu-panel", waitTimeSpan);
                }
            }
            #endregion

            if (omniDevice.ControlPanel.WaitForState("#hpid-tree-node-listitem-usbfirmwareupgrade", OmniElementState.Exists, waitTimeSpan))
            {
                omniDevice.ControlPanel.ScrollPressWait("#hpid-tree-node-listitem-usbfirmwareupgrade", "#hpid-usb-firmware-upgrade-screen", waitTimeSpan);
            }
            //var items = omniDevice.ControlPanel.GetIds("div", OmniIdCollectionType.Children);
            //foreach (var item in items)
            //{
            //    ExecutionServices.SystemTrace.LogInfo(item.ToString());
            //}

            pacekeeper.Pause();
            if (omniDevice.ControlPanel.WaitForAvailable("#hpid-firmware-bundles-list", waitTimeSpan))
            {
                //Verify USB firmware?--Lets find out
                if (omniDevice.ControlPanel.CheckState(".hp-listitem-text:contains(_)", OmniElementState.Exists))
                {
                    omniDevice.ControlPanel.ScrollPress(".hp-listitem-text:contains(_)");
                }
                else
                {
                    result = new PluginExecutionResult(PluginResult.Skipped, "Specified firmware bundle not found on USB media");
                    // throw new DeviceWorkflowException("Specified firmware bundle not found on USB media");
                }

                if (omniDevice.ControlPanel.WaitForState("#hpid-setting-install-button", OmniElementState.Enabled,
                                                         waitTimeSpan))
                {
                    omniDevice.ControlPanel.Press("#hpid-setting-install-button");
                    pacekeeper.Pause();
                }
                else
                {
                    result = new PluginExecutionResult(PluginResult.Failed, "Unable to install firmware");
                    //throw new DeviceWorkflowException("Unable to install firmware");
                }

                bool   popUpFound    = false;
                var    popUpWaitTime = DateTime.Now + TimeSpan.FromSeconds(6);
                string buttonPress   = @"";
                while (DateTime.Now < popUpWaitTime)
                {
                    popUpFound = omniDevice.ControlPanel.WaitForState("#hpid-reinstall-button", OmniElementState.Enabled, TimeSpan.FromSeconds(.5));
                    if (popUpFound)
                    {
                        buttonPress = "#hpid-reinstall-button";
                        break;
                    }
                    popUpFound = omniDevice.ControlPanel.WaitForAvailable("#hpid-upgrade-message", TimeSpan.FromSeconds(.5));
                    if (popUpFound)
                    {
                        buttonPress = "#hpid-upgrade-button";
                        break;
                    }
                    popUpFound = omniDevice.ControlPanel.WaitForState("#hpid-rollback-button", OmniElementState.Enabled, TimeSpan.FromSeconds(.5));
                    if (popUpFound)
                    {
                        buttonPress = "#hpid-rollback-button";
                        break;
                    }
                }
                switch (buttonPress)
                {
                case "#hpid-reinstall-button":
                    return(new PluginExecutionResult(PluginResult.Skipped, "This version of firmware is already installed."));

                    //omniDevice.ControlPanel.Press("#hpid-reinstall-button");
                    //pacekeeper.Pause();
                    break;

                case "#hpid-upgrade-button":
                    if (omniDevice.ControlPanel.WaitForAvailable("#hpid-upgrade-button", waitTimeSpan))
                    {
                        omniDevice.ControlPanel.Press("#hpid-upgrade-button");
                        pacekeeper.Pause();
                    }
                    break;

                case "#hpid-rollback-button":
                    result = new PluginExecutionResult(PluginResult.Skipped, "Firmware rollback not officially supported, please check that you have the right firmware");
                    return(result);

                    break;

                default:
                    result = new PluginExecutionResult(PluginResult.Failed, "Failed to find upgrade button to press");
                    return(result);
                }


                _performanceLogger.RecordEvent(DeviceWorkflowMarker.FirmwareUpdateBegin);
                UpdateProgressBar(20);
                while (omniDevice.ControlPanel.WaitForState("#hpid-firmware-install-progress-popup", OmniElementState.VisibleCompletely, waitTimeSpan))
                {
                    //do nothing
                    Application.DoEvents();

                    //let's not spam the device with check messages
                    Thread.Sleep(waitTimeSpan);
                }
                if (omniDevice.ControlPanel.WaitForAvailable("#hpid-usbfirmwareupgrade-error-msg-popup",
                                                             waitTimeSpan))
                {
                    var errorMessage = omniDevice.ControlPanel.GetValue(".hp-popup-content", "textContent",
                                                                        OmniPropertyType.Property);
                    omniDevice.ControlPanel.Press("#hpid-usbfirmwareupgrade-error-popup-button-ok");
                    result = new PluginExecutionResult(PluginResult.Failed, errorMessage);
                    throw new DeviceWorkflowException(errorMessage);
                }
                //_performanceLogger.RecordEvent(DeviceWorkflowMarker.FirmwareUpdateEnd);
                UpdateProgressBar(100);
            }
            else
            {
                var upgradeMessage = omniDevice.ControlPanel.GetValue("#hpid-usb-firmware-upgrade-message", "innerText",
                                                                      OmniPropertyType.Property);
                result = new PluginExecutionResult(PluginResult.Failed, upgradeMessage);
//                throw new DeviceWorkflowException(upgradeMessage);
            }

            return(result);
        }
Exemplo n.º 4
0
        /// <summary>
        /// Executes the scan job using the specified device.
        /// </summary>
        /// <param name="device">The device.</param>
        /// <param name="deviceInfo">The device information.</param>
        /// <returns>The result of execution.</returns>
        protected virtual PluginExecutionResult ExecuteScan(IDevice device, IDeviceInfo deviceInfo)
        {
            var result = new PluginExecutionResult(PluginResult.Failed, "Automation Failure", "Device workflow error.");

            try
            {
                // Make sure the device is in a good state
                var devicePrepManager = DevicePreparationManagerFactory.Create(device);
                devicePrepManager.WorkflowLogger = WorkflowLogger;
                devicePrepManager.InitializeDevice(true);

                // Configure the device (apply settings, load simulator ADF, etc.)
                UpdateStatus("Configuring device...");
                ConfigureDevice(deviceInfo);
                ScanLog.PageCount = (short)ScanOptions.PageCount;
                ScanLog.Sender    = ExecutionData.Credential.UserName;

                // Set up the job (enter parameters, etc.)
                RecordEvent(DeviceWorkflowMarker.ActivityBegin);
                UpdateStatus("Setting up job...");
                SetupJob(device);
                UpdateStatus("Job setup complete.");

                // Finish the job (apply job build options, press start, wait for finish)
                UpdateStatus("Finishing job...");
                result = FinishJob(device);
                UpdateStatus("Job finished.");

                // Clean up
                try
                {
                    devicePrepManager.NavigateHome();

                    if (devicePrepManager.SignOutRequired())
                    {
                        devicePrepManager.SignOut();
                    }
                    RecordEvent(DeviceWorkflowMarker.ActivityEnd);
                }
                catch (Exception ex) when(ex is DeviceCommunicationException || ex is DeviceInvalidOperationException)
                {
                    // Don't fail the activity if there is an exception here.
                    LogWarn("Device could not return to home screen.");
                    GatherTriageData(device, $"Device could not return to home screen: {ex.ToString()}");
                }
                UpdateStatus("Activity finished.");
            }
            catch (DeviceCommunicationException ex)
            {
                result = new PluginExecutionResult(PluginResult.Failed, ex, "Device communication error.");
                GatherTriageData(device, ex.ToString());
            }
            catch (DeviceInvalidOperationException ex)
            {
                result = new PluginExecutionResult(PluginResult.Failed, ex, "Device automation error.");
                GatherTriageData(device, ex.ToString());
            }
            catch (DeviceWorkflowException ex)
            {
                result = new PluginExecutionResult(PluginResult.Failed, ex, "Device workflow error.");
                GatherTriageData(device, ex.ToString());
            }
            catch (Exception ex)
            {
                GatherTriageData(device, $"Unexpected exception, gathering triage data: {ex.ToString()}");
                throw;
            }
            return(result);
        }
        protected override PluginExecutionResult ExecuteLinkPrint(IDevice device, IDeviceInfo deviceInfo)
        {
            var result = new PluginExecutionResult(PluginResult.Failed, "Automation Failure", "Device workflow error.");

            try
            {
                // Make sure the device is in a good state
                var devicePrepManager = DevicePreparationManagerFactory.Create(device);
                devicePrepManager.WorkflowLogger = WorkflowLogger;
                devicePrepManager.InitializeDevice(false);

                if (_data.SIO.Equals(SIOMethod.NoneSIO))
                {
                    devicePrepManager.Reset();
                }

                // Set up the job (enter parameters, etc.)
                RecordEvent(DeviceWorkflowMarker.ActivityBegin);
                UpdateStatus("Setting up job...");
                SetupJob(device);
                UpdateStatus("Job setup complete.");

                // Finish the job (apply job build options, press start, wait for finish)
                UpdateStatus("Finishing job...");
                result = FinishJob(device);
                UpdateStatus("Job finished.");

                // Clean up
                try
                {
                    SignOut();
                    RecordEvent(DeviceWorkflowMarker.ActivityEnd);

                    try
                    {
                        CollectJetAdvantagelinkMemoryMonitoring(deviceInfo);
                    }
                    catch (Exception ex)
                    {
                        SubmitConnectorLog(result.Result.ToString() + ex);
                        return(result);
                    }
                }
                catch (Exception ex) when(ex is DeviceCommunicationException || ex is DeviceInvalidOperationException)
                {
                    // Don't fail the activity if there is an exception here.
                    GatherTriageData(device, $"Device could not return to home screen: {ex.ToString()}");
                }
                UpdateStatus("Activity finished.");
            }
            catch (DeviceCommunicationException ex)
            {
                if (ex.Data.Contains(_exceptionCategoryData) && ex.Data[_exceptionCategoryData].Equals(ConnectorExceptionCategory.EnvironmentError.GetDescription()))
                {
                    result = new PluginExecutionResult(PluginResult.Error, ex, ex.Data[_exceptionCategoryData].ToString());
                }
                else
                {
                    result = new PluginExecutionResult(PluginResult.Failed, ex, $"Device communication error: {ex.Message}");
                }
            }
            catch (DeviceInvalidOperationException ex)
            {
                result = new PluginExecutionResult(PluginResult.Failed, ex, $"Device automation error: {ex.Message}");
            }
            catch (DeviceWorkflowException ex)
            {
                if (ex.Data.Contains(_exceptionCategoryData))
                {
                    result = new PluginExecutionResult(PluginResult.Failed, ex, ex.Data[_exceptionCategoryData].ToString());
                }
                else
                {
                    result = new PluginExecutionResult(PluginResult.Failed, ex, "Device workflow error.");
                }

                GatherTriageData(device, ex.ToString());
            }
            catch (Exception ex)
            {
                GatherTriageData(device, $"Unexpected exception, gathering triage data: {ex.ToString()}");
                throw;
            }
            SubmitConnectorLog(result.Result.ToString());
            return(result);
        }
        //Updating status during the parallel for each will lock the UI thread
        private bool UpdateDevice(IDeviceInfo device, LowLevelConfigActivityData data)
        {
            PrintDeviceInfoInternal printDevice = device as PrintDeviceInfoInternal;
            string validationCall = string.Empty;
            Dictionary <string, string> validationValues = new Dictionary <string, string>();


            var json = CreateJson(printDevice, data, ref validationCall, ref validationValues);

            if (json == string.Empty)// || !string.IsNullOrEmpty(data.FimBundle))
            {
                return(true);
            }
            ExecutionServices.SystemTrace.LogDebug(json);


            try
            {
                string callLocation = @"/jedi/nvpconfig";
                string jobId        = POST(_webServiceURL, callLocation, json);

                string status = GET(_webServiceURL, callLocation, jobId);
                //UpdateStatus($"Service Call Successful on device {device.Address}, response: {status}");
                DateTime startTime = DateTime.Now;


                while (status.ToUpper().Contains("PENDING") && startTime + TimeSpan.FromMinutes(15) > DateTime.Now)
                {
                    Thread.Sleep(TimeSpan.FromSeconds(10));
                    status = GET(_webServiceURL, callLocation, jobId);
                }

                if (!status.ToUpper().Contains("SUCCESS"))
                {
                    ExecutionServices.SystemTrace.LogDebug($"Device: {device.AssetId} failed to update NVRAM: Issue{status}");
                    if (status.ToUpper().Contains("PENDING"))
                    {
                        throw new Exception($"Device Unresponsive Exception, please check on device {device.AssetId}");
                    }
                    return(false);
                }
            }
            catch
            {
                throw;
            }


            //Validate here
            if (validationValues.ContainsKey("PartialClean"))
            {
                //We can't validate partial cleans.
                return(true);
            }
            else
            {
                //Otherwise send the nvram call to get the values of the current requested changes.
                string   endurl    = @"/jedi/nvpget";
                string   id        = POST(_webServiceURL, endurl, validationCall);
                string   temp      = GET(_webServiceURL, endurl, id);
                DateTime startTime = DateTime.Now;
                try
                {
                    while (temp.Contains("PENDING") && startTime + TimeSpan.FromMinutes(15) > DateTime.Now)
                    {
                        temp = GET(_webServiceURL, endurl, id);
                        Thread.Sleep(2000);
                        Console.WriteLine(temp);
                    }

                    //JavaScriptSerializer javascriptSerializer = new JavaScriptSerializer();
                    //temp = temp.Substring(1, temp.Length - 2);
                    var items = JsonConvert.DeserializeObject <List <NVRamPackageData> >(temp);

                    foreach (var item in items)
                    {
                        switch (item.Name)
                        {
                        case "SerialNumber":
                        case "ModelNumber":
                        case "ExecutionMode":
                        case "CRDefSleep":
                            byte[] hexval    = FromHex(item.HexValue);
                            string stringRep = Encoding.ASCII.GetString(hexval);

                            if (stringRep == validationValues[item.Name])
                            {
                                continue;
                            }
                            else
                            {
                                return(false);
                            }

                        case "JDIMfgReset":
                        case "SaveRecoverFlags":
                        case "Language":
                        case "RebootCrashMode":
                        case "SuppressUsed":
                            if (item.HexValue == validationValues[item.Name])
                            {
                                continue;
                            }
                            else
                            {
                                return(false);
                            }


                        //break;
                        //case "PartialClean":

                        //    break;
                        default:
                            continue;
                        }
                    }
                }
                catch (Exception ex)
                {
                    ExecutionServices.SystemTrace.LogDebug(ex);
                    throw;
                }

                return(true);
            }
        }