private PluginExecutionResult ExecuteHpcrComAction(PrintDeviceInfo asset, HpcrActivityData data, string serverAddress) { _device = DeviceConstructor.Create(asset); try { switch (data.HpcrAction) { case HpcrAction.Install: Install(serverAddress, data.DeviceGroup, _device.Address, _device.AdminPassword); break; case HpcrAction.Uninstall: Uninstall(serverAddress, data.DeviceGroup, _device.Address, _device.AdminPassword); break; } } catch (WebException wex) { ExecutionServices.SystemTrace.LogError($"Hpcr Action {data.HpcrAction} failed on device:{_device.Address}", wex); UpdateStatus($"{asset.AssetId}: Failed with exception: {wex.Message}"); return(new PluginExecutionResult(PluginResult.Failed, wex.Message)); } _device.Dispose(); UpdateStatus($"{asset.AssetId}-{data.HpcrAction}: Passed"); return(new PluginExecutionResult(PluginResult.Passed)); }
/// <summary> /// Performs the Control Panel activity if lock is acquired on the device, otherwise performs the Contention Activity. /// </summary> /// <returns></returns> public PluginExecutionResult RunContentionJob() { var result = new PluginExecutionResult(PluginResult.Failed); try { IEnumerable <IDeviceInfo> devices = ExecutionData.Assets.OfType <IDeviceInfo>(); IEnumerable <AssetLockToken> assetTokens = devices.Select(n => new AssetLockToken(n, _data.LockTimeouts)); RecordEvent(DeviceWorkflowMarker.DeviceLockBegin); ExecutionServices.CriticalSection.Run(assetTokens, selectedToken => { IDeviceInfo deviceInfo = (selectedToken as AssetLockToken).AssetInfo as IDeviceInfo; using (IDevice device = DeviceConstructor.Create(deviceInfo)) { var retryManager = new PluginRetryManager(ExecutionData, UpdateStatus); result = retryManager.Run(() => RunControlPanelActivity(device)); } } ); RecordEvent(DeviceWorkflowMarker.DeviceLockEnd); } catch (AcquireLockTimeoutException) { //If the user is unable to acquire the lock on device, run the contention activity. result = RunContentionActivity(); } catch (HoldLockTimeoutException) { result = new PluginExecutionResult(PluginResult.Error, $"Automation did not complete within {_data.LockTimeouts.HoldTimeout}.", "Automation timeout exceeded."); } return(result); }
private void InitializeDevice() { try { OnUpdateStatus(this, "Initializing device."); _device = (JediOmniDevice)DeviceConstructor.Create(_deviceInfo); _preparationManager = new JediOmniPreparationManager(_device); _digitalSendExerciser = new DigitalSendExerciser(this, _device, _preparationManager); _ewsExerciser = new EwsExerciserViaSeleniumWebDriver(this, _device); _printExerciser = new PrintExerciser(this, _device); _snmpExerciser = new SnmpExerciser(this, _device); _uiExerciser = new UIExerciser(this, _device, _preparationManager); _webServicesExerciser = new WebServicesExerciser(this, _device); _preparationManager.InitializeDevice(true); } catch (Exception ex) { OnUpdateStatus(this, ex.ToString()); OnUpdateStatus(this, "Cleaning up."); _device?.Dispose(); // Log the error and re-throw. ExecutionServices.SystemTrace.LogError(ex); throw; } }
/// <summary> /// Initializes the device. /// </summary> protected virtual void InitializeDevice() { try { Device = DeviceConstructor.Create(DeviceInfo); var preparationManager = DevicePreparationManagerFactory.Create(Device); preparationManager.InitializeDevice(AuthProvider != AuthenticationProvider.Skip); _collectMemoryManager = new CollectMemoryManager(Device, DeviceInfo); } catch (Exception ex) { // Make sure the device is disposed, if necessary if (Device != null) { Device.Dispose(); Device = null; } ExecutionServices.SessionRuntime.ReportAssetError(DeviceInfo); // Log the error and re-throw. ExecutionServices.SystemTrace.LogError(ex); throw; } }
/// <summary> /// Executes this plug-in'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) { PluginExecutionResult result = new PluginExecutionResult(PluginResult.Skipped); _data = executionData.GetMetadata <PaperCutInstallerActivityData>(); _serverInfo = executionData.Servers.FirstOrDefault(); _printDeviceInfo = executionData.Assets.OfType <PrintDeviceInfo>().FirstOrDefault(); _device = DeviceConstructor.Create(_printDeviceInfo); var bundleInstaller = new BundleInstaller(_device as JediOmniDevice); try { _signedSessionId = bundleInstaller.SignIn(string.Empty); switch (_data.Action) { case PaperCutInstallerAction.Install: { result = bundleInstaller.InstallSolution(_signedSessionId, _data.BundleFile); } break; case PaperCutInstallerAction.Register: { result = RegisterDevice(); } break; case PaperCutInstallerAction.ConfigureCredentials: case PaperCutInstallerAction.ConfigureSettings: { result = ConfigureDevice(); } break; } } catch (WebException wex) { _device.Dispose(); ExecutionServices.SystemTrace.LogError( $"PaperCut Installer Action {_data.Action} failed on device:{_device.Address}", wex); UpdateStatus($"{_printDeviceInfo.AssetId}: Failed with exception: {wex.Message}"); return(new PluginExecutionResult(PluginResult.Failed, wex.Message)); } catch (Exception ex) { _device.Dispose(); ExecutionServices.SystemTrace.LogError( $"PaperCut Installer Action {_data.Action} failed on device:{_device.Address}", ex); UpdateStatus($"{_printDeviceInfo.AssetId}: Failed with exception: {ex.Message}"); return(new PluginExecutionResult(PluginResult.Failed, ex.Message)); } _device.Dispose(); UpdateStatus($"{_printDeviceInfo.AssetId}: {result.Result}"); return(result); }
/// <summary> /// Sets the device. /// </summary> /// <param name="deviceAsset">The device asset.</param> /// <returns></returns> private IDevice SetDevice(IDeviceInfo deviceAsset) { // Select a device IDevice device = DeviceConstructor.Create(deviceAsset); UpdateStatus(string.Format("Using device {0} ({1})", deviceAsset.AssetId, deviceAsset.Address)); return(device); }
public PluginExecutionResult Execute(PluginExecutionData executionData) { _activityData = executionData.GetMetadata <WirelessAssociationActivityData>(); PrintDeviceInfo printDeviceInfo = (PrintDeviceInfo)executionData.Assets.First(); _device = DeviceConstructor.Create(printDeviceInfo); _httpClientHandler = new HttpClientHandler { AllowAutoRedirect = true, UseCookies = false, MaxAutomaticRedirections = 2 }; ServicePointManager.Expect100Continue = false; ServicePointManager.ServerCertificateValidationCallback = delegate { return(true); }; try { _ssid = WirelessAssociationActivityData.StringToHexConversion(_activityData.Ssid); _passPhrase = WirelessAssociationActivityData.StringToHexConversion(_activityData.Passphrase); switch (_activityData.AuthenticationType) { case AuthenticationMode.WPAAES: { _jediProfileString = string.Format(Properties.Resources.VEPWPA2AESProfilesValue, _activityData.Ssid, _activityData.Passphrase); } break; case AuthenticationMode.WPAHex: { _jediProfileString = string.Format(Properties.Resources.VEPWPA2HexProfilesValue, _activityData.Ssid, _passPhrase); } break; case AuthenticationMode.WPAAuto: { _jediProfileString = string.Format(Properties.Resources.VEPWPA2AutoProfilesValue, _activityData.Ssid, _activityData.Passphrase); } break; case AuthenticationMode.AutoAES: { _siriusTriptaneProfileString = string.Format(Properties.Resources.TriptaneAutoAESProfilesValue, _ssid, _passPhrase); _jediProfileString = string.Format(Properties.Resources.VEPAutoAESProfilesValue, _activityData.Ssid, _activityData.Passphrase); } break; } PersonalWirelessSetting(); } catch (Exception exception) { return(new PluginExecutionResult(PluginResult.Failed, $"Failed for {_device.Address} with exception:{exception.Message}")); } return(new PluginExecutionResult(PluginResult.Passed)); }
/// <summary> /// The Main Entry point for Execution /// </summary> /// <param name="executionData"></param> /// <returns></returns> public PluginExecutionResult Execute(PluginExecutionData executionData) { _activityData = executionData.GetMetadata <MessageCenterActivityData>(); var printDeviceInfo = (PrintDeviceInfo)executionData.Assets.First(); _device = DeviceConstructor.Create(printDeviceInfo); var executionResult = EvaluateMessageCenter(); _device.Dispose(); return(executionResult); }
PluginExecutionData IPluginFrameworkSimulator.CreateExecutionData(PluginConfigurationData configurationData) { if (configurationData == null) { throw new ArgumentNullException(nameof(configurationData)); } PluginExecutionContext executionContext = new PluginExecutionContext { ActivityExecutionId = SequentialGuid.NewGuid(), SessionId = SessionId, UserName = UserName, UserPassword = UserPassword }; // Retrieve all selected assets, then add any badge boxes associated with those assets var selectedAssets = PluginConfigurationTransformer.GetExecutionAssets(configurationData, _assetInventory); var badgeBoxes = _assetInventory.GetBadgeBoxes(selectedAssets); AssetInfoCollection executionAssets = new AssetInfoCollection(selectedAssets.Union(badgeBoxes).ToList()); // Set job media mode if (PaperlessMode != JobMediaMode.Unknown) { foreach (DeviceInfo deviceInfo in selectedAssets.Where(n => n.Attributes.HasFlag(AssetAttributes.Printer))) { using (var device = DeviceConstructor.Create(deviceInfo)) { try { DeviceSettingsManagerFactory.Create(device).SetJobMediaMode(PaperlessMode); } catch { //Did not set paperless mode. Ignore error. System.Diagnostics.Debug.WriteLine($"Error setting paperless mode. {executionAssets.ToString()}"); } } } } return(new PluginExecutionData ( configurationData.GetMetadata(), configurationData.MetadataVersion, executionAssets, PluginConfigurationTransformer.GetExecutionDocuments(configurationData, _documentLibrary), PluginConfigurationTransformer.GetExecutionServers(configurationData, _assetInventory), PluginConfigurationTransformer.GetExecutionPrintQueues(configurationData, _assetInventory), (this as IPluginFrameworkSimulator).Environment, executionContext, new PluginRetrySettingDictionary(RetrySettings), new ExternalCredentialInfoCollection(_assetInventory.GetExternalCredentials(executionContext.UserName)) )); }
private IDevice IDeviceCreate(IDeviceInfo d) { try { return(DeviceConstructor.Create(d)); } catch (Exception e) { Framework.Logger.LogError($"Error creating device: {e.ToString()}"); ExecutionServices.SessionRuntime.ReportAssetError(d); throw; } }
private IDevice ConnectToDevice(string address, string address2, string password) { IDevice device = null; if (!string.IsNullOrWhiteSpace(address)) { using (new BusyCursor()) { Framework.Assets.DeviceInfo deviceInfo = new Framework.Assets.DeviceInfo(SequentialGuid.NewGuid().ToShortString(), Framework.Assets.AssetAttributes.None, string.Empty, address, address2, password, string.Empty); device = DeviceConstructor.Create(deviceInfo); } } return(device); }
public void Initialize(PluginConfigurationData configuration, PluginEnvironment environment) { _activityData = configuration.GetMetadata <ControlPanelActivityData>(); controlpanel_assetSelectionControl.Initialize(configuration.Assets, AssetAttributes.ControlPanel); if (string.IsNullOrEmpty(_activityData.ControlPanelType)) { try { var deviceInfo = (DeviceInfo)ConfigurationServices.AssetInventory.GetAsset(configuration.Assets.SelectedAssets.First()); var device = DeviceConstructor.Create(deviceInfo); if (device is JediWindjammerDevice) { controlpaneltypes_comboBox.SelectedItem = "Jedi"; } else if (device is JediOmniDevice) { controlpaneltypes_comboBox.SelectedItem = "Omni"; } else if (device is SiriusUIv2Device) { controlpaneltypes_comboBox.SelectedItem = "SiriusPentane"; } else if (device is SiriusUIv3Device) { controlpaneltypes_comboBox.SelectedItem = "SiriusTriptane"; } else { controlpaneltypes_comboBox.SelectedItem = "Phoenix"; } } catch (DeviceCommunicationException) { controlpaneltypes_comboBox.SelectedIndex = -1; } } else { controlpaneltypes_comboBox.SelectedItem = _activityData.ControlPanelType; } controlPanelOptions_comboBox.Text = _activityData.ControlPanelAction; }
/// <summary> /// Execution Entry Point /// </summary> /// <param name="executionData"></param> /// <returns></returns> public PluginExecutionResult Execute(PluginExecutionData executionData) { if (executionData == null) { return(new PluginExecutionResult(PluginResult.Skipped, "Execution Data is empty!")); } _activityData = executionData.GetMetadata <EwsHeadlessActivityData>(); var printDeviceInfo = (PrintDeviceInfo)executionData.Assets.First(); _device = DeviceConstructor.Create(printDeviceInfo); IEwsCommunicator communicator = EwsCommunicatorFactory.Create(_device); EwsPayloadFactory.AddContractLocation(Path.Combine(executionData.Environment.PluginSettings["DATPayLoadRepository"], "EWSContractFiles")); EwsPayloadFactory.AddContractLocation(Path.Combine(executionData.Environment.PluginSettings["DATPayLoadRepository"], "EWSPayLoads")); if (_activityData.Operation.Equals(_activityData.DeviceSpecificOperation)) { _activityData.DeviceSpecificOperation = string.Empty; //to match the subfilter type in the XML } //create request to access EWS DAT payloads EwsRequest ewsRequest = communicator.CreateRequest(_activityData.Operation, _activityData.DeviceSpecificOperation); foreach (var configurationValue in _activityData.ConfigurationValues) { string valueToBePassed = configurationValue.Value; if (valueToBePassed.Equals("[CurrentUser]", StringComparison.OrdinalIgnoreCase)) { valueToBePassed = executionData.Credential.UserName; } if ((_device is SiriusDevice) && (_activityData.Operation.Equals("Administration")) && (configurationValue.Key.Equals("Password"))) { var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(valueToBePassed); valueToBePassed = Convert.ToBase64String(plainTextBytes); } ewsRequest.Add(configurationValue.Key, valueToBePassed); } EwsResult result = communicator.Submit(ewsRequest); return(result.Exception != null ? new PluginExecutionResult(PluginResult.Failed, result.Exception) : new PluginExecutionResult(PluginResult.Passed)); }
private int GetDeviceTypeIndex() { var selectedAsset = ConfigurationServices.AssetInventory.GetAsset(ews_assetSelectionControl.AssetSelectionData.SelectedAssets.First()); var printDeviceInfo = (PrintDeviceInfo)selectedAsset; try { using ( var device = DeviceConstructor.Create(printDeviceInfo)) { if (device is JediWindjammerDevice) { return(deviceType_comboBox.Items.IndexOf("Jedi")); } if (device is JediOmniDevice) { return(deviceType_comboBox.Items.IndexOf("Omni")); } if (device is PhoenixDevice) { return(deviceType_comboBox.Items.IndexOf("Phoenix")); } if (device is SiriusDevice) { return(deviceType_comboBox.Items.IndexOf("Sirius")); } if (device is OzDevice) { return(deviceType_comboBox.Items.IndexOf("Oz")); } return(deviceType_comboBox.Items.IndexOf("None")); } } catch (DeviceCommunicationException ex) { MessageBox.Show($"An error occurred. Please resolve before executing. {ex.Message} "); return(-1); } catch (Exception exc) { MessageBox.Show($"An error occurred. Please resolve before executing. {exc.Message} "); return(-1); } }
/// <summary> /// Entrypoint for the Plugin Task Execution for TwainDriverConfiguration Plugin /// </summary> /// <param name="executionData"></param> /// <returns></returns> public PluginExecutionResult Execute(PluginExecutionData executionData) { PluginExecutionResult result = new PluginExecutionResult(PluginResult.Passed); var acquireTimeout = TimeSpan.FromMinutes(5); var holdTimeout = TimeSpan.FromMinutes(5); _executionData = executionData; _deviceAssets = executionData.Assets.OfType <IDeviceInfo>().ToList(); try { _workflowLogger = new DeviceWorkflowLogger(executionData); UpdateStatus("Starting task engine"); List <AssetLockToken> tokens = _deviceAssets.Select(n => new AssetLockToken(n, acquireTimeout, holdTimeout)).ToList(); _workflowLogger.RecordEvent(DeviceWorkflowMarker.DeviceLockBegin); ExecutionServices.CriticalSection.Run(tokens, selectedToken => { IDeviceInfo deviceInfo = (selectedToken as AssetLockToken).AssetInfo as IDeviceInfo; UpdateStatus($"Using device {deviceInfo.AssetId} ({deviceInfo.Address})"); using (IDevice device = DeviceConstructor.Create(deviceInfo)) { var retryManager = new PluginRetryManager(executionData, UpdateStatus); result = retryManager.Run(() => RunTwain(device, executionData)); } }); _workflowLogger.RecordEvent(DeviceWorkflowMarker.DeviceLockEnd); } catch (DeviceCommunicationException ex) { return(new PluginExecutionResult(PluginResult.Failed, ex.Message, "Device communication error.")); } catch (DeviceInvalidOperationException ex) { return(new PluginExecutionResult(PluginResult.Failed, ex.Message, "Device automation error.")); } catch (DeviceWorkflowException ex) { return(new PluginExecutionResult(PluginResult.Failed, ex, "Device workflow error.")); } return(result); }
/// <summary> /// Constructor /// </summary> /// <param name="deviceInfo"></param> /// <param name="functionName"></param> /// <param name="parameterValues"></param> public ControlPanelWrapper(DeviceInfo deviceInfo, string functionName, Dictionary <string, string> parameterValues) { _methodName = functionName; _parameterValues = parameterValues; try { _device = DeviceConstructor.Create(deviceInfo); } catch (DeviceSecurityException) { throw; } catch (Exception e) { Console.WriteLine(e); throw; } }
public PluginExecutionResult Execute(PluginExecutionData executionData) { var activityData = executionData.GetMetadata <ControlPanelActivityData>(); ConcurrentDictionary <string, PluginExecutionResult> results = new ConcurrentDictionary <string, PluginExecutionResult>(); TimeSpan lockTimeout = TimeSpan.FromMinutes(5); TimeSpan holdTimeout = TimeSpan.FromMinutes(5); //if the assets are not found then skip it if (!executionData.Assets.OfType <IDeviceInfo>().Any()) { return(new PluginExecutionResult(PluginResult.Skipped, "No Assets found for execution")); } Parallel.ForEach(executionData.Assets.OfType <IDeviceInfo>(), asset => { if (!asset.Attributes.HasFlag(AssetAttributes.ControlPanel)) { results.AddOrUpdate(asset.AssetId, new PluginExecutionResult(PluginResult.Skipped, "Device does not have control panel"), (key, oldValue) => new PluginExecutionResult(PluginResult.Skipped, "Device does not have control panel")); return; } AssetLockToken assetToken = new AssetLockToken(asset, lockTimeout, holdTimeout); ExecutionServices.CriticalSection.Run(assetToken, () => { var printDevice = DeviceConstructor.Create(asset); ControlPanelWrapper wrapper = new ControlPanelWrapper(printDevice, executionData.Credential, activityData.ControlPanelAction, activityData.ParameterValues); var result = wrapper.Execute(); results.AddOrUpdate(asset.AssetId, result, (key, oldValue) => wrapper.Execute()); printDevice.Dispose(); }); }); return(results.Any(x => x.Value.Result != PluginResult.Passed) ? new PluginExecutionResult(PluginResult.Failed) : new PluginExecutionResult(PluginResult.Passed)); }
private static IDevice CreateAutomationDevice(IDeviceInfo deviceInfo) { // Jedi simulators stop working if TLS 1.1 or 1.2 are allowed. Exact cause is unknown, but could be because // Windows supports those protocols and the simulator does not. The negotiation with Windows establishes that // one of those should be used, but then the simulator closes the connection because it can't use the selected protocol. if (deviceInfo is DeviceSimulatorInfo) { NetworkConfiguration.SecurityProtocolOverrideValue = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls; } else { NetworkConfiguration.SecurityProtocolOverrideValue = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; } IDevice device = null; try { //throw new DeviceCommunicationException(); device = DeviceConstructor.Create(deviceInfo); return(device); } catch (Exception ex) { // Make sure the device is disposed, if necessary if (device != null) { device.Dispose(); device = null; } // Log the error and post the exception back to the dispatcher LogError($"Error creating device: {ex.Message}"); ExecutionServices.SessionRuntime.ReportAssetError(deviceInfo); throw; } }
public void ExecuteReboot() { JobMediaMode jobMediaModeNeeded = JobMediaMode.Paper; RebootDeviceActivityData activityData = _activityData; IDevice device = DeviceConstructor.Create(_deviceInfo); IDeviceSettingsManager settingsManager = DeviceSettingsManagerFactory.Create(device); if (activityData.JobMediaMode == JobMediaModeDesired.Preserve) { OnUpdateStatus("Getting job media mode because it will return to default after a reboot..."); jobMediaModeNeeded = settingsManager.GetJobMediaMode(); OnUpdateStatus($"Current job media mode is {jobMediaModeNeeded}."); } else { jobMediaModeNeeded = EnumUtil.Parse <JobMediaMode>(activityData.JobMediaMode.ToString()); } DateTime startTime = DateTime.Now; if (activityData.ShouldWaitForReady) { OnUpdateStatus("Reboot Begin"); } Reboot(activityData.ShouldWaitForReady); if (activityData.ShouldWaitForReady) { OnUpdateStatus("Reboot Complete"); ExecutionServices.SystemTrace.LogDebug($"Device rebooted"); if (jobMediaModeNeeded == JobMediaMode.Paperless) { OnUpdateStatus($"Setting job media mode to {jobMediaModeNeeded}."); settingsManager.SetJobMediaMode(JobMediaMode.Paperless); } } }
private void InitializeDevice() { try { // Might encounter exception: Unable to cast object of type 'HP.DeviceAutomation.Phoenix.PhoenixDevice' to type 'HP.DeviceAutomation.Jedi.JediDevice'. // Device is still initializing operate a different web service which looks like a Phoenix device. _device = (JediDevice)DeviceConstructor.Create(_deviceInfo); _device.PowerManagement.Wake(); } catch (Exception ex) { // Make sure the device is disposed, if necessary if (_device != null) { _device.Dispose(); _device = null; } // Log the error and re-throw. ExecutionServices.SystemTrace.LogError(ex); throw; } }
public PluginExecutionResult Execute(PluginExecutionData executionData) { PluginExecutionResult result = new PluginExecutionResult(PluginResult.Failed); var activityData = executionData.GetMetadata <ControlPanelActivityData>(); TimeSpan lockTimeout = TimeSpan.FromMinutes(5); TimeSpan holdTimeout = TimeSpan.FromMinutes(5); //if the assets are not found then skip it if (!executionData.Assets.OfType <IDeviceInfo>().Any()) { return(new PluginExecutionResult(PluginResult.Skipped, "No Assets found for execution")); } var asset = executionData.Assets.OfType <IDeviceInfo>().FirstOrDefault(); if (!asset.Attributes.HasFlag(AssetAttributes.ControlPanel)) { return(new PluginExecutionResult(PluginResult.Skipped, "Device does not have control panel")); } AssetLockToken assetToken = new AssetLockToken(asset, lockTimeout, holdTimeout); ExecutionServices.CriticalSection.Run(assetToken, () => { ExecutionServices.DataLogger.Submit(new ActivityExecutionAssetUsageLog(executionData, asset)); var printDevice = DeviceConstructor.Create(asset); ControlPanelWrapper wrapper = new ControlPanelWrapper(printDevice, executionData.Credential, activityData.ControlPanelAction, activityData.ParameterValues); wrapper.ScreenCapture += (s, e) => UpdateScreenShot(e.ScreenShotImage); wrapper.StatusUpdate += (s, e) => UpdateStatus(e.StatusMessage); result = wrapper.Execute(); printDevice.Dispose(); }); return(result); }
/// <summary> /// Initializes the device. /// </summary> protected override void InitializeDevice() { try { Device = DeviceConstructor.Create(DeviceInfo); _geniusBytesApp = GeniusBytesAppFactory.Create(Device); var preparationManager = new GeniusBytesPreparationManager((JediOmniDevice)Device, _geniusBytesApp); preparationManager.InitializeDevice(false); _collectMemoryManager = new CollectMemoryManager(Device, DeviceInfo); } catch (Exception ex) { // Make sure the device is disposed, if necessary if (Device != null) { Device.Dispose(); Device = null; } // Log the error and re-throw. ExecutionServices.SystemTrace.LogError(ex); throw; } }
/// <summary> /// Executes this plug-in'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) { PluginExecutionResult result = new PluginExecutionResult(PluginResult.Skipped); var data = executionData.GetMetadata <SafeComInstallerActivityData>(); var printDeviceInfo = executionData.Assets.OfType <PrintDeviceInfo>().FirstOrDefault(); _device = DeviceConstructor.Create(printDeviceInfo); _deviceModel = _device.GetDeviceInfo().ModelName; var bundleInstaller = new SafeComBundleInstaller(_device as JediOmniDevice); //only register device doesn't have these details. if (data.SafeComAction != SafeComAdministratorAction.RegisterDevice) { data.SafeComConfigurationCollection["devName"] = _deviceModel; data.SafeComConfigurationCollection["devModel"] = _deviceModel; data.SafeComConfigurationCollection["devPw"] = _device.AdminPassword; } try { _signedSessionId = bundleInstaller.SignIn(string.Empty); switch (data.SafeComAction) { case SafeComAdministratorAction.AddDevice: result = bundleInstaller.InstallSolution(_signedSessionId, data.BundleFile); break; case SafeComAdministratorAction.InitialConfiguration: case SafeComAdministratorAction.UpdateConfiguration: result = bundleInstaller.ConfigureSafeCom(_signedSessionId, data.SafeComConfigurationCollection); break; case SafeComAdministratorAction.RemoveDevice: result = bundleInstaller.RemoveSolution(_signedSessionId, "Safecom"); break; case SafeComAdministratorAction.RegisterDevice: result = bundleInstaller.RegisterDevice(_signedSessionId, data.SafeComConfigurationCollection); break; } } catch (WebException wex) { _device.Dispose(); ExecutionServices.SystemTrace.LogError( $"Safecom Action {data.SafeComAction} failed on device:{_device.Address}", wex); UpdateStatus($"{printDeviceInfo.AssetId}: Failed with exception: {wex.Message}"); return(new PluginExecutionResult(PluginResult.Failed, wex.Message)); } catch (Exception ex) { _device.Dispose(); ExecutionServices.SystemTrace.LogError( $"Safecom Action {data.SafeComAction} failed on device:{_device.Address}", ex); UpdateStatus($"{printDeviceInfo.AssetId}: Failed with exception: {ex.Message}"); return(new PluginExecutionResult(PluginResult.Failed, ex.Message)); } _device.Dispose(); UpdateStatus($"{printDeviceInfo.AssetId}: Passed"); return(result); }
//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); }
/// <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); }
public void WaitForReady() { TimeSpan waitBetweenChecks = TimeSpan.FromSeconds(5); OnUpdateStatus("Waiting for device to come to ready..."); PowerState[] rejectedPowerStates = new PowerState[] { PowerState.Off, PowerState.None }; OnUpdateStatus($" Waiting for device to return a responsive power state..."); int powerCheckCount = 0; bool success = Wait.ForTrue( () => { var state = _device.PowerManagement.GetPowerState(); OnUpdateStatus($" Device Power State: {state}"); bool ok = !rejectedPowerStates.Contains(state); if (ok) { ++powerCheckCount; } return(ok); } , TimeSpan.FromSeconds(240) , waitBetweenChecks); if (!success) { throw new DeviceInvalidOperationException($"Device did not come to an acceptable power state. ({_device.Address})"); } DeviceStatus[] acceptedDeviceStatus = new DeviceStatus[] { DeviceStatus.Running, DeviceStatus.Warning }; OnUpdateStatus($" Waiting for device status reflecting readiness..."); success = Wait.ForTrue( () => { var state = _device.GetDeviceStatus(); OnUpdateStatus($" Device Status: {state}"); return(acceptedDeviceStatus.Contains(state)); } , TimeSpan.FromSeconds(240) , waitBetweenChecks); if (!success) { throw new DeviceInvalidOperationException($"Device did not return an acceptable status. ({_device.Address})"); } OnUpdateStatus($" Waiting for device web services and OXP services to come online..."); const int MaxCreateCreateDeviceAttempts = 10; int createDeviceAttempts = 0; const int ConsecutiveSuccessfulDeviceInfoCallsRequired = 2; int consecutiveSuccessfulDeviceInfoCalls = 0; StringBuilder statusMessages = new StringBuilder(); do { JediDevice tempDevice = null; try { using (tempDevice = (JediDevice)DeviceConstructor.Create(_deviceInfo)) { var deviceInfo = tempDevice.GetDeviceInfo(); if (++consecutiveSuccessfulDeviceInfoCalls >= ConsecutiveSuccessfulDeviceInfoCallsRequired) { string message = $"Device is ready. (FirmwareRevision {deviceInfo.FirmwareRevision}; FirmwareDateCode: {deviceInfo.FirmwareDateCode})"; OnUpdateStatus($" {message}"); break; } else { string message = $"Device is responding. (ModelName {deviceInfo.ModelName}; ModelNumber: {deviceInfo.ModelNumber}; SerialNumber: {deviceInfo.SerialNumber})"; OnUpdateStatus($" {message}"); statusMessages.AppendLine(message); waitBetweenChecks = TimeSpan.FromSeconds(3); } } } catch (InvalidCastException castX) { // Might encounter exception: Unable to cast object of type 'HP.DeviceAutomation.Phoenix.PhoenixDevice' to type 'HP.DeviceAutomation.Jedi.JediDevice'. // Device is still initializing operate a different web service which looks like a Phoenix device. OnUpdateStatus($" Device is still initializing and hosting a rudimentary EWS landing page on a Phoenix-y web server. ({castX.Message})"); statusMessages.AppendLine(castX.ToString()); } catch (DeviceCommunicationException comX) { // HP.DeviceAutomation.DeviceCommunicationException: OXP UI Configuration service could not be found at 15.86.229.141 // HP.DeviceAutomation.DeviceCommunicationException: OXP UI Configuration service at 15.86.229.141 did not respond. OnUpdateStatus($" Device OXP services not yet ready. ({comX.Message})"); statusMessages.AppendLine(comX.ToString()); } catch (Exception x) { OnUpdateStatus($" {x.Message}"); statusMessages.AppendLine(x.ToString()); } Thread.Sleep(waitBetweenChecks); } while (++createDeviceAttempts <= MaxCreateCreateDeviceAttempts); if (createDeviceAttempts >= MaxCreateCreateDeviceAttempts) { OnUpdateStatus(statusMessages.ToString()); throw new DeviceInvalidOperationException($"Device web services and/or OXP services did not respond as expected after {MaxCreateCreateDeviceAttempts} attempts."); } }
/// <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; _activityData = executionData.GetMetadata <RebootActivityData>(); _performanceLogger = new DeviceWorkflowLogger(_executionData); TimeSpan lockTimeout = TimeSpan.FromMinutes(10); TimeSpan holdTimeout = TimeSpan.FromMinutes(60); UpdateStatus("Starting activity."); 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")); } PluginExecutionResult result = new PluginExecutionResult(PluginResult.Failed, "Failed to Start Reboot"); 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; ExecutionServices.DataLogger.Submit(new ActivityExecutionAssetUsageLog(_executionData, asset)); IDevice device = DeviceConstructor.Create(asset); ExecutionServices.SystemTrace.LogInfo($@"Rebooting {asset.AssetId}"); UpdateStatus($@"Rebooting {asset.AssetId}"); result = RebootDevice(device); //If we rebooted AND we want to set PJL, do so if (_activityData.SetPaperless) { //Wait for WS* to come back up. It's one of the last services WaitForService(device); Thread.Sleep(60000); EnablePJL(device); Thread.Sleep(1000); SetPaperlessPrintMode(true, device); } }); } catch (Exception e) { ExecutionServices.SystemTrace.LogInfo(e); UpdateStatus(e.Message); result = new PluginExecutionResult(PluginResult.Failed, e.Message); } UpdateStatus("Finished activity."); UpdateStatus($"Result = {result.Result}"); return(result); }
/// <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); }
/// <summary> /// Sets up the scan job. /// </summary> /// <param name="device">The device.</param> public PluginExecutionResult Execute(PluginExecutionData executionData) { bool activityFailed = false; StringBuilder failedMessages = new StringBuilder(); _activityData = executionData.GetMetadata <ePrintAdminActivityData>(); _credential = executionData.Credential; PrintDeviceInfo printDeviceInfo = (PrintDeviceInfo)executionData.Assets.First(); _device = DeviceConstructor.Create(printDeviceInfo); _userDnsName = executionData.Environment.UserDnsDomain; _ePrintServerIp = executionData.Servers.First().Address; CookieCollection loginCookie = new CookieCollection(); if (Login(loginCookie).Result == PluginResult.Failed) { return(new PluginExecutionResult(PluginResult.Failed, "Unable to login to eprint server")); } foreach (var eprintTask in _activityData.ePrintAdminTasks) { activityStatus_dataGridView.DataSource = null; try { switch (eprintTask.Operation) { case EprintAdminToolOperation.AddPrinteripv4: case EprintAdminToolOperation.AddPrinterHpac: case EprintAdminToolOperation.AddPrinterPJL: { ePrintAddPrinter(eprintTask, loginCookie); } break; case EprintAdminToolOperation.DeletePrinter: { ePrintDeletePrinter(eprintTask, loginCookie); } break; case EprintAdminToolOperation.ImportPrinter: { ePrintImportPrinter(eprintTask, loginCookie); } break; case EprintAdminToolOperation.RegularUser: case EprintAdminToolOperation.GuestUser: { AddUser(eprintTask, loginCookie); } break; case EprintAdminToolOperation.SendPrintJob: { ePrintSendPrintJob(eprintTask, loginCookie); } break; } activityStatus_dataGridView.Visible = false; activityStatus_dataGridView.DataSource = _activityData.ePrintAdminTasks; activityStatus_dataGridView.Visible = true; } catch (Exception ex) { failedMessages.AppendLine($"Failed for ActivityTask:{eprintTask.Operation} with Exception: {ex.Message}"); activityFailed = true; } } return(activityFailed ? new PluginExecutionResult(PluginResult.Failed, string.Join(",", failedMessages)) : new PluginExecutionResult(PluginResult.Passed, "All test cases passed")); }
private IDevice GetDevice(PrintDeviceInfo printDeviceInfo) => DeviceConstructor.Create(printDeviceInfo);