protected TaskCommandResult RunProcess(string workingDirectory, string executable, string processArguments)
        {
            log.Trace("Running process{0}: {1} {2}", shouldImpersonate ? " (as warden user)" : String.Empty,  executable, processArguments);

            using (var process = new BackgroundProcess(workingDirectory, executable, processArguments, GetImpersonatationCredential()))
            {
                process.ErrorDataReceived += process_ErrorDataReceived;
                process.OutputDataReceived += process_OutputDataReceived;

                Action<Process> postStartAction = (Process p) =>
                    {
                        log.Trace("Process ID: '{0}'", p.Id);
                        container.AddProcess(p, rlimits);
                    };
                process.StartAndWait(asyncOutput: true, postStartAction: postStartAction);

                process.ErrorDataReceived -= process_ErrorDataReceived;
                process.OutputDataReceived -= process_OutputDataReceived;

                string sout = stdout.ToString();
                string serr = stderr.ToString();

                log.Trace("Process ended with exit code: {0}", process.ExitCode);

                return new TaskCommandResult(process.ExitCode, sout, serr);
            }
        }
        protected TaskCommandResult RunProcess(string workingDirectory, string executable, string processArguments)
        {
            log.Trace("Running process{0}: {1} {2}", shouldImpersonate ? " (as warden user)" : String.Empty, executable, processArguments);

            using (var process = new BackgroundProcess(workingDirectory, executable, processArguments, GetImpersonatationCredential()))
            {
                process.ErrorDataReceived  += process_ErrorDataReceived;
                process.OutputDataReceived += process_OutputDataReceived;

                Action <Process> postStartAction = (Process p) =>
                {
                    log.Trace("Process ID: '{0}'", p.Id);
                    container.AddProcess(p, rlimits);
                };
                process.StartAndWait(asyncOutput: true, postStartAction: postStartAction);

                process.ErrorDataReceived  -= process_ErrorDataReceived;
                process.OutputDataReceived -= process_OutputDataReceived;

                string sout = stdout.ToString();
                string serr = stderr.ToString();

                log.Trace("Process ended with exit code: {0}", process.ExitCode);

                return(new TaskCommandResult(process.ExitCode, sout, serr));
            }
        }
        public void BackgroundProcess_Dispose()
        {
            var storage = new Mock <IStorage>();
            var process = new BackgroundProcess(() => { }, 1000);

            Assert.DoesNotThrow(() => process.Dispose());
        }
        public void Configuration(IAppBuilder app)
        {
            ConfigureAuth(app);
            GlobalHost.HubPipeline.AddModule(new HubPipelineHelper());
            // Branch the pipeline here for requests that start with "/signalr"
            app.Map("/signalr", map =>
            {
                // Setup the CORS middleware to run before SignalR.
                // By default this will allow all origins. You can
                // configure the set of origins and/or http verbs by
                // providing a cors options with a different policy.
                map.UseCors(CorsOptions.AllowAll);
                var hubConfiguration = new HubConfiguration
                {
                    // You can enable JSONP by uncommenting line below.
                    // JSONP requests are insecure but some older browsers (and some
                    // versions of IE) require JSONP to work cross domain
                    //EnableJSONP = true
                };
                // Run the SignalR pipeline. We're not using MapSignalR
                // since this branch already runs under the "/signalr"
                // path.
                map.RunSignalR(hubConfiguration);
            });

            //app.UseCors(CorsOptions.AllowAll);
            //app.MapSignalR();
            _backgroundProcess = new BackgroundProcess();
        }
Example #5
0
        static void Main(string[] args)
        {
            bool showRegexInfo = bool.Parse(ConfigurationManager.AppSettings["showRegexInfo"]);
            //string folderPath = ConfigurationManager.AppSettings["codeFolder"];
            //string filePattern = ConfigurationManager.AppSettings["fileSearchPattern"];

            string folderPath  = Path.Combine(new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory).Parent.Parent.Parent.FullName, "EncodingTestFiles");
            string filePattern = @"*.txt";

            //Directory.GetFiles(folderPath, "*.cs*").ToList().ForEach((f) => {
            //    var fi = new FileInfo(f);
            //    fi.MoveTo(fi.FullName+".txt");
            //});

            Dictionary <string, string> dictRegex = new Dictionary <string, string>()
            {
                { @"(\()[Ss]tring(\s+?str\))", "$1Int32$2" },
            };

            if (showRegexInfo)
            {
                //显示基本信息
                OutputRegexInfo(dictRegex, folderPath, filePattern);
            }

            //处理文本替换
            BackgroundProcess <ReplaceTaskItem> util = new BackgroundProcess <ReplaceTaskItem>();

            util.TasksFactory       = new ReplaceTaskItemFactory(folderPath, filePattern, dictRegex);
            util.OnProgressChanged += (progress, sn, taskItem) =>
            {
                Console.WriteLine("第{0}个", sn);
                Console.WriteLine("进度:{0:F2}%", progress * 100);
                Console.WriteLine("文件名:{0}", new FileInfo(taskItem.FilePath).Name);
                Console.WriteLine();
            };
            util.Start();

            Console.ReadKey();
        }
Example #6
0
        private void BW_DoWork(object sender, DoWorkEventArgs e)
        {
            //Check the database connection
            valiballecommon valiballecommon = valiballecommon.GetStorage();

            Properties.Settings setting = Properties.Settings.Default;
            string concheck             = "Data Source = " + valiballecommon.DatabaseName + "; Initial Catalog= GymManagement;  Integrated Security=True";

            SqlConnection con = new SqlConnection(concheck);

            try
            {
                con.Open();
                con.Close();
            }catch (Exception ex)
            {
                throw ex;
            }
            //Delete old member
            BackgroundProcess backgroundProcess = new BackgroundProcess();

            backgroundProcess.MakememberInactive();
            backgroundProcess.Deleteinactive();
        }
Example #7
0
        public async Task Initialize(Dispatcher dispatcher)
        {
            // read the settings from storage
            Settings.CopyFrom(await Storage.LoadSettings());
            if (Settings.SystemIdentifier == Guid.Empty)
            {
                // this only occurs when the system hasn't had one allocated
                // so we can create a new one, then save the settings.
                // (this will force an empty setting file with the System Identifier if needed)
                Settings.AllocateNewSystemIdentifier();
                await Storage.SaveSettings(Settings);
            }

            // read the room mappings from storage
            RoomMappings.Clear();
            foreach (var map in await Storage.LoadRoomMappings())
            {
                RoomMappings.Add(map);
            }

            Templates.Clear();
            foreach (var template in await Storage.LoadTemplates())
            {
                Templates.Add(template);
            }
            AddMissingTemplates();

            // reload any unmatched messages
            var messages = await Storage.LoadUnprocessableMessages(DisplayingDate);

            foreach (var item in messages)
            {
                UnprocessableMessages.Add(item);
            }

            PmsSimulator.Initialize(Storage);
            if (!IsSimulation)
            {
                FhirApptReader = new FhirAppointmentReader(FhirAppointmentReader.GetServerConnection);
                SmsProcessor.Initialize(Settings);
            }
            logger.Log(1, "Start up");
            if (!String.IsNullOrEmpty(Settings.AdministratorPhone))
            {
                logger.Log(1, "Send SMS to " + Settings.AdministratorPhone);
                try
                {
                    SmsProcessor.SendMessage(new SmsMessage(Settings.AdministratorPhone, "System is starting"));
                    if (!IsSimulation)
                    {
                        App.AdministratorPhone = Settings.AdministratorPhone;
                        App.SmsSender          = SmsProcessor;
                    }
                }
                catch (Exception ex)
                {
                    System.Windows.MessageBox.Show("Error sending message: " + ex.Message);
                }
            }

            // setup the background worker routines
            ReadSmsMessage = new BackgroundProcess(Settings, serverStatuses.IncomingSmsReader, dispatcher, async() =>
            {
                // Logic to run on this process
                // (called every settings.interval)
                StatusBarMessage            = $"Last read SMS messages at {DateTime.Now.ToLongTimeString()}";
                var engine                  = PrepareMessagingEngine();
                List <PmsAppointment> appts = new List <PmsAppointment>();
                appts.AddRange(Appointments);
                var messagesReceived = await engine.SmsSender.ReceiveMessages();
                serverStatuses.IncomingSmsReader.Use(messagesReceived.Count());
                engine.ProcessIncomingMessages(appts, messagesReceived);
            });

            ScanAppointments = new BackgroundProcess(Settings, serverStatuses.AppointmentScanner, dispatcher, async() =>
            {
                // Logic to run on this process
                // (called every settings.interval)
                var engine = PrepareMessagingEngine();
                List <PmsAppointment> appts = await FhirApptReader.SearchAppointments(this.DisplayingDate, RoomMappings, Storage);
                serverStatuses.Oridashi.Use(1);
                serverStatuses.AppointmentScanner.Use(engine.ProcessTodaysAppointments(appts));

                // Now update the UI once we've processed it all
                Expecting.Clear();
                Waiting.Clear();
                Appointments.Clear();
                foreach (var appt in appts)
                {
                    Appointments.Add(appt);
                    if (appt.ArrivalStatus == Hl7.Fhir.Model.Appointment.AppointmentStatus.Booked)
                    {
                        Expecting.Add(appt);
                    }
                    else if (appt.ArrivalStatus == Hl7.Fhir.Model.Appointment.AppointmentStatus.Arrived)
                    {
                        Waiting.Add(appt);
                    }
                }
            });

            ProcessUpcomingAppointments = new BackgroundProcess(Settings, serverStatuses.UpcomingAppointmentProcessor, dispatcher, async() =>
            {
                // Logic to run on this process
                // (called every settings.intervalUpcoming)
                var engine = PrepareMessagingEngine();
                List <PmsAppointment> appts = new List <PmsAppointment>();
                appts.AddRange(await FhirApptReader.SearchAppointments(this.DisplayingDate.AddDays(1), RoomMappings, Storage));
                appts.AddRange(await FhirApptReader.SearchAppointments(this.DisplayingDate.AddDays(2), RoomMappings, Storage));
                serverStatuses.Oridashi.Use(1);
                serverStatuses.UpcomingAppointmentProcessor.Use(engine.ProcessUpcomingAppointments(appts));
            }, true);
        }
Example #8
0
        public override void Start()
        {
            try
            {
                if (File.Exists(this.OutputFile))
                {
                    File.Delete(this.OutputFile);
                }
            }
            catch (Exception ex)
            {
                this.ExecutionState = ExecutionState.Failed;
                this.OnErrorOccurred(new InvalidOperationException(
                                         $"Output file <code>{this.OutputFile}</code> already exists and cannot be deleted. {ex.Message}"));
                return;
            }

            Match cmdParts = Regex.Match(this.TranscodingCommand, @"(\S+)\s+(.*)");

            if (cmdParts.Groups.Count != 3)
            {
                this.ExecutionState = ExecutionState.Failed;
                this.OnErrorOccurred(new InvalidOperationException(
                                         $"Invalid transcoding command: <code>{this.TranscodingCommand}</code>"));
                return;
            }

            string cmd       = cmdParts.Groups[1].Value;
            string cmdParams = cmdParts.Groups[2].Value;

            string cmdExecutable = FindExecutableInSystemPath(cmd);

            if (cmdExecutable == null)
            {
                this.ExecutionState = ExecutionState.Failed;
                this.OnErrorOccurred(new InvalidOperationException(
                                         $"Cannot find executable <code>{cmd}</code> in the system PATH. Make sure it is properly installed and configured."));
                return;
            }

            this.transcodeProcess = new BackgroundProcess
            {
                StartInfo =
                {
                    FileName               = cmdExecutable,
                    Arguments              = cmdParams,
                    UseShellExecute        = true,
                    CreateNoWindow         = false,
                    RedirectStandardOutput = false,
                    RedirectStandardError  = false,
                    WindowStyle            = ProcessWindowStyle.Minimized
                }
            };
            this.transcodeProcess.OutputDataReceived += TranscodeProcess_OutputDataReceived;
            this.transcodeProcess.ErrorDataReceived  += TranscodeProcess_ErrorDataReceived;
            this.AppendToLog($"{this.Description} started. Executing command:");
            this.AppendToLog($"{cmdExecutable} {cmdParams}");
            try
            {
                this.transcodeProcess.StartMinimizedNoFocus();
                this.ExecutionState = ExecutionState.Running;
            }
            catch (Exception ex)
            {
                this.ExecutionState = ExecutionState.Failed;
                this.OnErrorOccurred(ex);
            }
        }