public async Task <IActionResult> RunTasks([FromBody] LookUpRequest request)
        {
            try
            {
                _logger.LogInformation(
                    $"New Request with {request.Services?.Count ?? 0} selected services for {request.Address}");
                var badReq = CheckModelState(request);
                if (badReq != null)
                {
                    return(badReq);
                }

                var services = SetDefaultServicesIfNull(request.Services);

                var res = await WorkerHelper
                          .SendToWorkers(_config["WORKER_ADDRESS"], request.Address, services);

                _logger.LogInformation($"Finished processing request for {request.Address}");
                return(new OkObjectResult(res));
            }
            catch (Exception e)
            {
                _logger.LogError(e, $"Error processing request for {request.Address}");
                return(StatusCode(StatusCodes.Status500InternalServerError, new AppErrorResult
                {
                    ErrorMessage = $"Unexpected Error: {e}",
                    FailServices = SetDefaultServicesIfNull(request.Services)
                }));
            }
        }
        private static void KillOtherWorkers(ILogger <Program> logger, int processId)
        {
            logger.LogDebug($"Killing other workers except process id = '{processId}'");

            var executingFile    = WorkerHelper.GetExecutingFile();
            var workerFileName   = WorkerHelper.GetWorkerFileName(executingFile);
            var currentProcessId = Process.GetCurrentProcess().Id;
            var processes        = Process.GetProcesses();

            foreach (var process in processes)
            {
                logger.LogDebug($"Process id = '{process.Id}', name = '{process.ProcessName}'");

                try
                {
                    if (process.Id == currentProcessId ||
                        process.Id == processId ||
                        process.ProcessName.IndexOf("HstWbInstaller.Imager.GuiApp",
                                                    StringComparison.OrdinalIgnoreCase) < 0 ||
                        process.MainModule == null ||
                        process.MainModule.FileName == null ||
                        process.MainModule.FileName.IndexOf(workerFileName, StringComparison.OrdinalIgnoreCase) < 0)
                    {
                        continue;
                    }
                }
                catch (Exception)
                {
                    continue;
                }

                logger.LogDebug($"Killing worker process id '{process.Id}', name '{process.ProcessName}'");
                process.Kill();
            }
        }
Esempio n. 3
0
        private void m_worker_DoWork(object sender, DoWorkEventArgs e)
        {
            while (m_continue)
            {
                try
                {
                    BackgroundWorker worker = (BackgroundWorker)sender;
                    WorkerHelper     helper = (WorkerHelper)e.Argument;

                    helper.cam.RetrieveBuffer(helper.raw);
                    helper.raw.ConvertToBitmapSource(helper.converted);
                    helper.source = helper.converted.bitmapsource;
                    helper.source.Freeze();
                    worker.ReportProgress(0, helper.source);
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.Message);
                }
                finally
                {
                    GC.Collect();
                }
            }
        }
Esempio n. 4
0
        public void should_handle_bad_result()
        {
            var actual = WorkerHelper.HandleInvalidResult((ServiceType)50);

            Assert.IsNotNull(actual.ErrorMessage);
            Assert.IsNotEmpty(actual.FailServices);
        }
        public FullImageWindow()
        {
            InitializeComponent();
            this.Title = string.Format("FLIR Integrated Imaging Solutions. Zoom Demo. Tier {0}", (RenderCapability.Tier >> 16).ToString());

            m_busmgr    = new ManagedBusManager();
            m_ctldlg    = new CameraControlDialog();
            m_selDlg    = new CameraSelectionDialog();
            m_image     = new ManagedImage();
            m_converted = new ManagedImage();

            m_bitmap = new BitmapImage();
            m_worker = new BackgroundWorker();
            m_worker.WorkerReportsProgress = true;
            m_worker.DoWork          += new DoWorkEventHandler(m_worker_DoWork);
            m_worker.ProgressChanged += new ProgressChangedEventHandler(m_worker_ProgressChanged);
            m_Done = new AutoResetEvent(false);

            RenderOptions.SetBitmapScalingMode(myImage, BitmapScalingMode.LowQuality);
            RenderOptions.SetEdgeMode(myImage, EdgeMode.Aliased);

            if (m_selDlg.ShowModal())
            {
                ManagedPGRGuid[] guids = m_selDlg.GetSelectedCameraGuids();

                // Determine camera interface
                var interfaceType = m_busmgr.GetInterfaceTypeFromGuid(guids[0]);

                if (interfaceType == InterfaceType.GigE)
                {
                    m_cam = new ManagedGigECamera();
                }
                else
                {
                    m_cam = new ManagedCamera();
                }

                // Connect to camera object
                m_cam.Connect(guids[0]);

                // Connect control dialog
                m_ctldlg.Connect(m_cam);

                // Start capturing
                m_cam.StartCapture();

                btn_nearfast.IsChecked = true;

                WorkerHelper helper = new WorkerHelper();
                helper.converted = m_converted;
                helper.raw       = m_image;
                helper.cam       = m_cam;
                m_continue       = true;
                m_worker.RunWorkerAsync(helper);
            }
            else
            {
                Application.Current.Shutdown();
            }
        }
Esempio n. 6
0
        public async Task Run()
        {
            await WorkerHelper.LoopUntilCanceled();

            Console.WriteLine("Canceling...");

            // Let the worker gracefully exit
            await Task.Delay(2000);
        }
Esempio n. 7
0
        public async Task should_set_item_with_bad_result()
        {
            var actual = await WorkerHelper.SendToWorkers("", "", new List <ServiceType>()
            {
                ServiceType.GeoIP
            });

            Assert.IsNotNull(actual.GeoIp.ErrorMessage);
            Assert.AreEqual(ServiceStatus.Error, actual.GeoIp.Status);
        }
        public async Task Main()
        {
            var clockReader = new Mock <IClockReader>();

            clockReader.Setup(cr => cr.Read()).Returns(12);
            var valueSender = new Mock <IValueSender>();

            valueSender.Setup(vs => vs.SendValue(It.IsAny <decimal>()));
            var helper = new WorkerHelper(clockReader.Object, valueSender.Object);
            var value  = helper.GetValue();

            Assert.Equal(12, value);
            await helper.PostValue(value);
        }
Esempio n. 9
0
        private static void SetupDebugLogging()
        {
            var logFilePath = Path.Combine(Path.GetDirectoryName(WorkerHelper.GetExecutingFile()), "logs",
                                           "log-imager.txt");

            Log.Logger = new LoggerConfiguration()
                         .Enrich.FromLogContext()
                         .MinimumLevel.Debug()
                         .MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
                         .WriteTo.File(
                logFilePath,
                rollingInterval: RollingInterval.Day,
                outputTemplate:
                "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] ({SourceContext}) {Message}{NewLine}{Exception}")
                         .CreateLogger();
        }
        public TemplateEditor(TemplateViewModel templateViewModel, FileHelper fileHelper, Form parentForm, WorkerHelper workerHelper)
        {
            this.templateViewModel = templateViewModel;
            this.fileHelper        = fileHelper;
            this.workerHelper      = workerHelper;

            InitializeComponent();

            templateViewModel.ButtonSaveT4 = buttonSaveT4;
            templateViewModel.ButtonSaveCs = buttonSaveCs;

            templateViewModel.CodeEditorT4              = new CodeEditor(parentForm);
            templateViewModel.CodeEditorT4.TextChanged += (o, args) => templateViewModel.T4Saved = false;
            templateViewModel.CodeEditorCs              = new CodeEditor(parentForm);
            templateViewModel.CodeEditorCs.TextChanged += (o, args) => templateViewModel.CsSaved = false;
        }
Esempio n. 11
0
        public void Execute(object parameter)
        {
            WorkerHelper workerHelper             = new WorkerHelper();
            var          name                     = WorkerViewModel.CurrentWorker.Name;
            var          surname                  = WorkerViewModel.CurrentWorker.Surname;
            var          isFilledRequestingPlaces = workerHelper.IsFilledRequestingPlaces(name, surname);

            if (!isFilledRequestingPlaces)
            {
                MessageBox.Show("You did not fill name and surname places");
            }
            else
            {
                if (WorkerViewModel.AllWorkers == null)
                {
                    WorkerViewModel.AllWorkers = new ObservableCollection <Worker>();
                }
                if (WorkerViewModel.AllWorkers.Count == 0)
                {
                    WorkerViewModel.CurrentWorker.Id = 0;
                    WorkerViewModel.CurrentWorker.No = 0;
                }
                else if (WorkerViewModel.AllWorkers.Count != 0)
                {
                    int index = WorkerViewModel.AllWorkers.Count - 1;
                    int newID = WorkerViewModel.AllWorkers[index].Id + 1;
                    WorkerViewModel.CurrentWorker.Id = newID;
                    WorkerViewModel.CurrentWorker.No = newID;
                }
                var item = WorkerViewModel.AllWorkers.FirstOrDefault(x => x.Id == WorkerViewModel.CurrentWorker.Id);

                if (item == null)
                {
                    var newitem = WorkerViewModel.CurrentWorker;
                    App.DB.WorkerRepository.AddData(newitem);
                    WorkerViewModel.AllWorkers = App.DB.WorkerRepository.GetAllData();
                    MessageBoxResult add = MessageBox.Show("Added");
                    WorkerViewModel.CurrentWorker  = new Worker();
                    WorkerViewModel.SelectedWorker = new Worker();
                }
                else
                {
                    MessageBoxResult add = MessageBox.Show("Can not add this item, you can only update and delete");
                }
            }
        }
Esempio n. 12
0
        public static bool Print(this PDFDocumentResult pdfDocumentResult)
        {
            if (pdfDocumentResult == null)
            {
                return(false);
            }
            if (!File.Exists(pdfDocumentResult.FilePath))
            {
                return(false);
            }
            if (!pdfDocumentResult.Success)
            {
                return(false);
            }

            var repository = ContainerBootstrapper.Resolve <ISettingsRepository <PrinterSettings> >();
            var settings   = repository.GetPrinterSettings();

            var parameters = new WorkerParameters();

            parameters.SetParameter("FilePath", pdfDocumentResult.FilePath);
            parameters.SetParameter("AlwaysAskForPrinter", settings.AlwaysAskForPrinter);
            parameters.SetParameter("DefaultPrinterName", settings.DefaultPrinterName);
            parameters.SetParameter("DefaultNumberOfCopies", pdfDocumentResult.Document != null ? settings.DefaultNumberOfCopies : 1);
            parameters.SetParameter("LabelNumberOfCopies", settings.LabelNumberOfCopies);
            parameters.SetParameter("AutoClosePDFProgram", settings.AutoClosePDFProgram);
            parameters.SetParameter("ShowCompanyNameOnLabels", settings.ShowCompanyNameOnLabels);
            parameters.SetParameter("Timeout", settings.Timeout);

            var workerTask = new WorkerTask
            {
                TaskName = WorkerTaskName.Print
            };

            workerTask.SetWorkerParameters(parameters);

            WorkerHelper.QueueTask(workerTask);

            return(true);
        }
Esempio n. 13
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSignalR(o =>
            {
                o.EnableDetailedErrors      = ApplicationDataHelper.HasDebugEnabled(Constants.AppName);
                o.MaximumReceiveMessageSize = 1024 * 1024;
            });

            services.AddControllersWithViews().AddJsonOptions(options =>
            {
                options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
            });

            // In production, the React files will be served from this directory
            services.AddSpaStaticFiles(configuration =>
            {
                configuration.RootPath = "ClientApp/build";
            });

            services.AddHostedService <QueuedHostedService>();
            services.AddSingleton <IBackgroundTaskQueue>(new BackgroundTaskQueue(100));

            services.AddHostedService <BackgroundTaskService>();
            services.AddSingleton <IActiveBackgroundTaskList>(new ActiveBackgroundTaskList());
            services.AddSingleton(new AppState
            {
                AppPath          = AppContext.BaseDirectory,
                ExecutingFile    = WorkerHelper.GetExecutingFile(),
                IsLicenseAgreed  = ApplicationDataHelper.IsLicenseAgreed(Constants.AppName),
                IsAdministrator  = OperatingSystem.IsAdministrator(),
                IsElectronActive = HybridSupport.IsElectronActive,
                UseFake          = Debugger.IsAttached,
                IsWindows        = OperatingSystem.IsWindows(),
                IsMacOs          = OperatingSystem.IsMacOs(),
                IsLinux          = OperatingSystem.IsLinux()
            });
            services.AddSingleton <PhysicalDriveManagerFactory>();
            services.AddSingleton <WorkerService>();
        }
Esempio n. 14
0
        private static bool InitialiseApplication()
        {
            AppDomain.CurrentDomain.SetData("DataDirectory", Environment.GetFolderPath(Environment.SpecialFolder.CommonDocuments));

            //Resource dictionaries must be set in code to avoid issues with older operating systems
            Current.Resources.MergedDictionaries.Add(new ResourceDictionary {
                Source = new Uri("Resources/MainResourceDictionary.xaml", UriKind.Relative)
            });
            Current.Resources.MergedDictionaries.Add(new ResourceDictionary {
                Source = new Uri("pack://application:,,,/Fluent;Component/Themes/Generic.xaml")
            });

            MigrationHelper.MoveDatabaseIfRequired();
            MigrationHelper.HackMigrationHistoryTable();

            //Prepare database
            Database.SetInitializer(new MigrateDatabaseToLatestVersion <TachographContext, Configuration>());

            MigrationHelper.MigrateWorkshopImages();

            TachographContext context = new TachographContext();

            context.Database.CreateIfNotExists();

            //Make database accessible to all users
            MigrationHelper.SetDatabasePermissions();

            //Seed database
            MigrationHelper.ApplyDataHacks();

            //Launch Webcal Protocol
            RegistryHelper.RegisterProtocol();

            //Initialise worker queue, which will start checking for unprocessed tasks
            WorkerHelper.Initialize();

            return(true);
        }
Esempio n. 15
0
 void Awake()
 {
     DontDestroyOnLoad(gameObject);
     instance = this;
 }