public void AbortJobBatch(JJobType jobType, int pauseBeforeAbort = 1000)
 {
     try
     {
         if (jobType.JobBatchObject != null)
         {
             CancelAsyncJobBatch(jobType);
             Thread.Sleep(pauseBeforeAbort);
             //
             List <JRunningJob> jobs = new List <JRunningJob>();
             jobs.AddRange(jobType.JobBatchRunningDict.Values);//copy for prevent deadlock
             foreach (var job in jobs)
             {
                 AbortJob(job);
             }
             //
             if (jobType.JobBatchObject is AbortableBackgroundWorker)
             {
                 AbortableBackgroundWorker backgroundWorker1 = (jobType.JobBatchObject as AbortableBackgroundWorker);
                 if (backgroundWorker1.IsBusy == true)
                 {
                     backgroundWorker1.Abort();
                     backgroundWorker1.Dispose();
                 }
             }
             ResetJobBatch(jobType);
             JobManager.Instance.ComplateJobBatch(jobType, RunningJobStageEnum.aborted);
         }
     }
     catch (Exception ex)
     {
         Log.LogError("Error aborting job: " + jobType.JJobTypeId, ex);
     }
 }
        public void MakeContextMenu(IListProcessor list, List <ToolStripItem> menuItemList, object selectedListItem, object selectedObject, string aspectName)
        {
            menuItemList.Add(new ToolStripSeparator());
            JJobType job = (JJobType)selectedObject;

            if (job != null)
            {
                JobManager.MakeContextMenuForRunningJobBatch(job, menuItemList, list.ContentContainer);
            }
        }
Example #3
0
        override protected void MakeContextMenu(List <ToolStripItem> menuItemList, object selectedListItem, object selectedObject, string aspectName)
        {
            base.MakeContextMenu(menuItemList, selectedListItem, selectedObject, aspectName);
            menuItemList.Add(new ToolStripSeparator());
            JJobType job = (JJobType)selectedObject;

            if (job != null)
            {
                JobManager.MakeContextMenuForRunningJobBatch(job, menuItemList, this.ContentContainer);
            }
        }
 public void CancelAsyncJobBatch(JJobType jobType)
 {
     try
     {
         if (jobType.JobBatchObject != null && jobType.JobBatchObject is BackgroundWorker)
         {
             (jobType.JobBatchObject as BackgroundWorker).CancelAsync();
         }
         jobType.JobBatchCancellationPending = true;
     }
     catch (Exception ex)
     {
         Log.LogError("Error CancelAsync job: " + jobType.JJobTypeId, ex);
     }
 }
 private static void localReportProgresJobType(JJobType jobType, int progressPercentage)
 {
     try
     {
         if (jobType.JobBatchProgress != progressPercentage)
         {
             jobType.JobBatchLog.Debug("Out Progress jobType " + jobType.JJobTypeId + " Progress: " + progressPercentage.ToString() + "%");
             jobType.JobBatchProgress = progressPercentage;
             Dm.Instance.SaveObject(jobType);
         }
     }
     catch (Exception ex)
     {
         Log.LogError("Error reporting progress jobType: " + jobType.JJobTypeId, ex);
     }
 }
        public static void MakeTitleContextMenuForRunningJobTypeQueue(JJobType jobType, List <ToolStripItem> menuItemList, IContentContainer docPanelContainer)
        {
            ToolStripMenuItem menuItem = null;

            if (jobType != null)
            {
                List <ToolStripItem> menuItemList1 = new List <ToolStripItem>();
                MakeContextMenuForRunningJobBatch(jobType, menuItemList1, docPanelContainer);
                if (menuItemList1.Count > 0)
                {
                    menuItem      = new ToolStripMenuItem();
                    menuItem.Text = FrwCRUDRes.Job_batch__ + jobType.Name + "\"";// + " (" + job.Stage + ")";
                    menuItemList.Add(menuItem);
                    menuItem.DropDownItems.AddRange(menuItemList1.ToArray <ToolStripItem>());
                }
            }
        }
 public void ComplateJobBatch(JJobType jobType, RunningJobStageEnum stage = RunningJobStageEnum.complated)
 {
     try
     {
         jobType.JobBatchLog.Info("JobBatch complate with result: " + stage);
         jobType.JobBatchStage = stage.ToString();
         if (jobType.JobBatchProgress == 0)
         {
             jobType.JobBatchProgress = 100;
         }
         Dm.Instance.SaveObject(jobType);
         //save log to file
         jobType.JobBatchLog.SaveLogToFile();
     }
     catch (Exception ex)
     {
         Log.LogError("Error complating job: " + jobType.JJobTypeId, ex);
     }
 }
        public override void SetKeyParams(IDictionary <string, object> pars)
        {
            if (pars == null)
            {
                return;
            }

            object t = DictHelper.Get(pars, "JobType");

            if (t != null && t is JJobType)
            {
                JobType = t as JJobType;
            }
            else if (t != null && t is string)
            {
                JobType = Dm.Instance.Find <JJobType>(t as string);
                //todo load log
            }
            else if (t != null)
            {
                throw new ArgumentException();
            }
        }
 private bool compareJobTypeKey(object key, JJobType item)
 {
     //если ключ не задан сравнение по нему не производится
     if (key != null)
     {
         if (key is JJobType)
         {
             return(((JJobType)key).Equals(item));
         }
         if (key is string)
         {
             return((item != null) ? ((string)key).Equals(JobType.JJobTypeId) : false);
         }
         else
         {
             throw new ArgumentException();
         }
     }
     else
     {
         return(true);
     }
 }
        public void AbortAllJobsAndJobBatches()
        {
            IList jobTypes = Dm.Instance.FindAll(typeof(JJobType));

            foreach (var j in jobTypes)
            {
                JJobType jobType = j as JJobType;
                if (jobType.IsJobBatchWorking())
                {
                    AbortJobBatch(jobType);
                }
            }

            IList jobs = Dm.Instance.FindAll(typeof(JRunningJob));

            foreach (var j in jobs)
            {
                JRunningJob job = j as JRunningJob;
                if (job.IsWorking())
                {
                    AbortJob(job);
                }
            }
        }
        public static void MakeContextMenuForRunningJobBatch(JJobType jobType, List <ToolStripItem> menuItemList, IContentContainer docPanelContainer)
        {
            ToolStripMenuItem menuItem = null;

            if (jobType != null)
            {
                if (RunningJobStageEnum.running.ToString().Equals(jobType.JobBatchStage) && jobType.JobBatchObject != null)
                {
                    menuItem        = new ToolStripMenuItem();
                    menuItem.Text   = FrwCRUDRes.Try_to_cancel_job_batch;
                    menuItem.Click += (s, em) =>
                    {
                        try
                        {
                            JobManager.Instance.CancelAsyncJobBatch(jobType);
                        }
                        catch (Exception ex)
                        {
                            Log.ShowError(ex);
                        }
                    };
                    menuItemList.Add(menuItem);

                    menuItem        = new ToolStripMenuItem();
                    menuItem.Text   = FrwCRUDRes.Kill_job_batch_thread;
                    menuItem.Click += (s, em) =>
                    {
                        try
                        {
                            JobManager.Instance.AbortJobBatch(jobType);
                        }
                        catch (Exception ex)
                        {
                            Log.ShowError(ex);
                        }
                    };
                    menuItemList.Add(menuItem);
                }

                string   logFileName = JobManager.Instance.GetJobTypeLogFileName(jobType);
                FileInfo logFile     = new FileInfo(logFileName);
                if (jobType.JobBatchLog != null || logFile.Exists)
                {
                    menuItem        = new ToolStripMenuItem();
                    menuItem.Text   = FrwCRUDRes.Show_job_batch_console;
                    menuItem.Click += (s, em) =>
                    {
                        try
                        {
                            JobTypeConsoleWindow consoleWindow = (JobTypeConsoleWindow)AppManager.Instance.CreateContent(docPanelContainer, typeof(JobTypeConsoleWindow),
                                                                                                                         new Dictionary <string, object> {
                                { "JobType", jobType }
                            });
                            if (consoleWindow != null)
                            {
                                if (jobType.JobBatchLog != null)
                                {
                                    jobType.JobBatchLog.ExternalWriter = consoleWindow.ConsoleWriter;
                                }
                                else if (logFile.Exists)
                                {
                                    consoleWindow.ConsoleWriter.Write(File.ReadAllText(logFile.FullName));
                                }
                                consoleWindow.ProcessView();
                            }
                        }
                        catch (Exception ex)
                        {
                            Log.ShowError(ex);
                        }
                    };
                    menuItemList.Add(menuItem);
                }
            }
        }
        /// <summary>
        /// Creates new job and job type (if needs)
        /// </summary>
        /// <param name="jjobTypeId"></param>
        /// <param name="jobTypeName"></param>
        /// <param name="additionalJobName"></param>
        /// <param name="concurType"></param>
        /// <returns></returns>
        public JRunningJob CreateJob(string jjobTypeId, string jobTypeName, string additionalJobName, JobConcurrentTypeEnum concurType = JobConcurrentTypeEnum.Wait)
        {
            DateTime time = DateTime.Now;

            if (jjobTypeId == null)
            {
                throw new ArgumentException();
            }
            JJobType jobType = (JJobType)Dm.Instance.Find(typeof(JJobType), jjobTypeId);
            bool     created = false;

            if (jobType == null)
            {
                jobType                = (JJobType)Dm.Instance.EmptyObject(typeof(JJobType), null);
                jobType.JJobTypeId     = jjobTypeId;
                jobType.ConcurrentType = concurType.ToString();
                if (JobConcurrentTypeEnum.Allow.ToString().Equals(jobType.ConcurrentType))
                {
                    jobType.MaxThreadCount = JJobType.DEFAULT_MAX_THREAD_COUNT;
                }
                if (jobTypeName != null)
                {
                    jobType.Name = jobTypeName;
                }
                else
                {
                    jobType.Name = jjobTypeId;
                }
                Dm.Instance.SaveObject(jobType);
                created = true;
            }
            if (jobType.JobBatchLog == null)
            {
                jobType.JobBatchLog             = new JobLog();
                jobType.JobBatchLog.LogFileName = GetJobTypeLogFileName(jobType);
                JobTypeConsoleWindow consoleWindow = (JobTypeConsoleWindow)AppManager.Instance.FindContent(typeof(JobTypeConsoleWindow), null, new Dictionary <string, object> {
                    { "JobType", jobType }
                });
                if (consoleWindow != null)
                {
                    if (jobType.JobBatchLog != null)
                    {
                        jobType.JobBatchLog.ExternalWriter = consoleWindow.ConsoleWriter;
                    }
                }
            }
            if (created)
            {
                jobType.JobBatchLog.Debug("Job type" + jobType.JJobTypeId + " created new");
            }
            else
            {
                jobType.JobBatchLog.Debug("Job type" + jobType.JJobTypeId + " found");
            }

            JRunningJob job = null;

            job       = (JRunningJob)Dm.Instance.EmptyObject(typeof(JRunningJob), null);
            job.Stage = RunningJobStageEnum.initial.ToString();

            job.CreateDate = time;
            if (additionalJobName != null)
            {
                job.Name = (jobType.Name) + " " + additionalJobName;
            }
            else
            {
                job.Name = (jobType.Name) + " " + time.ToString("yyyy/MM/dd HH:mm:ss");
            };
            job.JJobType           = jobType;
            job.JobLog             = new JobLog();
            job.JobLog.ParentLog   = jobType.JobBatchLog;//paren ref
            job.JobLog.LogFileName = GetJobLogFileName(job);
            Dm.Instance.SaveObject(job);
            job.JobLog.Debug("Job " + job.JRunningJobId + " created");
            return(job);
        }
 static public void ResetJobBatch(JJobType jobType)
 {
     //reset
     jobType.JobBatchObject         = null;
     jobType.JobBatchQueueSemaphore = null;
 }
        static public void StartProcessingJobBatch(JJobType jobType)
        {
            if (jobType.JobBatchObject != null)
            {
                throw new InvalidOperationException();                                //todo
            }
            BackgroundWorker mainWorker = new AbortableBackgroundWorker();

            mainWorker.WorkerSupportsCancellation = true;
            mainWorker.WorkerReportsProgress      = true;
            mainWorker.DoWork += (sd, ew) =>
            {
                BackgroundWorker wk = sd as BackgroundWorker;
                if (wk.CancellationPending)
                {
                    ew.Cancel = true;
                    return;
                }
                try
                {
                    if (jobType.JobBatchQueueSemaphore == null)
                    {
                        //first start
                        int maxTreadCount = 1;
                        if (JobConcurrentTypeEnum.Cancel.ToString().Equals(jobType.ConcurrentType))
                        {
                            maxTreadCount = 1;
                        }
                        else if (JobConcurrentTypeEnum.Wait.ToString().Equals(jobType.ConcurrentType))
                        {
                            maxTreadCount = 1;
                        }
                        else if (JobConcurrentTypeEnum.Allow.ToString().Equals(jobType.ConcurrentType))
                        {
                            maxTreadCount = jobType.MaxThreadCount;
                        }

                        jobType.JobBatchRunningDict.Clear();
                        jobType.JobBatchQueueSemaphore = new Semaphore(maxTreadCount, maxTreadCount);
                        jobType.JobBatchLog.Debug("JobType Semaphore created maxTreadCount: " + maxTreadCount);

                        jobType.JobBatchLastRunDate = DateTime.Now;
                        jobType.JobBatchStage       = RunningJobStageEnum.running.ToString();
                        Dm.Instance.SaveObject(jobType);
                    }

                    List <AutoResetEvent> endHandlers = new List <AutoResetEvent>();
                    int initialQueueCount             = jobType.JobBatchQueueCount;
                    int startedCount = 0;
                    while (true)
                    {
                        if (wk.CancellationPending)
                        {
                            ew.Cancel = true;
                            break;
                        }
                        if (jobType.JobBatchQueueCount == 0)
                        {
                            break;
                        }

                        jobType.JobBatchQueueSemaphore.WaitOne();

                        JRunningJob job = jobType.DequeueJob();
                        job.QueueSemaphore = jobType.JobBatchQueueSemaphore;
                        job.EndHandle      = new AutoResetEvent(false);
                        endHandlers.Add(job.EndHandle);

                        ScheduleJobBackgroundLocal(job);

                        startedCount++;
                        int progress = (int)(((double)startedCount / (double)initialQueueCount) * 100.0);
                        wk.ReportProgress(progress);
                    }
                    if (endHandlers.Count > 0)
                    {
                        WaitHandle.WaitAll(endHandlers.ToArray <AutoResetEvent>());
                    }

                    PostLastJobRunEventArgs arg1 = new PostLastJobRunEventArgs();
                    arg1.Canceled = ew.Cancel;
                    jobType.DoPostLJobBatch(arg1);
                    if (ew.Cancel == false)
                    {
                        ew.Result = RunningJobStageEnum.complated;
                    }
                }
                catch (Exception ex)
                {
                    jobType.JobBatchLog.Error("Job Batch fatal error", ex);
                    ew.Result = RunningJobStageEnum.exception;
                    JobManager.Instance.ComplateJobBatch(jobType, RunningJobStageEnum.exception);
                }
            };
            mainWorker.RunWorkerCompleted += (sd, ek) =>
            {
                ResetJobBatch(jobType);
                if (ek.Cancelled == true)
                {
                    JobManager.Instance.ComplateJobBatch(jobType, RunningJobStageEnum.aborted);
                }
                else
                {
                    if (RunningJobStageEnum.exception.Equals(ek.Result))
                    {
                        //do nothing
                    }
                    else if (RunningJobStageEnum.warning.Equals(ek.Result))
                    {
                        JobManager.Instance.ComplateJobBatch(jobType, RunningJobStageEnum.warning);
                    }
                    else if (RunningJobStageEnum.error.Equals(ek.Result))
                    {
                        JobManager.Instance.ComplateJobBatch(jobType, RunningJobStageEnum.error);
                    }
                    else
                    {
                        JobManager.Instance.ComplateJobBatch(jobType, RunningJobStageEnum.complated);
                    }
                }
            };
            mainWorker.ProgressChanged += (sd, pc) =>
            {
                localReportProgresJobType(jobType, pc.ProgressPercentage);
            };
            //run worker
            jobType.JobBatchObject = mainWorker;
            mainWorker.RunWorkerAsync();
        }
 public string GetJobTypeLogFileName(JJobType jobType)
 {
     return(Path.Combine(FrwConfig.Instance.ProfileDir, Path.Combine("jobLogs", Path.Combine(jobType.JJobTypeId, "jobTypeLog"))));
 }