Пример #1
0
 public SystemsDispatcher(SystemNode[] nodes)
 {
     _nodes    = nodes;
     _progress = new JobProgress((uint)nodes.Length);
     _status   = new NodeStatus[nodes.Length];
     _handles  = new Handle <WorkerPool> [nodes.Length];
 }
Пример #2
0
        private void CalculateProgressBeforeRead()
        {
            var start            = Progress?.NextIterationStart ?? _context.StartInstant;
            var endCutoffInstant = InstantUtils.SecondsAgo(_context.ClockSkewProtectionSeconds);
            var minEndInstant    = start.Plus(Duration.FromSeconds(_context.MinIntervalSeconds));
            var maxEndInstant    = start.Plus(Duration.FromSeconds(_context.MaxIntervalSeconds));

            var end = Progress?.NextIterationEnd ?? maxEndInstant;

            if (end > maxEndInstant)
            {
                end = maxEndInstant;
            }
            if (end > endCutoffInstant)
            {
                end = endCutoffInstant;
            }
            if (end < minEndInstant)
            {
                end = minEndInstant;
            }

            // Fix the iteration based on _context.End only if the _context.End is between progress start and end
            // (so that the iteration needs to be run partially). We don't need to consider any other cases, if
            // the Progress.end is passed _context.end, we won't run the iteration anyway.
            if (_context.EndInstant.HasValue &&
                start < _context.EndInstant.Value &&
                end > _context.EndInstant.Value)
            {
                end = _context.EndInstant.Value;
            }

            Progress = new JobProgress(start, end, Progress?.NextToken);
        }
Пример #3
0
        public Main()
        {
            InitializeComponent();
            // Radi pretplatu na event, event vraca ukupan broj zapisa za sve tipove LogType, npr. koliko ERRORA je zabiljezeno
            Log.OnLogTypeNumberChange += new Log.delLogTypeInfo(Log_OnLogTypeNumberChange);
            // Zapisuje osnovne podatke o aplikaciji
            Log.StandardRunInfo();
            Log.Write(Static.conConnectionString, this, "Main", Log.LogType.INFO);

            // make instance of ToolsWindowsMenager
            toolsWindowsMenager = new ToolsWindowsMenager();
            toolsWindowsMenager.AddPanel(pToolsWindowsHolder);

            // stara progerss classa
            JobProgress isStatus = new JobProgress(this);

            isStatus.StatusChange += new JobProgress.delStatusChange(isStatus_StatusChange);

            JobProgress jobProgress = new JobProgress(this);


            // Novi module menager, sadrzi listu svijh UberTools modula
            moduleManager = new ModuleManager();
            moduleManager.OnActivateModule += new ModuleManager.delModuleObject(moduleMenager_OnActivateModule);

            // Ucitaj sve module u ModuleMenager, i pokazi ih na ToolStripMenu listi
            GetPluginsList(Application.StartupPath + "\\plugins");



            //GetAssemblies();
            //AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
            //Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException);
            //throw new Exception("Kita");
        }
        public async Task <int> SetJobProgressAsync(Guid jobId, JobProgress jobProgress)
        {
            var connectionString = configuration.GetConnectionString("DefaultConnection");

            await using var connection = new SqlConnection(connectionString);
            var progressToSet = Math.Max(jobProgress.Progress, 0.05);

            await using var command = new SqlCommand(@"                
                INSERT INTO JobProgress (JobId, Progress, DateLastUpdated, Status, Message)
                SELECT @JobId, @Progress, GETDATE(), @Status, @Message
                WHERE NOT EXISTS (SELECT * FROM JobProgress WHERE JobId = @JobId)
                DECLARE @rowsInserted int = @@ROWCOUNT

                UPDATE JobProgress SET Progress = @Progress, DateLastUpdated = GETDATE(), Status = @Status, Message = @Message
                WHERE JobId = @JobId
                
                SELECT @rowsInserted",
                                                     connection);
            command.Parameters.AddWithValue("@JobId", jobId);
            command.Parameters.AddWithValue("@Progress", progressToSet);
            command.Parameters.AddWithValue("@Status", jobProgress.Status.ToString());
            command.Parameters.AddWithValue("@Message", jobProgress.Message);
            await connection.OpenAsync();

            var rowsInserted = await command.ExecuteScalarAsync();

            return(Convert.ToInt32(rowsInserted));
        }
Пример #5
0
        private void Main()
        {
            while (true)
            {
                try
                {
                    Thread.Sleep(WAITER_INTERVAL);
                }
                catch (ThreadInterruptedException e)
                {
                    Console.WriteLine(nameof(StatsDisplayer) + " stopped");
                    return;
                }

                var activeJobs = Directory.GetFiles(Program.ACTIVE_JOBS_PATH, "*" + Program.JOB_EXT);

                if (activeJobs.Length > 0)
                {
                    if (activeJobs.Length > 1)
                    {
                        //TODO: handling in case of failure
                        Logger.LogDebug("Something strange! More than one active job");
                    }

                    var job = JsonConvert.DeserializeObject <Job>(File.ReadAllText(activeJobs[0]));
                    Logger.LogStatsActiveJob(job);
                    var activeJobProgressPath = activeJobs[0] + ".progress";
                    if (File.Exists(activeJobProgressPath)) //TODO: redo, move ext to program class
                    {
                        try
                        {
                            JobProgress progress =
                                JsonConvert.DeserializeObject <JobProgress>(File.ReadAllText(activeJobProgressPath));
                            Logger.LogStatsActiveProgress(progress);
                        }
                        catch (Exception e)
                        {
                            //failed to read info about progress
                            Logger.LogDebug("Failed to read progress info");
                        }
                    }
                    //nothing to display
                    continue;
                }

                var pendingCount = Directory.GetFiles(Program.PENDING_JOBS_PATH, "*" + Program.JOB_EXT).Length;
                if (pendingCount > 0)
                {
                    Logger.LogStatsPendingJobs(pendingCount);
                }
                var pendingJobs = Directory.GetFiles(Program.PENDING_JOBS_PATH, "*" + Program.JOB_EXT);
            }
        }
 /// <summary>
 /// GET api/jobprogress/id. Returns a JSON response indicating the job's progress.
 /// </summary>
 /// <param name="id">Job ID</param>
 /// <returns>JSON JobProgress response</returns>
 public JobProgress Get(int id)
 {
     if (ProcessManager.JobCached(id))
     {
         StoredJob job = ProcessManager.GetJob(id);
         return(JobProgress.CreateFromStored(job));
     }
     else
     {
         return(JobProgress.CreateFailResponse("Job not found"));
     }
 }
Пример #7
0
 private async Task SendLogProgressToFront(double progress, DateTime?EndTimeUtc = null)
 {
     var info = new JobProgress
     {
         Id = Id,
         CurrentProgressPercentage = progress,
         State        = State,
         StartTimeUtc = StartTimeUtc ?? DateTime.UtcNow,
         EndTimeUtc   = EndTimeUtc,
         Title        = Title
     };
     await HubHelper.BroadcastJobProgress(info);
 }
Пример #8
0
 void child_Status(object text)
 {
     // TODO: neki kurac sam ovdje pijan radio
     if (text != null)
     {
         tssStatus.Text = (string)text;
         Application.DoEvents();
         JobProgress.Write((string)text);
     }
     else
     {
         JobProgress.Ready();
     }
 }
Пример #9
0
 public void RemoveJob(string jobName)
 {
     try
     {
         JobProgress jp = this.Jobs.GetByName(jobName);
         if (jp != null)
         {
             this.Jobs.Remove(jp);
         }
     }
     catch (Exception ex)
     {
     }
 }
Пример #10
0
 public void RemoveJob(int jobId)
 {
     try
     {
         JobProgress jp = this.Jobs.GetById(jobId);
         if (jp != null)
         {
             this.Jobs.Remove(jp);
         }
     }
     catch (Exception ex)
     {
     }
 }
Пример #11
0
        public void OnJobProgress(long jobId, float progress)
        {
            using var scope       = scopeFactory.CreateScope();
            using var dataContext = scope.ServiceProvider.GetRequiredService <DataContext>();

            var job = dataContext.Jobs.Find(jobId);

            job.Progress = progress;

            JobProgress?.Invoke(this, new JobProgressEventArgs()
            {
                Job = job, Progress = progress
            });
        }
Пример #12
0
 public void IncrementValue(int jobId)
 {
     try
     {
         JobProgress jp = this.Jobs.GetById(jobId);
         if (jp != null)
         {
             SetValue(jp, jp.Value + 1);
         }
     }
     catch (Exception ex)
     {
     }
 }
Пример #13
0
 public void SetValue(string jobName, decimal value)
 {
     try
     {
         JobProgress jp = this.Jobs.GetByName(jobName);
         if (jp != null)
         {
             SetValue(jp, value);
         }
     }
     catch (Exception ex)
     {
     }
 }
Пример #14
0
 public void SetValue(int jobId, decimal value)
 {
     try
     {
         JobProgress jp = this.Jobs.GetById(jobId);
         if (jp != null)
         {
             SetValue(jp, value);
         }
     }
     catch (Exception ex)
     {
     }
 }
Пример #15
0
 public void IncrementValue(string jobName)
 {
     try
     {
         JobProgress jp = this.Jobs.GetByName(jobName);
         if (jp != null)
         {
             SetValue(jp, jp.Value + 1.0M);
         }
     }
     catch (Exception ex)
     {
     }
 }
Пример #16
0
        private static void InitRepository()
        {
            JobProgress progress = progressController.CreateJob(0, 4, "Init");

            Membership.Tasks.Init(settings.SqlConnectionString);
            progressController.IncrementValue(progress.JobId);

            Membership.Roles.Init(settings.SqlConnectionString);
            progressController.IncrementValue(progress.JobId);

            Membership.UserSettings.Init(settings.SqlConnectionString);
            progressController.IncrementValue(progress.JobId);

            Membership.Users.Init(settings.SqlConnectionString, Cultures.GetAll());
            progressController.IncrementValue(progress.JobId);
        }
Пример #17
0
        public void Run_Counter(int counter)
        {
            string templateVariable;
            string templateHeader;
            string templateBody;
            string templateFooter;

            JobProgress.Start();

            // Reset all setings on RowCollections objects
            outputMenagerSettings.rowCollectionMenager.ResetSettings();

            ReplaceTagsOnce();

            for (int i = 0; i < counter; i++)
            {
                // increment row counter
                outputMenagerSettings.rowCollectionMenager.ActiveObjectInstance.RowCounter++;

                templateVariable = tagsReplace.ReplaceTags(outputMenagerSettings.sourceTemplateVariables, null);
                templateHeader   = tagsReplace.ReplaceTags(outputMenagerSettings.sourceTemplateHeader, null);
                templateBody     = tagsReplace.ReplaceTags(outputMenagerSettings.sourceTemplateBody, null);
                templateFooter   = tagsReplace.ReplaceTags(outputMenagerSettings.sourceTemplateFooter, null);

                if (outputMenagerSettings.destinationType == OutputMenagerSettings.DestinationType.File)
                {
                    this.DestinationFile(templateHeader, templateBody, templateFooter, null, i, counter);
                }
                else if (outputMenagerSettings.destinationType == OutputMenagerSettings.DestinationType.Notepad)
                {
                    this.DestinationNotepad(templateHeader, templateBody, templateFooter, i, counter);
                }
                else if (outputMenagerSettings.destinationType == OutputMenagerSettings.DestinationType.DataObjectCompareStrings)
                {
                    this.DestinationObjectData_CompareStrings(templateHeader, templateBody, templateFooter, null, i, counter);
                }
                System.Windows.Forms.Application.DoEvents();
                //JobProgress.Write("Radim ...." + i );
            }
            // Close stream writer object
            if (sw != null)
            {
                sw.Close();
            }
            JobProgress.Ready();
        }
Пример #18
0
        /// <summary>
        /// Query progress of a specific settler job at this location
        /// </summary>
        /// <param name="job">the job</param>
        /// <param name="progress">the progress</param>
        /// <returns>result of operation</returns>
        public PlayResult GetJobProgress__Turn(Job job, out JobProgress progress)
        {
            fixed(JobProgress *jobProgressData = new JobProgress[Protocol.nJob])
            {
                PlayResult result = TheEmpire.Play(Protocol.sGetJobProgress, Id, jobProgressData);

                progress = jobProgressData[(int)job];
                if (result.OK)
                {
                    JobWorkRemaining[] workRemaining = new JobWorkRemaining[Protocol.nJob];
                    for (int j = 0; j < Protocol.nJob; j++)
                    {
                        workRemaining[j] = new JobWorkRemaining(jobProgressData[j].Required, jobProgressData[j].Done);
                    }
                    TheEmpire.Map.JobInfo[Id] = workRemaining;
                }
                return(result);
            }
        }
Пример #19
0
 public WpsJob(WpsProcess wpsProcess, Execute execute)
 {
     logger = wpsProcess.GetLogger();
     logger.LogInformation("Create new wpsjob");
     logger.LogDebug("Create new wpsjob -- start");
     this.wpsProcess  = wpsProcess;
     this.wpsJobCache = this.wpsProcess.GetMemoryCache();
     progress         = new JobProgress();
     creationTime     = DateTime.UtcNow;
     this.jobOrder    = new JobOrder()
     {
         ExecuteRequest = execute, JobProgress = progress, CreationTime = creationTime
     };
     this.Task         = wpsProcess.CreateTask(jobOrder);
     Uid               = Save(DateTimeOffset.Now.Add(wpsProcess.JobCacheTime));
     this.jobOrder.Uid = this.Uid;
     JobOrder.WriteExecuteRequest(execute, this.Uid);
     logger.LogDebug("Create new wpsjob -- end");
 }
Пример #20
0
        public JobProgress CreateJob(decimal minValue, decimal maxValue, string name)
        {
            JobProgress job;

            try
            {
                lock (this)
                {
                    job = new JobProgress(Jobs.Count, name, minValue, maxValue);
                    this.Jobs.Add(job);
                }
            }
            catch (Exception ex)
            {
                job = null;
            }

            return(job);
        }
Пример #21
0
        private void LoadXML(string xmlFile)
        {
            ModuleLog.Write(xmlFile, this, "LoadXML", ModuleLog.LogType.DEBUG);
            if (string.Empty != xmlFile)
            {
                //FileInfo fInfo = new FileInfo(xmlFile);
                //DirectoryInfo dInfo = new DirectoryInfo(string.Concat(fInfo.Directory.FullName, "/", "icons/"));
                //if (dInfo.Exists)
                //{
                //    JobStatus.Write("Loading images..");
                //    imageList1.Images.Clear();
                //    FileInfo[] imgList = dInfo.GetFiles("*.gif");
                //    foreach (FileInfo file in imgList)
                //    {
                //        Image image = Image.FromFile(file.FullName);
                //        imageList1.Images.Add("icons/" + file.Name, image);
                //    }
                //    treeView1.ImageList = imageList1;
                //}
                //JobStatus.Write("Opening xml...");
                xmlDoc = new XmlDocument();
                try
                {
                    TreeNode rootNode = new TreeNode("Root");
                    xmlDoc.Load(xmlFile);
                    LoadXMLChild(rootNode, xmlDoc.SelectSingleNode("tags"));
                    treeView1.Nodes.Add(rootNode);
                    //LoadActions();
                }
                catch (XmlException err)
                {
                    //SetStatus("Error opening xml file");
                    MessageBox.Show(err.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                catch (Exception e)
                {
                    ModuleLog.Write(e, this, "LoadXML", ModuleLog.LogType.ERROR, false);
                }

                JobProgress.Ready();
            }
        }
Пример #22
0
        public async Task Set(string key, JobProgress progress)
        {
            await _semaphore.WaitAsync();

            try
            {
                _progresses[key] = progress;

                if (_storageEnabled)
                {
                    var filePath = GetFilePath(key);
                    var text     = Serialize(progress);
                    await File.WriteAllTextAsync(filePath, text);
                }
            }
            finally
            {
                _semaphore.Release();
            }
        }
Пример #23
0
        internal bool UpdateJob(decimal minValue, decimal maxValue, string name)
        {
            bool res = false;

            try
            {
                JobProgress jp = this.Jobs.GetByName(name);
                if (jp != null)
                {
                    jp.MinValue = minValue;
                    jp.MaxValue = maxValue;

                    res = true;
                }
            }
            catch (Exception ex)
            {
                res = false;
            }

            return(res);
        }
Пример #24
0
        private bool IsRunnable(JobProgress progress)
        {
            if (_context.EndInstant.HasValue)
            {
                // Just check for the end. If this would have been a partial iteration (_context.End was between
                // Progress.Start and Progress.End), CalculateProgressBeforeRead method would have been adjusted it.
                if (progress.NextIterationEnd > _context.EndInstant.Value)
                {
                    return(false);
                }

                // If the Progress.End is exactly equal to _context.End, allow it to be run without any regard
                // to cut-off, since it's the last iteration ever to be run.
                if (progress.NextIterationEnd == _context.EndInstant.Value)
                {
                    return(true);
                }
            }

            var endCutoffInstant = InstantUtils.SecondsAgo(_context.ClockSkewProtectionSeconds);

            return(progress.NextIterationEnd <= endCutoffInstant);
        }
Пример #25
0
 protected abstract void ProcessJobProgress(JobProgress jobProgress);
Пример #26
0
        private static void Init(Entities.Culture culture)
        {
            JobProgress progress = progressController.Jobs.GetByName("Init");

            if (progress == null)
            {
                progress = progressController.CreateJob(0, 27, "Init");
            }
            else
            {
                progress.MinValue = 0;
                progress.MaxValue = 27;
            }

            Currencies.Init(settings.SqlConnectionString);
            progress.Value++;

            Types.Init(settings.SqlConnectionString);
            progress.Value++;

            Categories.Init(settings.SqlConnectionString);
            progress.Value++;

            Employees.Init(settings.SqlConnectionString);
            progress.Value++;

            SignUpTypes.Init(settings.SqlConnectionString, culture);
            progress.Value++;

            PersonTitleTypes.Init(settings.SqlConnectionString, culture);
            progress.Value++;

            ContactMediaTypes.Init(settings.SqlConnectionString, culture);
            progress.Value++;

            TourTypes.Init(settings.SqlConnectionString, culture);
            progress.Value++;

            PaymentTypes.Init(settings.SqlConnectionString, culture);
            progress.Value++;

            TourMembershipTypes.Init(settings.SqlConnectionString, culture);
            progress.Value++;

            Phonebook.Init(settings.SqlConnectionString);
            progress.Value++;

            TourStates.Init(settings.SqlConnectionString, culture);
            progress.Value++;

            TourCostConstraintTypes.Init(settings.SqlConnectionString, culture);
            progress.Value++;

            Tours.Init(settings.SqlConnectionString);
            progress.Value++;

            ServiceTypes.Init(settings.SqlConnectionString, culture);
            progress.Value++;

            MailEventTypes.Init(settings.SqlConnectionString, culture);
            progress.Value++;

            TourRuleConstraints.Init(settings.SqlConnectionString);
            progress.Value++;

            TourCostRules.Init(settings.SqlConnectionString);
            progress.Value++;

            TourCostGroups.Init(settings.SqlConnectionString);
            progress.Value++;

            TourGroupServiceCosts.Init(settings.SqlConnectionString);
            progress.Value++;

            TourGroupServicePayments.Init(settings.SqlConnectionString);
            progress.Value++;

            TourGroupMembers.Init(settings.SqlConnectionString);
            progress.Value++;

            TourGroupEmployees.Init(settings.SqlConnectionString);
            progress.Value++;

            TourGroups.Init(settings.SqlConnectionString);
            progress.Value++;

            Services.Init(settings.SqlConnectionString);
            progress.Value++;

            TourGroupServices.Init(settings.SqlConnectionString);
            progress.Value++;

            Mails.Init(settings.SqlConnectionString);
            progress.Value++;

            // Note: please fix # of progress jobs if you added
            // anything else here.
        }
Пример #27
0
 protected override void ProcessJobProgress(JobProgress jobProgress)
 {
     this.RemoveOldDiscoveryJob(jobProgress.get_JobId());
 }
Пример #28
0
        static int Main(string[] args)
        {
            //0 - success
            //1 - see in result file
            //2 - failed to read job

            if (args.Length == 0)
            {
                Console.WriteLine("No job specified");
                return(2);
            }

            if (!File.Exists(args[0]))
            {
                Console.WriteLine("Job file not found");
                return(2);
            }

            string jobPath = args[0];

            //load the job
            try
            {
                string json = File.ReadAllText(jobPath);
                Job = JsonConvert.DeserializeObject <ImportJob>(json);
            }
            catch (JobParseException e)
            {
                Console.WriteLine("Failed to initialize the job");
            }
            catch (Exception e)
            {
                Console.WriteLine("Failed to load the job");
                return(2);
            }
            //initialize the job
            try
            {
                Job.Init();
                if (!Job.TmpFolder.EndsWith("\\") && !Job.TmpFolder.EndsWith("/"))
                {
                    Job.TmpFolder += "\\";
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Problem detected with job, " + e);
                JobResult.WriteForJob(jobPath, Job, 1, e.Message);
                return(1);
            }

            if (!File.Exists(Job.Input.CsvFileName))
            {
                Console.WriteLine("Input file not found");
                JobResult.WriteForJob(jobPath, Job, 1, "Input file not found");
                return(1);
            }

            if (Directory.Exists(Job.TmpFolder))
            {
                //delete all subs
                foreach (var fs in new DirectoryInfo(Job.TmpFolder).GetFileSystemInfos())
                {
                    fs.Delete();
                }
            }
            else
            {
                Directory.CreateDirectory(Job.TmpFolder);
            }
            var selfProgr = new JobProgress()
            {
                CurrentStage           = "init",
                CurrentStagePercentage = 0,
                OverallProgress        = 0,
                Id = Job.Id
            };

            using (Progress = new JobProgressWrapper(selfProgr, args[0] + ".progress"))
            {
                Progress.Progress.TotalStagesCount = 3;
                Progress.CommitProgress();

                //Console.ReadLine();
                //todo: try to truncate all the data that is the same for all records in the line
                try
                {
                    Progress.Progress.CurrentStageNomber = 1;
                    CsvImporter.Import(Job);
                    Progress.Progress.CurrentStageNomber = 2;
                    MetaCompiler.Compile(Job.TmpFolder);
                    Progress.Progress.CurrentStageNomber = 3;
                    MongoExporter.ExportToMongoDB(Job);
                }
                catch (ImportException e)
                {
                    JobResult.WriteForJob(jobPath, Job, e.Code, e.Message);
                    return(1);
                }
                catch (Exception e)
                {
                    JobResult.WriteForJob(jobPath, Job, 777, $"Crashed with exception {e}");
                    return(1);
                }

                //Console.WriteLine("Completed import");
                //Console.ReadLine();
                //TODO:clean up tmp folder?
            }
            JobResult.WriteForJob(jobPath, Job, 0, "OK");

            //Stopwatch swTotal = Stopwatch.StartNew();

            //string log_path =
            //    "C:\\Users\\Alex\\Downloads\\BPI2016_Clicks_Logged_In.csv\\BPI2016_Clicks_Logged_In_old.csv";
            ////"C:\\Users\\Alex\\Downloads\\BPI2016_Clicks_Logged_In.csv\\0.csv";
            //string tmp_dir = "X:\\tmp\\";


            ////if (dict.Count != 0)
            ////{
            ////    Console.WriteLine("Importing remaining objects");
            ////    ImportToDb(dict);
            ////    dict.Clear();
            ////    GC.Collect();
            ////}
            ////test();
            ////Console.WriteLine();
            ////Console.WriteLine("Objects : " + counter);
            ////Console.WriteLine("Grouped : " + grouped_count);
            //swTotal.Stop();

            //Console.WriteLine("Total : " + swTotal.ElapsedMilliseconds + " ms");
            // Console.ReadLine();
            return(0);
        }
Пример #29
0
 public async Task BroadcastJobProgress(JobProgress info)
 {
     await _jobHubContext.Clients.All.SendAsync(JobReportProgressMethod, info);
 }
Пример #30
0
        private void lvJobFiles_DrawSubItem(object sender, DrawListViewSubItemEventArgs e)
        {
            Rectangle       rectangle;
            Brush           gradientActiveCaption;
            BitsFile        tag        = (BitsFile)e.Item.Tag;
            BitsJob         bitsJob    = base.wrapper.BitsJob;
            Color           windowText = SystemColors.WindowText;
            Font            prototype  = this.lvJobFiles.Font;
            TextFormatFlags flags      = TextFormatFlags.LeftAndRightPadding | TextFormatFlags.EndEllipsis | TextFormatFlags.VerticalCenter;

            if (tag == null)
            {
                if ((bitsJob.State == JobState.Suspended) || (bitsJob.State == JobState.Queued))
                {
                    if (e.Item.Selected)
                    {
                        windowText = SystemColors.ActiveCaptionText;
                    }
                    else
                    {
                        windowText = SystemColors.InactiveCaptionText;
                    }
                    prototype = new Font(prototype, FontStyle.Italic);
                }
                else if ((bitsJob.State == JobState.Error) || (bitsJob.State == JobState.TransientError))
                {
                    windowText = Color.Red;
                }
                else if ((bitsJob.State == JobState.Transferred) || (bitsJob.State == JobState.Acknowledged))
                {
                    windowText = Settings.Default.ProgressCompletedColor;
                    prototype  = new Font(prototype, FontStyle.Strikeout);
                }
                else if (bitsJob.State == JobState.Canceled)
                {
                    if (e.Item.Selected)
                    {
                        windowText = SystemColors.ActiveCaptionText;
                    }
                    else
                    {
                        windowText = SystemColors.InactiveCaptionText;
                    }
                    prototype = new Font(prototype, FontStyle.Strikeout);
                }
                else if (bitsJob.State == JobState.Connecting)
                {
                    windowText = Color.YellowGreen;
                }
                else if (bitsJob.State == JobState.Transferring)
                {
                    windowText = Settings.Default.ProgressDoneColor;
                }
            }
            if (e.Item.Selected)
            {
                int num = (e.ColumnIndex == 0) ? 1 : 0;
                rectangle = new Rectangle(e.Bounds.X + num, e.Bounds.Y + 1, e.Bounds.Width - num, e.Bounds.Height - 2);
                if (this.lvJobFiles.Focused)
                {
                    gradientActiveCaption = SystemBrushes.GradientActiveCaption;
                }
                else
                {
                    gradientActiveCaption = SystemBrushes.GradientInactiveCaption;
                }
                e.Graphics.FillRectangle(gradientActiveCaption, rectangle);
            }
            if (e.SubItem.Name.Equals("BytesTotal"))
            {
                TextRenderer.DrawText(e.Graphics, e.SubItem.Text, prototype, e.Bounds, windowText, flags | TextFormatFlags.Right);
            }
            else if (e.SubItem.Name.Equals("BytesTransfered"))
            {
                TextRenderer.DrawText(e.Graphics, e.SubItem.Text, prototype, e.Bounds, windowText, flags | TextFormatFlags.Right);
            }
            else if (e.SubItem.Name == "Progress")
            {
                Rectangle    rectangle2;
                StringFormat format = new StringFormat();
                format.Alignment      = StringAlignment.Center;
                gradientActiveCaption = new SolidBrush(Settings.Default.ProgressLeftColor);
                rectangle             = new Rectangle(e.Bounds.X, e.Bounds.Y, e.Bounds.Width, e.Bounds.Height);
                e.Graphics.FillRectangle(gradientActiveCaption, rectangle);
                JobProgress progress = null;
                if (tag != null)
                {
                    FileProgress progress2 = null;
                    progress2  = tag.Progress;
                    rectangle2 = CalcProgress(e.Bounds, progress2.BytesTotal, progress2.BytesTransferred);
                    if (progress2.BytesTransferred > 0L)
                    {
                        if (progress2.Completed || (progress2.BytesTotal == progress2.BytesTransferred))
                        {
                            gradientActiveCaption = new SolidBrush(Settings.Default.ProgressCompletedColor);
                        }
                        else
                        {
                            gradientActiveCaption = new LinearGradientBrush(rectangle, Settings.Default.ProgressDoneColor, Settings.Default.ProgressCompletedColor, LinearGradientMode.Horizontal);
                        }
                    }
                    rectangle2 = Utils.CalculateProgress(rectangle, progress2.BytesTotal, progress2.BytesTransferred);
                }
                else
                {
                    progress   = bitsJob.Progress;
                    rectangle2 = CalcProgress(e.Bounds, progress.BytesTotal, progress.BytesTransferred);
                    if (progress.BytesTransferred > 0L)
                    {
                        if ((bitsJob.State == JobState.Transferred) || (bitsJob.State == JobState.Acknowledged))
                        {
                            gradientActiveCaption = new SolidBrush(Settings.Default.ProgressCompletedColor);
                        }
                        else
                        {
                            gradientActiveCaption = new LinearGradientBrush(rectangle, Settings.Default.ProgressDoneColor, Settings.Default.ProgressCompletedColor, LinearGradientMode.Horizontal);
                        }
                    }
                    rectangle2 = Utils.CalculateProgress(rectangle, progress.BytesTotal, progress.BytesTransferred);
                }
                e.Graphics.FillRectangle(gradientActiveCaption, rectangle2);
                ControlPaint.DrawBorder(e.Graphics, rectangle, SystemColors.ActiveBorder, ButtonBorderStyle.Solid);
                windowText = SystemColors.InactiveCaptionText;
                TextRenderer.DrawText(e.Graphics, e.SubItem.Text, prototype, rectangle, windowText, TextFormatFlags.VerticalCenter | TextFormatFlags.HorizontalCenter);
            }
            else
            {
                TextRenderer.DrawText(e.Graphics, e.SubItem.Text, prototype, e.Bounds, windowText, flags);
            }
        }
Пример #31
0
 protected Job(IContainer container)
 {
     _jobProgress = container.Get<JobProgress>();
 }