/// <summary>
        /// Installs any dependent software via a DOS command file before executing the configured file list.
        /// </summary>
        /// <param name="executionData"></param>
        public void Setup(PluginExecutionData executionData)
        {
            _activityData = executionData?.GetMetadata <ExecutorActivityData>();

            if (!string.IsNullOrEmpty(_activityData?.SetupFileName))
            {
                SystemSetup.Run(_activityData.SetupFileName, string.Empty, executionData?.Credential, _activityData.CopyDirectory);
            }
        }
        /// <summary>
        /// Execute the plugin operation.
        /// </summary>
        /// <param name="executionData"></param>
        /// <returns></returns>
        public PluginExecutionResult Execute(PluginExecutionData executionData)
        {
            if (!_setupDone)
            {
                Setup(executionData);
                _setupDone = true;
            }

            _activityData = executionData?.GetMetadata <ExecutorActivityData>();
            _exectuables  = _activityData?.Executables;
            TimeSpan timeout = TimeSpan.FromMinutes(5);

            if (_exectuables == null)
            {
                return(new PluginExecutionResult(PluginResult.Skipped, "No files were configured to execute."));
            }

            foreach (Executable exe in _exectuables)
            {
                string   finalArgument  = exe.Arguments + (exe.PassSessionId ? $" {executionData?.SessionId}" : string.Empty);
                DateTime executionStart = DateTime.Now;

                ProcessExecutionResult result = ProcessUtil.Execute(exe.FilePath, finalArgument, timeout);

                if (result.SuccessfulExit)
                {
                    //Framework.ExecutionServices.SystemTrace.LogDebug($"Success. Output: {result.StandardOutput}");
                    RefreshGrid(new ExecutionResult {
                        FileName = exe.FileName, Result = "Succeeded", ExecutionDateTime = executionStart
                    });
                }
                else
                {
                    RefreshGrid(new ExecutionResult {
                        FileName = exe.FileName, Result = "Failed", ExecutionDateTime = executionStart
                    });

                    StringBuilder errorDescription = new StringBuilder("Error: ");
                    errorDescription.Append(GetProcessError(result, executionStart, timeout));
                    errorDescription.Append(Environment.NewLine);
                    errorDescription.Append("Output: ");
                    errorDescription.Append(result.StandardOutput);
                    errorDescription.Append(Environment.NewLine);
                    errorDescription.Append("File: ");
                    errorDescription.Append(exe.FileName);
                    Framework.ExecutionServices.SystemTrace.LogDebug(errorDescription.ToString());

                    return(new PluginExecutionResult(PluginResult.Failed, errorDescription.ToString()));
                }
            }

            return(new PluginExecutionResult(PluginResult.Passed));
        }
Exemplo n.º 3
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.º 4
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)
        {
            UpdateStatus("Starting activity.");
            UpdateLabel(sessionId_value_label, executionData.SessionId);

            _workflowLogger = new DeviceWorkflowLogger(executionData);
            GFriendExecutionActivityData data = executionData.GetMetadata <GFriendExecutionActivityData>();

            UpdateStatus("Prepare Files.");
            string scriptPath;

            if (executionData.Environment.PluginSettings.ContainsKey("GFScriptPath"))
            {
                scriptPath = executionData.Environment.PluginSettings["GFScriptPath"];
            }
            else
            {
                scriptPath = Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), "scripts", executionData.SessionId);
            }
            UpdateStatus($"GFriend files will be saved to {scriptPath}");

            GFriendPreparationManager.PrepareFiles(data.GFriendFiles, scriptPath);

            string scriptToRun = data.GFriendFiles.Where(s => s.FileType.Equals(GFFileTypes.GFScript)).FirstOrDefault()?.FileName ?? string.Empty;

            if (string.IsNullOrEmpty(scriptToRun))
            {
                UpdateStatus("GF Script file does not exist. Please check activity data");
                return(new PluginExecutionResult(PluginResult.Failed, "Invalid activity data (No Script File)"));
            }

            scriptToRun = Path.Combine(scriptPath, scriptToRun);
            UpdateStatus($"GFriend test script {scriptToRun} will be exeucted.");

            // Run GFriend
            _consoleWriter = new OutputWriter(output_RichTextBox);
            Console.SetOut(_consoleWriter);

            IDeviceInfo           deviceInfo;
            PluginExecutionResult executionResult = new PluginExecutionResult(PluginResult.Passed);

            if (executionData.Assets.Count > 0)
            {
                var devices     = executionData.Assets.OfType <IDeviceInfo>();
                var assetTokens = devices.Select(n => new AssetLockToken(n, data.LockTimeouts));
                _workflowLogger.RecordEvent(DeviceWorkflowMarker.DeviceLockBegin);
                ExecutionServices.CriticalSection.Run(assetTokens, selectedToken =>
                {
                    deviceInfo = (selectedToken as AssetLockToken).AssetInfo as IDeviceInfo;
                    UpdateLabel(dut_value_label, deviceInfo.AssetId);
                    ExecutionServices.DataLogger.Submit(new ActivityExecutionAssetUsageLog(executionData, deviceInfo));
                    executionResult = RunGFriendScript(executionData, scriptToRun, deviceInfo);
                });
                _workflowLogger.RecordEvent(DeviceWorkflowMarker.DeviceLockEnd);
            }
            else
            {
                executionResult = RunGFriendScript(executionData, scriptToRun, null);
            }

            var standardOutput = new StreamWriter(Console.OpenStandardOutput());

            standardOutput.AutoFlush = true;
            Console.SetOut(standardOutput);

            UpdateStatus("Finished activity.");
            UpdateStatus($"Result = {executionResult.Result}");

            return(executionResult);
        }
        public PluginExecutionResult ApplyConfiguration(PluginExecutionData executionData)
        {
            _executionData = executionData;
            _activityData  = executionData.GetMetadata <LockSmithConfigurationActivityData>();
            try
            {
                CopyDriverFiles(_activityData);
                _driver.Manage().Window.Maximize();
                PerformLogin();
                SettingEWSAdminPassword();
                CreateGroup();
                switch (_activityData.Adddevice)
                {
                case PrinterDiscovery.ManualIPAddress:
                    PrinterDiscoveryManualIPAddress();
                    break;

                case PrinterDiscovery.DeviceListFile:
                    PrinterDiscoveryDeviceListFile();
                    break;

                case PrinterDiscovery.AutomaticHops:
                    PrinterDiscoveryAutomaticHops();
                    break;

                case PrinterDiscovery.AutomaticRange:
                    PrinterDiscoveryAutomaticRange();
                    break;

                case PrinterDiscovery.AssetInventory:
                    PrinterDiscoveryAssetInventory();
                    break;
                }

                if (_activityData.PolicyConfiguration)
                {
                    ImportPolicy();
                }

                if (_activityData.ReportExtraction)
                {
                    GenerateReports();
                }

                UpdateStatus("Activities completed successfully.");

                return(new PluginExecutionResult(PluginResult.Passed));
            }
            catch (IOException exception)
            {
                ExecutionServices.SystemTrace.LogError(exception.ToString());
                return(new PluginExecutionResult(PluginResult.Failed, "Selenium Web driver is already in use. Please close all diver instances and re-run."));
            }
            catch (NoSuchElementException exception)
            {
                ExecutionServices.SystemTrace.LogError(exception.ToString());
                return(new PluginExecutionResult(PluginResult.Failed, "Selenium Web element does not exist."));
            }
            catch (NotFoundException exception)
            {
                ExecutionServices.SystemTrace.LogError(exception.ToString());
                return(new PluginExecutionResult(PluginResult.Failed, "Unable to find Selenium web element."));
            }
            catch (StaleElementReferenceException exception)
            {
                ExecutionServices.SystemTrace.LogError(exception.ToString());
                return(new PluginExecutionResult(PluginResult.Failed, "Selenium element reference does not exist."));
            }
            catch (WebDriverTimeoutException exception)
            {
                ExecutionServices.SystemTrace.LogError(exception.ToString());
                return(new PluginExecutionResult(PluginResult.Failed, "Selenium webDriver timed out."));
            }
            catch (WebDriverException exception)
            {
                ExecutionServices.SystemTrace.LogError(exception.ToString());
                return(new PluginExecutionResult(PluginResult.Failed, "Lost communication with the Selenium webdriver."));
            }
            catch (LocksmithConfigurationException exception)
            {
                ExecutionServices.SystemTrace.LogError(exception.ToString());
                return(new PluginExecutionResult(PluginResult.Failed, "Locksmith configuration operation failed while performing a selenium action."));
            }
            catch (Exception exception)
            {
                ExecutionServices.SystemTrace.LogError(exception.ToString());
                return(new PluginExecutionResult(PluginResult.Failed, "Locksmith configuration operation failed."));
            }
            finally
            {
                if (_driver != null)
                {
                    _driver.Quit();
                    _driver.Dispose();
                }
            }
        }
Exemplo n.º 6
0
        private PluginExecutionResult RunApp(IDevice device)
        {
            try
            {
                PluginExecutionResult result = new PluginExecutionResult(PluginResult.Failed);

                _activityData = _executionData.GetMetadata <PrintFromUsbActivityData>();

                IUsbApp        usbApp = UsbAppFactory.Create(device);
                IAuthenticator auth   = AuthenticatorFactory.Create(device, _executionData.Credential, AuthenticationProvider.Auto);

                usbApp.WorkflowLogger = auth.WorkflowLogger = _workflowLogger;

                var preparationManager = DevicePreparationManagerFactory.Create(device);
                preparationManager.InitializeDevice(true);
                preparationManager.WorkflowLogger = _workflowLogger;

                // need to add the ability for user to set eager or lazy authentication
                //AuthenticationMode am = (_data.ApplicationAuthentication == false) ? AuthenticationMode.Eager : AuthenticationMode.Lazy;

                usbApp.Pacekeeper = auth.Pacekeeper = new Pacekeeper(TimeSpan.FromSeconds(2));
                _workflowLogger.RecordEvent(DeviceWorkflowMarker.ActivityBegin);
                usbApp.LaunchPrintFromUsb(auth, AuthenticationMode.Lazy);
                UpdateStatus("The Print From USB app is launched");

                usbApp.SelectUsbPrint(_activityData.UsbName);
                UpdateStatus("The USB is selected");

                usbApp.SelectFile();
                UpdateStatus("File to Print is selected");

                if (usbApp.ExecutePrintJob())
                {
                    UpdateStatus("The selected file is printed");
                    result = new PluginExecutionResult(PluginResult.Passed);
                }

                preparationManager.NavigateHome();
                if (preparationManager.SignOutRequired())
                {
                    preparationManager.SignOut();
                }
                _workflowLogger.RecordEvent(DeviceWorkflowMarker.ActivityEnd);
                return(result);
            }
            catch (DeviceCommunicationException ex)
            {
                GatherTriageData(device, ex.ToString());
                return(new PluginExecutionResult(PluginResult.Failed, ex.Message, "Device communication error."));
            }
            catch (DeviceInvalidOperationException ex)
            {
                GatherTriageData(device, ex.ToString());
                return(new PluginExecutionResult(PluginResult.Failed, ex.Message, "Device automation error."));
            }
            catch (DeviceWorkflowException ex)
            {
                GatherTriageData(device, ex.ToString());
                return(new PluginExecutionResult(PluginResult.Failed, ex, "Device workflow error."));
            }
            catch (Exception ex)
            {
                GatherTriageData(device, ex.ToString());
                throw;
            }
        }
Exemplo n.º 7
0
 /// <summary>
 /// Initializes a new instance of the <see cref="RegusKioskPrintManager" /> class.
 /// </summary>
 /// <param name="executionData">The execution data.</param>
 /// <param name="printOptions">The scan options.</param>
 public RegusKioskPrintManager(PluginExecutionData executionData, RegusKioskPrintOptions printOptions, LockTimeoutData lockTimeoutData)
     : base(executionData, lockTimeoutData)
 {
     _data = executionData.GetMetadata <RegusKioskActivityData>();
     _regusKioskPrintOptions = _data.PrintOptions;
 }
        /// <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);
        }
Exemplo n.º 9
0
 public WorkflowScanManager(PluginExecutionData executionData, ScanOptions scanOptions, string serverName)
     : base(executionData, serverName)
 {
     _data       = executionData.GetMetadata <ScanToWorkflowData>(ConverterProvider.GetMetadataConverters());
     ScanOptions = scanOptions;
 }
Exemplo n.º 10
0
        public PluginExecutionResult Execute(PluginExecutionData executionData)
        {
            CtcSettings.Initialize(executionData);

            // create activity data
            CertificateManagementActivityData activityData = executionData.GetMetadata <CertificateManagementActivityData>(CtcMetadataConverter.Converters);
            var             ipV4Address = IPAddress.Parse(activityData.Ipv4Address);
            PrinterFamilies family      = (PrinterFamilies)Enum.Parse(typeof(PrinterFamilies), Enum <ProductFamilies> .Value(activityData.ProductFamily));

            // Create instance of ews adapter
            // Remember to give Combined sitemapPath + sitemapVersion
            EwsWrapper.Instance().Create(family, activityData.ProductName, activityData.Ipv4Address, Path.Combine(activityData.SitemapPath, activityData.SiteMapVersion), BrowserModel.Firefox);

            EwsWrapper.Instance().Start();
            EwsWrapper.Instance().WakeUpPrinter();
            EwsWrapper.Instance().SetAdvancedOptions();
            EwsWrapper.Instance().EnableSnmpv1v2ReadWriteAccess();

            SnmpWrapper.Instance().Create(activityData.Ipv4Address);
            SnmpWrapper.Instance().SetCommunityName("public");

            TelnetWrapper.Instance().Create(activityData.Ipv4Address);

            //  PrinterFamilies family = (PrinterFamilies)Enum.Parse(typeof(PrinterFamilies), Enum<ProductFamilies>.Value(activityData.ProductFamily));
            Printer.Printer printer = PrinterFactory.Create(family, ipV4Address);
            activityData.MacAddress = printer.MacAddress;

            //Check the Windows Server Service,Packet Capture service and Kiwi Syslog server is up and running
            CtcUtility.StartService("WindowsServerService", activityData.DhcpServerIp);
            CtcUtility.StartService(@"dns", activityData.DhcpServerIp);

            using (DhcpApplicationServiceClient dhcpClient = DhcpApplicationServiceClient.Create(activityData.DhcpServerIp))
            {
                string scope = dhcpClient.Channel.GetDhcpScopeIP(activityData.DhcpServerIp);
                dhcpClient.Channel.DeleteReservation(activityData.DhcpServerIp, scope, activityData.Ipv4Address, activityData.MacAddress);

                if (dhcpClient.Channel.CreateReservation(activityData.DhcpServerIp, scope, ipV4Address.ToString(), activityData.MacAddress, ReservationType.Both))
                {
                    TraceFactory.Logger.Info("Successfully created reservation for IP address: {0}, Mac address: {1} for {2}".FormatWith(ipV4Address, activityData.MacAddress, ReservationType.Both));
                }
                else
                {
                    TraceFactory.Logger.Info("Failed to create reservation for IP address: {0}, Mac address: {1} for {2}".FormatWith(ipV4Address, activityData.MacAddress, ReservationType.Both));
                    return(new PluginExecutionResult(PluginResult.Failed, "Failed to create reservation for IP address: {0}, Mac address: {1} for {2}".FormatWith(ipV4Address, activityData.MacAddress, ReservationType.Both)));
                }
            }

            if (null == _tests)
            {
                _tests = new CertificateManagementTests(activityData);
            }

            // Execute the selected tests
            foreach (int testNumber in activityData.SelectedTests)
            {
                try
                {
                    ExecutionServices.SessionRuntime.AsInternal().WaitIfPaused();
                    _tests.RunTest(executionData, testNumber, ipV4Address, activityData.ProductFamily);
                }
                catch (Exception ex)
                {
                    TraceFactory.Logger.Fatal("** Error while executing Test:{0} \n".FormatWith(testNumber, ex.Message));
                    continue;
                }
            }

            EwsWrapper.Instance().Stop();

            return(new PluginExecutionResult(PluginResult.Passed));
        }
        public PluginExecutionResult Execute(PluginExecutionData executionData)
        {
            CtcSettings.Initialize(executionData);

            NetworkNamingServiceActivityData activityData = executionData.GetMetadata <NetworkNamingServiceActivityData>(CtcMetadataConverter.Converters);

            #region Scenario Prerequisites

            //Check the Windows Server Service,Packet Capture service and Kiwi Syslog server is up and running
            CtcUtility.StartService("WindowsServerService", activityData.PrimaryDhcpServerIPAddress);
            CtcUtility.StartService("PacketCaptureService", activityData.PrimaryDhcpServerIPAddress);
            CtcUtility.StartService("Kiwi Syslog Server", activityData.PrimaryDhcpServerIPAddress);

            //Check dns and wins server is up and running on both primary and secondary dhcp server
            CtcUtility.StartService(@"dns", activityData.PrimaryDhcpServerIPAddress);
            CtcUtility.StartService("WINS", activityData.PrimaryDhcpServerIPAddress);
            CtcUtility.StartService(@"dns", activityData.SecondDhcpServerIPAddress);
            CtcUtility.StartService("WINS", activityData.SecondDhcpServerIPAddress);

            //Check the Wireless printer ip is accessible
            if (activityData.SelectedTests.Contains(678968))
            {
                if (!(NetworkUtil.PingUntilTimeout(IPAddress.Parse(activityData.WirelessIPv4Address), TimeSpan.FromSeconds(20))))
                {
                    MessageBox.Show(string.Concat("Wireless Printer IP Address is not accessible\n\n"),
                                    "Wireless IP Address Not Accessible", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return(new PluginExecutionResult(PluginResult.Failed, "Wireless Printer IP Address is not accessible"));
                }
            }

            //Check whether all devices are accesible and the server IP
            CtcUtility.CheckPrinterConnectivity(activityData.WiredIPv4Address, activityData.PrimaryDhcpServerIPAddress,
                                                activityData.SecondPrinterIPAddress, activityData.SecondDhcpServerIPAddress,
                                                activityData.LinuxServerIPAddress, activityData.SwitchIpAddress);

            // Fetch the VLAN details.
            GetVlanDetails(ref activityData);

            // Check if Switch VLAN details are fetched
            if (3 != activityData.VirtualLanDetails.Count)
            {
                MessageBox.Show(string.Concat("Unable to fetch Switch VLAN details\n\n",
                                              "Check whether Printer is connected to Network Switch.\n",
                                              "Switch should be configured with 3 network virtual LAN."),
                                "Network switch not found", MessageBoxButtons.OK, MessageBoxIcon.Error);

                return(new PluginExecutionResult(PluginResult.Failed, "Unable to fetch Switch VLAN details"));
            }

            //Reservation for Primary Printer
            using (DhcpApplicationServiceClient client = DhcpApplicationServiceClient.Create(activityData.PrimaryDhcpServerIPAddress))
            {
                Printer.Printer printer = PrinterFactory.Create(activityData.ProductFamily, activityData.WiredIPv4Address);
                activityData.PrinterMacAddress = printer.MacAddress.Replace(":", string.Empty);
                client.Channel.DeleteReservation(activityData.PrimaryDhcpServerIPAddress, client.Channel.GetDhcpScopeIP(activityData.PrimaryDhcpServerIPAddress),
                                                 activityData.WiredIPv4Address, activityData.PrinterMacAddress);

                if (client.Channel.CreateReservation(activityData.PrimaryDhcpServerIPAddress, client.Channel.GetDhcpScopeIP(activityData.PrimaryDhcpServerIPAddress),
                                                     activityData.WiredIPv4Address, activityData.PrinterMacAddress, ReservationType.Both))
                {
                    TraceFactory.Logger.Info("Primary Printer IP Address Reservation in DHCP Server for both DHCP and BOOTP : Succeeded");
                }
                else
                {
                    TraceFactory.Logger.Info("Primary Printer IP Address Reservation in DHCP Server for both DHCP and BOOTP: Failed");
                    return(new PluginExecutionResult(PluginResult.Failed, "Primary Printer IP Address Reservation in DHCP Server for both DHCP and BOOTP: Failed"));
                }

                activityData.PrimaryDhcpIPv6Address = client.Channel.GetIPv6Address();
            }

            //Reservation for Secondary Printer[user may give input as primary server ip/secondary server ip ,so getting server ip based on the printer ipaddress]
            string secondDhcpServerIPAddress = Printer.Printer.GetDHCPServerIP(IPAddress.Parse(activityData.SecondPrinterIPAddress)).ToString();
            using (DhcpApplicationServiceClient client = DhcpApplicationServiceClient.Create(secondDhcpServerIPAddress))
            {
                Printer.Printer printer = PrinterFactory.Create(activityData.ProductFamily, activityData.SecondPrinterIPAddress);
                string          secondPrinterMacAddress = printer.MacAddress.Replace(":", string.Empty);
                client.Channel.DeleteReservation(secondDhcpServerIPAddress, client.Channel.GetDhcpScopeIP(secondDhcpServerIPAddress),
                                                 activityData.SecondPrinterIPAddress, secondPrinterMacAddress);

                if (client.Channel.CreateReservation(secondDhcpServerIPAddress, client.Channel.GetDhcpScopeIP(secondDhcpServerIPAddress),
                                                     activityData.SecondPrinterIPAddress, secondPrinterMacAddress, ReservationType.Both))
                {
                    TraceFactory.Logger.Info("Secondary Printer IP Address Reservation in DHCP Server for both DHCP and BOOTP : Succeeded");
                }
                else
                {
                    TraceFactory.Logger.Info("Secondary Printer IP Address Reservation in DHCP Server for both DHCP and BOOTP: Failed");
                    return(new PluginExecutionResult(PluginResult.Failed, "Secondary Printer IP Address Reservation in DHCP Server for both DHCP and BOOTP: Failed"));
                }
            }

            using (DhcpApplicationServiceClient client = DhcpApplicationServiceClient.Create(activityData.SecondDhcpServerIPAddress))
            {
                activityData.SecondaryDhcpIPv6Address = client.Channel.GetIPv6Address();
            }

            #endregion

            // create instance of ews adapter
            EwsWrapper.Instance().Create(Enum <PrinterFamilies> .Parse(activityData.ProductFamily), activityData.ProductName, activityData.WiredIPv4Address, Path.Combine(activityData.SitemapPath, activityData.SiteMapVersion), BrowserModel.Firefox);

            EwsWrapper.Instance().Start();
            EwsWrapper.Instance().WakeUpPrinter();
            EwsWrapper.Instance().SetAdvancedOptions();

            //create instance of SNMP wrapper
            SnmpWrapper.Instance().Create(activityData.WiredIPv4Address);

            //create instance of Telnet wrapper
            TelnetWrapper.Instance().Create(activityData.WiredIPv4Address);

            //Enabling IPV6 startup
            EwsWrapper.Instance().SetDHCPv6OnStartup(true);
            EwsWrapper.Instance().SetIPv6(false);
            EwsWrapper.Instance().SetIPv6(true);
            EwsWrapper.Instance().EnableSnmpv1v2ReadWriteAccess();

            if (null == _networkNamingTests)
            {
                _networkNamingTests = new NetworkNamingServiceTests(activityData);
            }

            // assign the session id to activity data
            activityData.SessionId = executionData.SessionId;

            foreach (int testNumber in activityData.SelectedTests)
            {
                try
                {
                    ExecutionServices.SessionRuntime.AsInternal().WaitIfPaused();
                    _networkNamingTests.RunTest(executionData, testNumber, IPAddress.Parse(activityData.WiredIPv4Address), (ProductFamilies)Enum.Parse(typeof(ProductFamilies), activityData.ProductFamily));
                }
                catch (Exception generalException)
                {
                    TraceFactory.Logger.Info("Test {0} failed with error: {1}".FormatWith(testNumber, generalException.Message));
                }
            }

            EwsWrapper.Instance().Stop();

            return(new PluginExecutionResult(PluginResult.Passed));
        }
Exemplo n.º 12
0
 /// <summary>
 /// Initializes a new instance of the <see cref="NetworkFolderScanManager" /> class.
 /// </summary>
 /// <param name="executionData">The execution data.</param>
 /// <param name="scanOptions">The scan options.</param>
 /// <param name="serverName">Name of the server.</param>
 public NetworkFolderScanManager(PluginExecutionData executionData, string serverName)
     : base(executionData, serverName)
 {
     _data       = executionData.GetMetadata <ScanToFolderData>(ConverterProvider.GetMetadataConverters());
     ScanOptions = _data.ScanOptions;
 }
        public PluginExecutionResult Execute(PluginExecutionData executionData)
        {
            CtcSettings.Initialize(executionData);

            // create activity data
            IPSecurityActivityData activityData = executionData.GetMetadata <IPSecurityActivityData>(CtcMetadataConverter.Converters);

            #region Scenario Prerequisites

            // TODO: Need to enable broadcast and multicast option in failsafe
            // TODO: Cleaning up the rules on client side and on the printer


            //Check the Windows Server Service,Packet Capture service and Kiwi Sys log server is up and running
            CtcUtility.StartService("WindowsServerService", activityData.PrimaryDhcpServerIPAddress);
            CtcUtility.StartService("PacketCaptureService", activityData.PrimaryDhcpServerIPAddress);

            Printer.Printer printer = PrinterFactory.Create(activityData.ProductFamily, activityData.WiredIPv4Address);
            //Reservation for Primary Printer
            using (DhcpApplicationServiceClient client = DhcpApplicationServiceClient.Create(activityData.PrimaryDhcpServerIPAddress))
            {
                activityData.PrinterMacAddress = printer.MacAddress.Replace(":", string.Empty);
                client.Channel.DeleteReservation(activityData.PrimaryDhcpServerIPAddress, client.Channel.GetDhcpScopeIP(activityData.PrimaryDhcpServerIPAddress),
                                                 activityData.WiredIPv4Address, activityData.PrinterMacAddress);

                if (client.Channel.CreateReservation(activityData.PrimaryDhcpServerIPAddress, client.Channel.GetDhcpScopeIP(activityData.PrimaryDhcpServerIPAddress),
                                                     activityData.WiredIPv4Address, activityData.PrinterMacAddress, ReservationType.Both))
                {
                    TraceFactory.Logger.Info("Primary Printer IP Address Reservation in DHCP Server for both DHCP and BOOTP : Succeeded");
                }
                else
                {
                    TraceFactory.Logger.Info("Primary Printer IP Address Reservation in DHCP Server for both DHCP and BOOTP: Failed");
                    return(new PluginExecutionResult(PluginResult.Failed, "Primary Printer IP Address Reservation in DHCP Server for both DHCP and BOOTP: Failed"));
                }
            }

            #endregion

            // create instance of EWS adapter
            EwsWrapper.Instance().Create(Enum <PrinterFamilies> .Parse(activityData.ProductFamily), activityData.ProductName, activityData.WiredIPv4Address, Path.Combine(activityData.SitemapPath, activityData.SitemapsVersion), BrowserModel.Firefox, EwsAdapterType.WebDriverAdapter);

            EwsWrapper.Instance().Start();
            EwsWrapper.Instance().WakeUpPrinter();

            //create instance of SNMP wrapper
            SnmpWrapper.Instance().Create(activityData.WiredIPv4Address);

            //create instance of Telnet wrapper
            TelnetWrapper.Instance().Create(activityData.WiredIPv4Address);

            //IPv6 and Dhcpv6 on startup should be enabled to get IPv6 addresses. Applicable only for VEP
            if (PrinterFamilies.VEP.ToString().EqualsIgnoreCase(activityData.ProductFamily) ||
                PrinterFamilies.LFP.ToString().EqualsIgnoreCase(activityData.ProductFamily))
            {
                EwsWrapper.Instance().SetDHCPv6(true);
                EwsWrapper.Instance().SetDHCPv6OnStartup(true);
                EwsWrapper.Instance().SetIPv6(false);
                EwsWrapper.Instance().SetIPv6(true);
                EwsWrapper.Instance().EnableSnmpv1v2ReadWriteAccess();
            }

            TraceFactory.Logger.Info("Collecting Ipv6 addresses of the printer");
            activityData.IPV6StatefullAddress = printer.IPv6StateFullAddress.ToString();
            activityData.IPV6StatelessAddress = printer.IPv6StatelessAddresses[0].ToString();
            activityData.LinkLocalAddress     = printer.IPv6LinkLocalAddress.ToString();

            // assign session id to activity data
            activityData.SessionId = executionData.SessionId;

            if (null == _ipSecuritytests)
            {
                _ipSecuritytests = new IPSecurityTests(activityData);
            }

            // Execute the selected tests
            foreach (int testNumber in activityData.SelectedTests)
            {
                try
                {
                    ExecutionServices.SessionRuntime.AsInternal().WaitIfPaused();
                    _ipSecuritytests.RunTest(executionData, testNumber, IPAddress.Parse(activityData.WiredIPv4Address), (ProductFamilies)Enum.Parse(typeof(ProductFamilies), activityData.ProductFamily));
                }
                catch (Exception ex)
                {
                    TraceFactory.Logger.Fatal("Error while executing Test:{0} \n".FormatWith(testNumber, ex.Message));
                    continue;
                }
            }

            EwsWrapper.Instance().Stop();

            return(new PluginExecutionResult(PluginResult.Passed));
        }
Exemplo n.º 14
0
 public CopyManager(PluginExecutionData executionData, ScanOptions scanOptions)
     : base(executionData)
 {
     _data       = executionData.GetMetadata <CopyData>(ConverterProvider.GetMetadataConverters());
     ScanOptions = scanOptions;
 }
Exemplo n.º 15
0
 /// <summary>
 /// Scan Manager for the ScanToJobStorage plugin.
 /// </summary>
 public JobStorageScanManager(PluginExecutionData executionData)
     : base(executionData)
 {
     _data       = executionData.GetMetadata <ScanToJobStorageData>(ConverterProvider.GetMetadataConverters());
     ScanOptions = _data.ScanOptions;
 }
Exemplo n.º 16
0
        private PluginExecutionResult RunApp(IDevice device)
        {
            try
            {
                PluginExecutionResult result = new PluginExecutionResult(PluginResult.Failed);

                _activityData = _executionData.GetMetadata <PrintFromJobStorageActivityData>();

                IJobStoragePrintApp jobStorageApp = JobStoragePrintAppFactory.Create(device);
                IAuthenticator      authenticator = GetAuthenticator(_activityData.AuthProvider, device);

                AuthenticationMode am = (_activityData.ApplicationAuthentication == false) ? AuthenticationMode.Eager : AuthenticationMode.Lazy;

                var preparationManager = DevicePreparationManagerFactory.Create(device);
                preparationManager.InitializeDevice(true);

                jobStorageApp.Pacekeeper = authenticator.Pacekeeper = new Pacekeeper(TimeSpan.FromSeconds(2));
                jobStorageApp.Launch(authenticator, am);
                UpdateStatus("The Print From Job Storage app is launched");

                jobStorageApp.SelectFolder(_activityData.FolderName);
                UpdateStatus($"The Selected Folder: '{_activityData.FolderName}'");

                if (_activityData.PrintAll)
                {
                    bool allJobsSelected;
                    allJobsSelected = jobStorageApp.SelectAllJobs(_activityData.Pin, _activityData.FolderName);
                    if (allJobsSelected)
                    {
                        jobStorageApp.ExecutePrintJob();
                        UpdateStatus("All jobs are selected and printed");
                        if (_activityData.DeleteJobAfterPrint)
                        {
                            try
                            {
                                jobStorageApp.DeletePrintedJob();
                                UpdateStatus("All Selected Jobs were deleted");
                            }
                            catch (JobStorageDeleteJobExeception ex)
                            {
                                string message = $"The selected Job was not deleted. {ex.ToString()}";
                                LogDebug(message);
                                UpdateStatus(message);
                            }
                        }
                        result = new PluginExecutionResult(PluginResult.Passed);
                    }
                }
                else
                {
                    jobStorageApp.SelectFirstJob(_activityData.Pin, _activityData.NumberOfCopies, _activityData.FolderName);
                    UpdateStatus("The first job is selected");
                    jobStorageApp.ExecutePrintJob();
                    UpdateStatus("The first job is printed");
                    if (_activityData.DeleteJobAfterPrint)
                    {
                        try
                        {
                            jobStorageApp.DeletePrintedJob();
                            UpdateStatus("The Selected job was deleted");
                        }
                        catch (JobStorageDeleteJobExeception ex)
                        {
                            string message = $"The selected Job was not deleted. {ex.ToString()}";
                            LogDebug(message);
                            UpdateStatus(message);
                        }
                    }
                    result = new PluginExecutionResult(PluginResult.Passed);
                }
                preparationManager.Reset();
                return(result);
            }
            catch (DeviceCommunicationException ex)
            {
                GatherTriageData(device, ex.ToString());
                return(new PluginExecutionResult(PluginResult.Failed, ex.Message, "Device communication error."));
            }
            catch (DeviceInvalidOperationException ex)
            {
                GatherTriageData(device, ex.ToString());
                return(new PluginExecutionResult(PluginResult.Failed, ex.Message, "Device automation error."));
            }
            catch (DeviceWorkflowException ex)
            {
                GatherTriageData(device, ex.ToString());
                return(new PluginExecutionResult(PluginResult.Failed, ex, "Device workflow error."));
            }
            catch (Exception ex)
            {
                GatherTriageData(device, ex.ToString());
                throw;
            }
        }
Exemplo n.º 17
0
        /// <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)
        {
            _executionData     = executionData;
            _performanceLogger = new DeviceWorkflowLogger(_executionData);
            _activityData      = _executionData.GetMetadata <DriverlessPrintingActivityData>();
            var printer = executionData.Assets.OfType <PrintDeviceInfo>().FirstOrDefault();

            if (printer == null)
            {
                return(new PluginExecutionResult(PluginResult.Skipped, "No assets available for execution."));
            }
            if (!printer.Attributes.HasFlag(AssetAttributes.Printer))
            {
                return(new PluginExecutionResult(PluginResult.Skipped, "The device has no print capability."));
            }
            var address = printer.Address;

            var iteratorMode = _activityData.ShuffleDocuments
                ? CollectionSelectorMode.ShuffledRoundRobin
                : CollectionSelectorMode.Random;
            var      documentIterator = new DocumentCollectionIterator(iteratorMode);
            var      document         = documentIterator.GetNext(executionData.Documents);
            FileInfo localFile        = ExecutionServices.FileRepository.GetFile(document);

            if (_activityData.PinProtected)
            {
                AddPinProtection(localFile, _activityData.Pin);
            }

            if (_activityData.PrintMethod == PrintMethod.Random)
            {
                Random newRandom = new Random(4);
                var    randomInt = newRandom.Next(0, 999) % 4;
                _activityData.PrintMethod = (PrintMethod)randomInt;
            }

            _performanceLogger.RecordEvent(DeviceWorkflowMarker.PrintJobBegin);
            UpdateStatus($"Printing {document.FileName} via {_activityData.PrintMethod}.");
            switch (_activityData.PrintMethod)
            {
            default:
                Print9100(address, localFile);
                break;

            case PrintMethod.Ftp:
                PrintFtp(address, "admin", printer.AdminPassword, localFile, true);
                break;

            case PrintMethod.Ipp:
                PrintIpp(address, localFile);
                break;

            case PrintMethod.Ews:
                PrintEws(address, printer.AdminPassword, localFile);
                break;
            }
            _performanceLogger.RecordEvent(DeviceWorkflowMarker.PrintJobEnd);
            _performanceLogger.RecordExecutionDetail(DeviceWorkflowMarker.PrintJobEnd, _activityData.PrintMethod.ToString());
            ActivityExecutionDocumentUsageLog documentLog = new ActivityExecutionDocumentUsageLog(executionData, document);

            ExecutionServices.DataLogger.Submit(documentLog);

            if (_activityData.PrintJobSeparator)
            {
                UpdateStatus("Printing Job Separator.");
                PrintJobSeparator(address);
            }
            localFile.Delete();
            return(_result);
        }
Exemplo n.º 18
0
        public PluginExecutionResult Execute(PluginExecutionData executionData)
        {
            if (!_setupDone)
            {
                Setup(executionData);
                _setupDone = true;
            }

            try
            {
                var action = new Action(() =>
                {
                    ExecutionServices.SystemTrace.LogDebug("Emulating network condition now");
                    NestService.Initialize();
                    NestActivityData data = executionData.GetMetadata <NestActivityData>();;
                    if (!string.IsNullOrEmpty(data.EmulationString))
                    {
                        if (File.Exists(_emulationFileName))
                        {
                            File.Delete(_emulationFileName);
                        }

                        var xDocument = XDocument.Parse(data.EmulationString, LoadOptions.None);
                        xDocument.Save(_emulationFileName, SaveOptions.None);
                        ExecutionServices.SystemTrace.LogDebug("Emulation file created");

                        if (NestService.StartEmulation(_emulationFileName))
                        {
                            networkprofile_textBox.Text = data.EmulationProfileName;
                            UpdateUI(data.EmulationString);
                        }
                    }
                    else
                    {
                        if (NetworkEmulator.NetworkEmulationInstaller.IsNetworkEmulationBoundToAnyNetworkInterfaceCards())
                        {
                            if (NestService.StopEmulation())
                            {
                                nic_textBox.Text = @"Not emulating";
                                ExecutionServices.SystemTrace.LogInfo("Network Emulation Stopped");
                            }
                        }
                        else
                        {
                            ExecutionServices.SystemTrace.LogInfo("Network Emulation is currently not running");
                        }
                    }
                });

                ExecutionServices.CriticalSection.Run(new Framework.Synchronization.LocalLockToken("NetworkEmulation", new TimeSpan(0, 5, 0), new TimeSpan(0, 5, 0)), action);
            }
            catch (NetworkEmulator.NetworkEmulationNotInitializedException eNonInitialized)
            {
                ExecutionServices.SystemTrace.LogDebug("Emulator not Initialized " + eNonInitialized.Message);
                return(new PluginExecutionResult(PluginResult.Failed, "Emulator not Initialized :" + eNonInitialized.Message));
            }
            catch (Exception genericException)
            {
                ExecutionServices.SystemTrace.LogDebug(genericException.Message);
                return(new PluginExecutionResult(PluginResult.Failed, "Activity Failed :" + genericException.Message));
            }

            return(new PluginExecutionResult(PluginResult.Passed));
        }
Exemplo n.º 19
0
        public PluginExecutionResult Execute(PluginExecutionData executionData)
        {
            _activityData       = executionData?.GetMetadata <PrintQueueManagementActivityData>();
            _documentCollection = executionData?.Documents;

            _localPrintQueueInfo = executionData?.PrintQueues.First() as DynamicLocalPrintQueueInfo;

            _taskCounter = 0;

            foreach (var pqmTask in _activityData.PrintQueueTasks)
            {
                activityStatus_dataGridView.DataSource = null;

                switch (pqmTask.Operation)
                {
                case PrintQueueOperation.Install:
                {
                    pqmTask.Status = InstallPrintQueue(executionData);
                }
                break;

                case PrintQueueOperation.Upgrade:
                {
                    UpgradePrintQueue(pqmTask, executionData.Environment.PluginSettings);
                }
                break;

                case PrintQueueOperation.Uninstall:
                {
                    pqmTask.Status = UninstallPrintQueue();
                }
                break;

                case PrintQueueOperation.Print:
                {
                    pqmTask.Status = PrintDocument(pqmTask.TargetObject.ToString());
                }
                break;

                case PrintQueueOperation.Cancel:
                {
                    pqmTask.Status = CancelDocument(pqmTask.TargetObject.ToString(), pqmTask.Delay);
                }
                break;

                case PrintQueueOperation.Configure:
                {
                    ConfigureQueueForm(pqmTask);
                }
                break;
                }
                activityStatus_dataGridView.Visible = false;

                activityStatus_dataGridView.DataSource = _activityData.PrintQueueTasks;
                activityStatus_dataGridView.Visible    = true;

                _taskCounter++;
            }

            return(_activityData.PrintQueueTasks.All(x => x.Status == Status.Passed) ? new PluginExecutionResult(PluginResult.Passed) : new PluginExecutionResult(PluginResult.Failed));
        }
Exemplo n.º 20
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ClioScanManager" /> class.
 /// </summary>
 /// <param name="executionData">The execution data.</param>
 /// <param name="scanOptions">The scan options.</param>
 /// <param name="lockTimeoutData">The lock timeout options.</param>
 public ClioScanManager(PluginExecutionData executionData, LinkScanOptions scanOptions, LockTimeoutData lockTimeoutData)
     : base(executionData, scanOptions, lockTimeoutData)
 {
     _data = executionData.GetMetadata <ClioActivityData>();
 }
        public PluginExecutionResult Execute(PluginExecutionData executionData)
        {
            CtcSettings.Initialize(executionData);

            WebProxyActivityData activityData = executionData.GetMetadata <WebProxyActivityData>(CtcMetadataConverter.Converters);

            #region Scenario Prerequisites

            //Check the Windows Server Service is up and running on all servers
            CtcUtility.StartService("WindowsServerService", activityData.PrimaryDHCPServerIPAddress);
            CtcUtility.StartService("WindowsServerService", activityData.UnsecureWebProxyServerIPAddress);
            CtcUtility.StartService("WindowsServerService", activityData.SecureWebProxyServerIPAddress);
            CtcUtility.StartService("WindowsServerService", activityData.WPADServerIPAddress);

            //Add WPAD entry and Domain Name on the DHCP Server
            DhcpApplicationServiceClient serviceFunction = DhcpApplicationServiceClient.Create(activityData.PrimaryDHCPServerIPAddress);
            activityData.PrimaryDHCPScopeIPAddress = serviceFunction.Channel.GetDhcpScopeIP(activityData.PrimaryDHCPServerIPAddress);
            serviceFunction.Channel.SetWPADServer(activityData.PrimaryDHCPServerIPAddress, activityData.PrimaryDHCPScopeIPAddress, activityData.cURLPathIPAddress);
            activityData.DomainName = "lfpctc.com";

            string recordType = "A";
            serviceFunction.Channel.SetDomainName(activityData.PrimaryDHCPServerIPAddress, activityData.PrimaryDHCPScopeIPAddress, activityData.DomainName);

            // Retrieving hostnames of all servers

            SystemConfigurationClient secureProxy = SystemConfigurationClient.Create(activityData.SecureWebProxyServerIPAddress);
            activityData.SecureWebProxyServerHostName = secureProxy.Channel.GetHostName();
            TraceFactory.Logger.Info("Secure Web Proxy hostname is {0}".FormatWith(activityData.SecureWebProxyServerHostName));

            SystemConfigurationClient unsecureProxy = SystemConfigurationClient.Create(activityData.UnsecureWebProxyServerIPAddress);
            activityData.UnsecureWebProxyServerHostName = unsecureProxy.Channel.GetHostName();
            TraceFactory.Logger.Info("Unsecure Web Proxy hostname is {0}".FormatWith(activityData.UnsecureWebProxyServerHostName));

            SystemConfigurationClient wpadServer = SystemConfigurationClient.Create(activityData.WPADServerIPAddress);
            activityData.WPADServerHostName = wpadServer.Channel.GetHostName();
            TraceFactory.Logger.Info("WPAD hostname is {0}".FormatWith(activityData.WPADServerHostName));

            //Add DNS entry for all servers on the DHCP/DNS server
            DnsApplicationServiceClient dnsClient = DnsApplicationServiceClient.Create(activityData.PrimaryDHCPServerIPAddress);
            dnsClient.Channel.AddDomain(activityData.DomainName);
            dnsClient.Channel.AddRecord(activityData.DomainName, activityData.SecureWebProxyServerHostName, recordType, activityData.SecureWebProxyServerIPAddress);
            dnsClient.Channel.AddRecord(activityData.DomainName, activityData.UnsecureWebProxyServerHostName, recordType, activityData.UnsecureWebProxyServerIPAddress);
            dnsClient.Channel.AddRecord(activityData.DomainName, activityData.WPADServerHostName, recordType, activityData.WPADServerIPAddress);

            string curlFqdn = string.Concat(activityData.WPADServerHostName, activityData.DomainName);
            activityData.cURLPathFQDN             = string.Concat("http://", curlFqdn, ":80/wpad.dat");
            activityData.SecureWebProxyServerFQDN = string.Concat(activityData.SecureWebProxyServerHostName, activityData.DomainName);

            TraceFactory.Logger.Info(activityData.cURLPathFQDN);
            TraceFactory.Logger.Info(activityData.SecureWebProxyServerFQDN);

            PrinterFamilies family  = (PrinterFamilies)Enum.Parse(typeof(PrinterFamilies), activityData.ProductFamily);
            Printer         printer = PrinterFactory.Create(family, IPAddress.Parse(activityData.WiredIPv4Address));

            // create instance of ews adapter
            EwsWrapper.Instance().Create(family, activityData.ProductName, activityData.WiredIPv4Address, Path.Combine(activityData.SitemapPath, activityData.SiteMapVersion), BrowserModel.Firefox);
            EwsWrapper.Instance().Start();

            //Create instance of SNMP Wrapper
            SnmpWrapper.Instance().Create(activityData.WiredIPv4Address);

            //Create instance of Telnet Wrapper
            TelnetWrapper.Instance().Create(activityData.WiredIPv4Address);

            //Wake up the printer and disable sleep mode
            EwsWrapper.Instance().WakeUpPrinter();
            printer.KeepAwake();

            EwsWrapper.Instance().EnableSnmpv1v2ReadWriteAccess();

            #endregion
            if (null == _webProxyTests)
            {
                _webProxyTests = new WebProxyTests(activityData);
            }

            // assign the session id to activity data
            activityData.SessionId = executionData.SessionId;

            foreach (int testNumber in activityData.SelectedTests)
            {
                try
                {
                    ExecutionServices.SessionRuntime.AsInternal().WaitIfPaused();
                    _webProxyTests.RunTest(executionData, testNumber, IPAddress.Parse(activityData.WiredIPv4Address), (ProductFamilies)Enum.Parse(typeof(ProductFamilies), activityData.ProductFamily));
                }
                catch (Exception generalException)
                {
                    TraceFactory.Logger.Info("Test {0} failed with error: {1}".FormatWith(testNumber, generalException.Message));
                }
            }

            EwsWrapper.Instance().Stop();

            return(new PluginExecutionResult(PluginResult.Passed));
        }
        /// <summary>
        ///Execution point for the plugin
        /// <seealso cref="PluginExecutionData"/>
        /// <seealso cref="PluginExecutionResult"/>
        /// <seealso cref="PluginResult"/>
        /// <param name="executionData">The execution data.</param>
        /// <returns>A <see cref="PluginExecutionResult"/> indicating the outcome of the
        /// execution.</returns>
        /// </summary>

        public PluginExecutionResult Execute(PluginExecutionData executionData)
        {
            var serviceHost = executionData.Environment.PluginSettings["BashLogCollectorServiceHost"];

            if (string.IsNullOrEmpty(serviceHost))
            {
                return(new PluginExecutionResult(PluginResult.Error, "Bash Logger Service Host setting missing. Please enter the value in Plugin Settings"));
            }

            _client = new BashLogCollectorClient(serviceHost);
            _data   = executionData.GetMetadata <BashLoggerActivityData>();

            try
            {
                Parallel.ForEach(executionData.Assets.OfType <IDeviceInfo>(),
                                 asset =>
                {
                    var assetId = _client.CreateLogger(asset.AssetId);
                    if (string.IsNullOrEmpty(assetId))
                    {
                        ExecutionServices.SystemTrace.LogError(
                            $"Unable to Create Logger for {asset.AssetId}, Please verify the bash logger information for the device in Asset Inventory");
                        return;
                    }
                    switch (_data.LoggerAction)
                    {
                    case LoggerAction.Start:
                        _client.StartLogging(assetId);
                        UpdateStatus($"Logging Started for device: {asset.AssetId}");
                        break;

                    case LoggerAction.Stop:
                        _client.StopLogging(assetId);
                        UpdateStatus($"Logging Stopped for device: {asset.AssetId}");
                        break;

                    case LoggerAction.CollectLog:
                        {
                            UpdateStatus($"Collecting Logs for device: {asset.AssetId}");
                            var log = _client.CollectLog(assetId);
                            UpdateStatus($"Collection of Logs completed for device: {asset.AssetId}");
                            _client.Flush(assetId);
                            UpdateStatus($"Clearing the Logs for device: {asset.AssetId}");
                            _bashLogConcurrentDictionary.AddOrUpdate(assetId, log, (key, oldvalue) => oldvalue + log);
                        }
                        break;
                    }
                });
            }
            catch (Exception e)
            {
                return(new PluginExecutionResult(PluginResult.Error, e.InnerException?.Message ?? e.Message));
            }

            if (_data.LoggerAction == LoggerAction.CollectLog)
            {
                foreach (var bashLogPair in _bashLogConcurrentDictionary)
                {
                    var fileSplitSize = _data.FileSplitSize * 1024 * 1024;
                    var numOfFiles    = bashLogPair.Value.Length / fileSplitSize + 1;

                    if (!Directory.Exists(_data.FolderPath))
                    {
                        UpdateStatus("Given path doesn't exist, switching to temporary location");
                        _data.FolderPath = Path.GetTempPath();
                    }

                    for (int i = 0; i < numOfFiles; i++)
                    {
                        using (
                            var logFile =
                                File.Create(
                                    Path.Combine(_data.FolderPath,
                                                 $"{bashLogPair.Key}_{executionData.SessionId}_BashLog_{i}.txt"), fileSplitSize,
                                    FileOptions.None))
                        {
                            byte[] buffer = new byte[fileSplitSize];

                            //complicated math below
                            //checks if the file split size is less than total file length, check for total log size is smaller than split size, check for last chunk file to be written to avoid null character entry
                            int charCount = fileSplitSize < bashLogPair.Value.Length
                                ? fileSplitSize < bashLogPair.Value.Length - i * fileSplitSize
                                    ? fileSplitSize
                                    : bashLogPair.Value.Length - i * fileSplitSize
                                : bashLogPair.Value.Length;
                            Encoding.ASCII.GetBytes(bashLogPair.Value, i * fileSplitSize, charCount, buffer,
                                                    buffer.GetLowerBound(0));
                            //write the log file
                            UpdateStatus($"Writing the log file: {logFile.Name}");
                            logFile.Write(buffer, 0, charCount);
                            logFile.Flush(true);
                        }
                    }
                }
            }

            return(new PluginExecutionResult(PluginResult.Passed));
        }
Exemplo n.º 23
0
        public PluginExecutionResult Execute(PluginExecutionData executionData)
        {
            CtcSettings.Initialize(executionData);

            // create activity data
            DotOneXActivityData activityData = executionData.GetMetadata <DotOneXActivityData>(CtcMetadataConverter.Converters);
            PrinterFamilies     family       = (PrinterFamilies)Enum.Parse(typeof(PrinterFamilies), activityData.ProductFamily);

            activityData.DotOneXUserName = DOT1X_USERNAME.FormatWith(activityData.RadiusServerType.ToString().ToLower(CultureInfo.CurrentCulture));
            activityData.DotOneXPassword = DOT1X_PASSWORD;
            activityData.SharedSecret    = SHARED_SECRET;
            activityData.PolicyName      = NETWORK_POLICY;

            bool continueTest = true;

            while (continueTest && !NetworkUtil.PingUntilTimeout(IPAddress.Parse(activityData.Ipv4Address), TimeSpan.FromSeconds(30)))
            {
                continueTest = DotOneXTemplates.ShowErrorPopUp("Printer: {0} is not available.\nPlease cold reset the printer.".FormatWith(activityData.Ipv4Address));
            }

            if (!continueTest)
            {
                return(new PluginExecutionResult(PluginResult.Failed, "Printer: {0} is not available.\nPlease cold reset the printer.".FormatWith(activityData.Ipv4Address)));
            }

            // create instance of ews adapter
            EwsWrapper.Instance().Create(family, activityData.ProductName, activityData.Ipv4Address, Path.Combine(activityData.SitemapPath, activityData.SiteMapVersion), BrowserModel.Firefox);

            EwsWrapper.Instance().Start();

            EwsWrapper.Instance().WakeUpPrinter();

            EwsWrapper.Instance().EnableSnmpv1v2ReadWriteAccess();

            SnmpWrapper.Instance().Create(activityData.Ipv4Address);
            SnmpWrapper.Instance().SetCommunityName("public");

            TelnetWrapper.Instance().Create(activityData.Ipv4Address);

            //TODO: Migration issue even thought it is not migration issue why it is commented
            //EwsWrapper.Instance().SetWSDiscovery(true);

            Printer.Printer printer = PrinterFactory.Create(activityData.ProductFamily, activityData.Ipv4Address);
            activityData.MacAddress = printer.MacAddress;

            using (DhcpApplicationServiceClient dhcpClient = DhcpApplicationServiceClient.Create(activityData.DhcpServerIp))
            {
                string scope = dhcpClient.Channel.GetDhcpScopeIP(activityData.DhcpServerIp);
                dhcpClient.Channel.DeleteReservation(activityData.DhcpServerIp, scope, activityData.Ipv4Address, activityData.MacAddress);

                if (dhcpClient.Channel.CreateReservation(activityData.DhcpServerIp, scope, activityData.Ipv4Address, activityData.MacAddress, ReservationType.Both))
                {
                    TraceFactory.Logger.Info("Successfully created reservation for IP address: {0}, Mac address: {1} for {2}".FormatWith(activityData.Ipv4Address, activityData.MacAddress, ReservationType.Both));
                }
                else
                {
                    TraceFactory.Logger.Info("Failed to create reservation for IP address: {0}, Mac address: {1} for {2}".FormatWith(activityData.Ipv4Address, activityData.MacAddress, ReservationType.Both));
                    return(new PluginExecutionResult(PluginResult.Failed, "Failed to create reservation for IP address: {0}, Mac address: {1} for {2}".FormatWith(activityData.Ipv4Address, activityData.MacAddress, ReservationType.Both)));
                }
            }

            if (!ConfigureRadiusServer(activityData))
            {
                return(new PluginExecutionResult(PluginResult.Failed, "Failed to configure radius server"));
            }

            if (!ConfigureSwitch(activityData))
            {
                return(new PluginExecutionResult(PluginResult.Failed, "Failed to configure switch"));
            }

            activityData.SessionId = executionData.SessionId;

            if (null == _tests)
            {
                _tests = new DotOneXTests(activityData);
            }

            // Execute the selected tests
            foreach (int testNumber in activityData.SelectedTests)
            {
                try
                {
                    ExecutionServices.SessionRuntime.AsInternal().WaitIfPaused();
                    _tests.RunTest(executionData, testNumber, IPAddress.Parse(activityData.Ipv4Address), (ProductFamilies)Enum.Parse(typeof(ProductFamilies), activityData.ProductFamily));
                }
                catch (Exception ex)
                {
                    TraceFactory.Logger.Fatal("Error while executing Test:{0} \n".FormatWith(testNumber, ex.Message));
                }
            }

            EwsWrapper.Instance().Stop();

            return(new PluginExecutionResult(PluginResult.Passed));
        }
Exemplo n.º 24
0
        /// <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"));
        }
Exemplo n.º 25
0
        /// <summary>
        /// Executes this plugin's workflow using the specified <see cref="T:HP.ScalableTest.Framework.Plugin.PluginExecutionData" />.
        /// </summary>
        /// <param name="executionData">The execution data.</param>
        /// <returns>A <see cref="T:HP.ScalableTest.Framework.Plugin.PluginExecutionResult" /> indicating the outcome of the execution.</returns>
        public PluginExecutionResult Execute(PluginExecutionData executionData)
        {
            PluginExecutionResult result = new PluginExecutionResult(PluginResult.Passed);

            _executionData = executionData;

            _deviceAssets = executionData.Assets.OfType <IDeviceInfo>().ToList();
            ExecutionServices.SystemTrace.LogDebug($"# of assets in ExecutionData: {executionData.Assets.Count}");

            try
            {
                UpdateStatus("Starting activity...");
                _activityData = executionData.GetMetadata <AuthenticationData>(ConverterProvider.GetMetadataConverters());

                _workflowLogger = new DeviceWorkflowLogger(executionData);
                TimeSpan acquireTimeout = _activityData.LockTimeouts.AcquireTimeout;
                TimeSpan holdTimeout    = _activityData.LockTimeouts.HoldTimeout;

                string msg = string.Empty;

                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;
                    LogDevice(deviceInfo);

                    using (IDevice device = SetDevice(deviceInfo))
                    {
                        var retryManager = new PluginRetryManager(executionData, UpdateStatus);
                        result           = retryManager.Run(() => LaunchApp(device, deviceInfo));
                    }
                });

                _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)
            {
                result = new PluginExecutionResult(PluginResult.Failed, ex, "Device workflow error.");
            }
            catch (AcquireLockTimeoutException)
            {
                return(new PluginExecutionResult(PluginResult.Skipped, "Could not obtain lock on specified devices(s).", "Device unavailable."));
            }
            catch (HoldLockTimeoutException)
            {
                return(new PluginExecutionResult(PluginResult.Error, $"Automation did not complete within {_activityData.LockTimeouts.HoldTimeout}.", "Automation timeout exceeded."));
            }
            finally
            {
                UpdateStatus("Finished activity");
            }
            return(result);
        }
Exemplo n.º 26
0
 /// <summary>
 /// Initializes a new instance of the <see cref="iManageScanManager" /> class.
 /// </summary>
 /// <param name="executionData">The execution data.</param>
 /// <param name="scanOptions">The scan options.</param>
 /// <param name="serverName">Name of the server.</param>
 public iManageScanManager(PluginExecutionData executionData, LinkScanOptions scanOptions, LockTimeoutData lockTimeoutData, string serverName)
     : base(executionData, scanOptions, lockTimeoutData, serverName)
 {
     _data = executionData.GetMetadata <iManageActivityData>();
 }
Exemplo n.º 27
0
        /// <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);
        }
Exemplo n.º 28
0
        /// <summary>
        /// Start the activity.
        /// </summary>
        /// <param name="executionData">Serialized activity data.</param>
        public PluginExecutionResult ProcessActivity(PluginExecutionData executionData)
        {
            PrintingActivityData     data        = executionData.GetMetadata <PrintingActivityData>();
            PrintQueueInfoCollection printQueues = executionData.PrintQueues;

            // Initialize the document iterator, if it is not already created
            if (_documentIterator == null)
            {
                CollectionSelectorMode mode = data.ShuffleDocuments ? CollectionSelectorMode.ShuffledRoundRobin : CollectionSelectorMode.RoundRobin;
                _documentIterator = new DocumentCollectionIterator(mode);
            }

            // Check to make sure we have something in the pool...
            if (printQueues.Count == 0)
            {
                return(new PluginExecutionResult(PluginResult.Skipped, "None of the selected print queues are available.", "No available print queues."));
            }

            // Select a print queue and log the device/server if applicable
            PrintQueueInfo printQueueInfo = printQueues.GetRandom();

            LogDevice(executionData, printQueueInfo);
            LogServer(executionData, printQueueInfo);

            // Get the corresponding system print queue
            LogDebug(string.Format("Retrieving print queue for {0}", printQueueInfo.QueueName));
            PrintQueue printQueue;

            if (ExecutionServices.SessionRuntime.AsInternal().IsCitrixEnvironment())
            {
                printQueue = GetCitrixPrintQueue(printQueueInfo);
            }
            else
            {
                printQueue = PrintQueueController.Connect(printQueueInfo);
            }

            LogDebug(string.Format("Found queue: {0}", printQueue.FullName));

            if (data.JobThrottling)
            {
                // Make sure that there is enough room in the print queue for this job.
                if (!CheckJobCountInQueue(printQueue, data.MaxJobsInQueue))
                {
                    // Skip the activity.
                    return(new PluginExecutionResult(PluginResult.Skipped, "Print Queue cannot accept any more jobs.", "Print queue throttling."));
                }
            }

            LogDebug("Executing print controller");
            if (data.PrintJobSeparator)
            {
                PrintTag(printQueue, executionData);
            }

            // Select a document to print
            Document document = _documentIterator.GetNext(executionData.Documents);
            ActivityExecutionDocumentUsageLog documentLog = new ActivityExecutionDocumentUsageLog(executionData, document);

            ExecutionServices.DataLogger.Submit(documentLog);

            // Download the document and log the starting information for the print job
            Guid              jobId     = SequentialGuid.NewGuid();
            FileInfo          localFile = ExecutionServices.FileRepository.GetFile(document);
            PrintJobClientLog log       = LogPrintJobStart(executionData, localFile, printQueue, jobId);

            // Print the job
            var engine = new Print.PrintingEngine();

            engine.StatusChanged += (s, e) => StatusChanged?.Invoke(s, e);
            var result = engine.Print(localFile, printQueue, jobId);

            // Log the ending information
            LogPrintJobEnd(log, result);
            LogDebug("Controller execution completed");
            return(new PluginExecutionResult(PluginResult.Passed));
        }
Exemplo n.º 29
0
 /// <summary>
 /// Initializes a new instance of the <see cref="HpcrScanManager"/> class.
 /// </summary>
 public HpecScanManager(PluginExecutionData executionData, ScanOptions scanOptions)
     : base(executionData)
 {
     _data       = executionData.GetMetadata <HpecActivityData>();
     ScanOptions = scanOptions;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="CloudConnectorScanManager" /> class.
 /// </summary>
 /// <param name="executionData">The execution data.</param>
 /// <param name="scanOptions">The scan options.</param>
 /// <param name="serverName">Name of the server.</param>
 public CloudConnectorScanManager(PluginExecutionData executionData, LinkScanOptions scanOptions, LockTimeoutData lockTimeoutData, string serverName)
     : base(executionData, scanOptions, lockTimeoutData, serverName)
 {
     ExecutionData = executionData;
     _data         = executionData.GetMetadata <CloudConnectorActivityData>();
 }