示例#1
0
        private void OnGetRepositoriesCompleted(IList <ExtendedRepository> repositories, Exception exception)
        {
            if (null == repositories || repositories.Count == 0)
            {
                Progress = WorkerProgress.Idle;
                return;
            }

            foreach (ExtendedRepository repo in repositories)
            {
                _repositoriesToCheck.Add(repo);
            }

            if (_workSequential)
            {
                if (_repositoriesToCheck.Count > 0)
                {
                    ExtendedRepository firstRepo = _repositoriesToCheck[0];
                    _dataService.BeginGetIncomingChanges(firstRepo, OnGetIncomingChangesCompleted);
                }
            }
            else
            {
                if (_repositoriesToCheck.Count > 0)
                {
                    foreach (ExtendedRepository repo in _repositoriesToCheck)
                    {
                        _dataService.BeginGetIncomingChanges(repo, OnGetIncomingChangesCompleted);
                    }
                }
            }
        }
示例#2
0
        private static void ActionWorkerDoWork(object sender, DoWorkEventArgs e)
        {
            const int progressBufferSize = 5;

            BackgroundWorker worker = (BackgroundWorker)sender;
            WorkerArgs args = (WorkerArgs)e.Argument;

            string[] allFiles = Directory.GetFiles(args.BaseDirectory, "*.*",
                args.IncludeSubdirectories ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly);

            WorkerProgress[] progressBuffer = new WorkerProgress[progressBufferSize];
            int reportBufferCounter = 1;

            IEnumerable<Regex> maskPatterns = GenerateMaskPatterns(args.FileMasks);
            for (int i = 0; i < allFiles.Length; i++)
            {
                if (worker.CancellationPending)
                {
                    e.Cancel = true;
                    break;
                }

                string path = allFiles[i];
                string fileName = Path.GetFileName(path);
                if (!SatisfiesMaskPatterns(fileName, maskPatterns))
                    continue;

                CharsetDetector detector = new CharsetDetector();
                using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))
                {
                    detector.Feed(fs);
                    detector.DataEnd();
                }
                if (args.Action == CurrentAction.Validate)
                {
                    if (detector.Charset == null)
                        continue;
                    if (args.ValidCharsets.Contains(detector.Charset))
                        continue;
                }

                string directoryName = Path.GetDirectoryName(path);

                WorkerProgress progress = new WorkerProgress();
                progress.Charset = detector.Charset ?? "(Unknown)";
                progress.FileName = fileName;
                progress.DirectoryName = directoryName;
                progressBuffer[reportBufferCounter - 1] = progress;
                reportBufferCounter++;
                if (reportBufferCounter > progressBufferSize)
                {
                    reportBufferCounter = 1;
                    int percentageCompleted = (i * 100) / allFiles.Length;
                    WorkerProgress[] reportProgress = new WorkerProgress[progressBufferSize];
                    Array.Copy(progressBuffer, reportProgress, progressBufferSize);
                    worker.ReportProgress(percentageCompleted, reportProgress);
                    Array.Clear(progressBuffer, 0, progressBufferSize);
                }
            }
        }
示例#3
0
 private void OnTimerTick(object sender, EventArgs e)
 {
     //_timer.Stop();
     Progress = WorkerProgress.Active;
     _updatedRepositories.Clear();
     _dataService.BeginGetRepositories(OnGetRepositoriesCompleted);
 }
示例#4
0
        private void Btn_Start_Click(object sender, RoutedEventArgs e)
        {
            cts = new CancellationTokenSource();
            //Worker wrk = new Worker(10, 1000, cts);
            IProgress <int> progress = new Progress <int>(UpdateUI);
            WorkerProgress  wrk      = new WorkerProgress(10, 1000, cts, progress);

            wrk.Start();
            MessageBox.Show("Mi dimentico del thread secondario e visualizzo subito questo messaggio senza attendere che l'altro abbia finito", "Informazioni", MessageBoxButton.OK, MessageBoxImage.Information);
        }
示例#5
0
        private void ActionWorkerProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            WorkerProgress progress = (WorkerProgress)e.UserState;

            ListViewItem resultItem = new ListViewItem(new string[] { progress.Charset, progress.FileName, progress.DirectoryName }, -1);

            lstResults.Items.Add(resultItem);

            actionProgress.Value = e.ProgressPercentage;
            actionStatus.Text    = progress.FileName;
        }
示例#6
0
        private static void ActionWorkerDoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = (BackgroundWorker)sender;
            WorkerArgs       args   = (WorkerArgs)e.Argument;

            string[] allFiles = Directory.GetFiles(args.BaseDirectory, "*.*",
                                                   args.IncludeSubdirectories ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly);

            IEnumerable <Regex> maskPatterns = GenerateMaskPatterns(args.FileMasks);

            for (int i = 0; i < allFiles.Length; i++)
            {
                if (worker.CancellationPending)
                {
                    e.Cancel = true;
                    break;
                }

                string path     = allFiles[i];
                string fileName = Path.GetFileName(path);
                if (!SatisfiesMaskPatterns(fileName, maskPatterns))
                {
                    continue;
                }

                CharsetDetector detector = new CharsetDetector();
                using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))
                {
                    detector.Feed(fs);
                    detector.DataEnd();
                }
                if (args.Action == CurrentAction.Validate)
                {
                    if (detector.Charset == null)
                    {
                        continue;
                    }
                    if (args.ValidCharsets.Contains(detector.Charset))
                    {
                        continue;
                    }
                }

                string directoryName = Path.GetDirectoryName(path);

                int            percentageCompleted = (i * 100) / allFiles.Length;
                WorkerProgress progress            = new WorkerProgress();
                progress.Charset       = detector.Charset ?? "(Unknown)";
                progress.FileName      = fileName;
                progress.DirectoryName = directoryName;
                worker.ReportProgress(percentageCompleted, progress);
            }
        }
示例#7
0
 private void SwitchTrayIcon(WorkerProgress workerProgress)
 {
     switch (workerProgress)
     {
         case (WorkerProgress.Idle):
             {
                 Stream imageStream = Application.GetResourceStream(new Uri("pack://application:,,/Images/WatchtowerIdle.ico")).Stream;
                 _trayIcon.Icon = new System.Drawing.Icon(imageStream);
                 break;
             }
         case (WorkerProgress.Active):
             {
                 Stream imageStream = Application.GetResourceStream(new Uri("pack://application:,,/Images/WatchtowerActive.ico")).Stream;
                 _trayIcon.Icon = new System.Drawing.Icon(imageStream);
                 break;
             }
     }
 }
示例#8
0
        private void SwitchTrayIcon(WorkerProgress workerProgress)
        {
            switch (workerProgress)
            {
            case (WorkerProgress.Idle):
            {
                Stream imageStream = Application.GetResourceStream(new Uri("pack://application:,,/Images/WatchtowerIdle.ico")).Stream;
                _trayIcon.Icon = new System.Drawing.Icon(imageStream);
                break;
            }

            case (WorkerProgress.Active):
            {
                Stream imageStream = Application.GetResourceStream(new Uri("pack://application:,,/Images/WatchtowerActive.ico")).Stream;
                _trayIcon.Icon = new System.Drawing.Icon(imageStream);
                break;
            }
            }
        }
示例#9
0
            public Worker(
                Queue <IWorkerTask> taskQueue,
                ref object syncRoot,
                WorkerProgress progress,
                ILog log,
                DisposingOptions disposingOptions)
            {
                this.taskQueue        = taskQueue;
                this.syncRoot         = syncRoot;
                this.progress         = progress;
                this.disposingOptions = disposingOptions;

                thread = new Thread(WorkerRoutine)
                {
                    IsBackground = true
                };
                this.log = log.WithPrefix($"[Thread {thread.ManagedThreadId}]");
                thread.Start();
            }
        public ActionResult WorkProgressOwner(int id)
        {
            var             post            = _postservice.GetByID(id);
            var             selectedWorkers = _selectedWorkerService.GetAll().Data.Where(d => d.PostId == id).ToList();
            List <UserInfo> workers         = new List <UserInfo>();

            foreach (var v in selectedWorkers)
            {
                workers.Add(_userservice.GetByID(v.UserId).Data);
            }

            List <int> sectionIDs      = new List <int>();
            var        projectSections = _sectionservice.GetAll().Data.Where(d => d.PostId == id).ToList();

            foreach (var v in projectSections)
            {
                sectionIDs.Add(v.ProjectSectionId);
            }

            var commentsAll = _comentSectionService.GetAll().Data.ToList();
            var comments    = new List <COMMENTSEC>();

            foreach (var v in commentsAll)
            {
                foreach (var x in sectionIDs)
                {
                    if (v.ProjectSectionId == x)
                    {
                        comments.Add(v);
                    }
                }
            }

            var files = _savedFileService.GetAll().Data.Where(d => d.PostId == id).ToList();
            var VM    = new WorkerProgress();

            VM = VM.creation(post, workers, projectSections, comments, files);
            return(View(VM));
        }
示例#11
0
        private void OnGetIncomingChangesCompleted(ExtendedRepository repository, Exception exception)
        {
            _repositoriesToCheck.RemoveAt(0);

            if (null != repository && null != repository.IncomingChangesets && repository.IncomingChangesets.Count > 0)
            {
                _updatedRepositories.Add(repository.Name, repository);
            }

            if (_repositoriesToCheck.Count > 0)
            {
                ExtendedRepository firstRepo = _repositoriesToCheck[0];
                _dataService.BeginGetIncomingChanges(firstRepo, OnGetIncomingChangesCompleted);
            }
            else
            {
                Progress = WorkerProgress.Idle;

                if (_updatedRepositories.Count > 0)
                {
                    OnIncomingChangesDetected();
                }
            }
        }
示例#12
0
        public WorkersPool(int workersCount, ILog log, DisposingOptions disposingOptions = null)
        {
            if (workersCount <= 0)
            {
                throw new ArgumentException("Workers count can't be negative or zero number", nameof(workersCount));
            }

            if (log == null)
            {
                throw new ArgumentNullException(nameof(log));
            }

            disposingOptions = disposingOptions ?? DisposingOptions.Default;

            this.log  = log.WithPrefix($"[{nameof(WorkersPool)}]");
            taskQueue = new Queue <IWorkerTask>(workersCount);
            progress  = new WorkerProgress();

            workers = new List <Worker>(workersCount);
            for (var i = 0; i < workersCount; i++)
            {
                workers.Add(new Worker(taskQueue, ref syncObject, progress, log, disposingOptions));
            }
        }
示例#13
0
 public ProgressChangedEventArgs(WorkerProgress workerProgress)
 {
     WorkerProgress = workerProgress;
 }
示例#14
0
        private static void ActionWorkerDoWork(object sender, DoWorkEventArgs e)
        {
            const int progressBufferSize = 5;

            BackgroundWorker worker = (BackgroundWorker)sender;
            WorkerArgs       args   = (WorkerArgs)e.Argument;

            string[] allFiles = Directory.GetFiles(args.BaseDirectory, "*.*",
                                                   args.IncludeSubdirectories ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly);

            WorkerProgress[] progressBuffer = new WorkerProgress[progressBufferSize];
            int reportBufferCounter         = 1;

            IEnumerable <Regex> maskPatterns = GenerateMaskPatterns(args.FileMasks);

            for (int i = 0; i < allFiles.Length; i++)
            {
                if (worker.CancellationPending)
                {
                    e.Cancel = true;
                    break;
                }

                string path     = allFiles[i];
                string fileName = Path.GetFileName(path);
                if (!SatisfiesMaskPatterns(fileName, maskPatterns))
                {
                    continue;
                }

                Encoding encoding = TextEncoding.GetFileEncoding(path);
                string   charset  = encoding?.WebName ?? "(Unknown)";

                if (args.Action == CurrentAction.Validate)
                {
                    if (args.ValidCharsets.Contains(charset))
                    {
                        continue;
                    }
                }

                string directoryName = Path.GetDirectoryName(path);

                progressBuffer[reportBufferCounter - 1] = new WorkerProgress
                {
                    Charset       = charset,
                    FileName      = fileName,
                    DirectoryName = directoryName
                };
                reportBufferCounter++;
                if (reportBufferCounter > progressBufferSize)
                {
                    reportBufferCounter = 1;
                    int percentageCompleted         = (i * 100) / allFiles.Length;
                    WorkerProgress[] reportProgress = new WorkerProgress[progressBufferSize];
                    Array.Copy(progressBuffer, reportProgress, progressBufferSize);
                    worker.ReportProgress(percentageCompleted, reportProgress);
                    Array.Clear(progressBuffer, 0, progressBufferSize);
                }
            }

            // Copy remaining results from buffer, if any.
            if (reportBufferCounter > 1)
            {
                reportBufferCounter--;
                int percentageCompleted         = 100;
                WorkerProgress[] reportProgress = new WorkerProgress[reportBufferCounter];
                Array.Copy(progressBuffer, reportProgress, reportBufferCounter);
                worker.ReportProgress(percentageCompleted, reportProgress);
                Array.Clear(progressBuffer, 0, reportBufferCounter);
            }
        }
示例#15
0
        private void RenumberWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            if (!(e.Argument is WorkerParameters workerParameter))
            {
                return;
            }

            try
            {
                int currentEpisodeNumber = workerParameter.EpisodeNumberStart;

                for (int i = 0; i < workerParameter.SelectedEpisodes.Count; i++)
                {
                    var episodeFilePath = workerParameter.SelectedEpisodes[i];

                    string curDir = System.IO.Path.GetDirectoryName(episodeFilePath);

                    if (string.IsNullOrEmpty(curDir))
                    {
                        WriteOutput("Could not find directory, skipping.", OutputMessageLevel.Error);
                        continue;
                    }

                    string curName = System.IO.Path.GetFileName(episodeFilePath);

                    if (string.IsNullOrEmpty(curName))
                    {
                        WriteOutput("Could not find file, skipping.", OutputMessageLevel.Error);
                        continue;
                    }

                    // Using substring and Length so that user doesn't need an exact natch (e.g. episode number will be different for each selected episode, thus only one selection will get renamed... the exact match)
                    var selectedText = curName.Substring(0, workerParameter.SelectedTextLength);

                    // Get the show name to workaround not being able to select exact text
                    var showName = Directory.GetParent(episodeFilePath)?.Parent?.Name;

                    // Prefix the name name with the Show, then the season, then the episode number
                    string newName = curName.Replace(selectedText, $"{showName} - S{workerParameter.SeasonNumber}E{currentEpisodeNumber:00} -", StringComparison.InvariantCulture);

                    // If this is not a preview run, invoke the file rename
                    if (!workerParameter.IsPreview)
                    {
                        File.Move(episodeFilePath, System.IO.Path.Combine(curDir, newName));
                    }

                    // Increment the episode number
                    currentEpisodeNumber++;

                    // Report progress
                    var progressParameter = new WorkerProgress
                    {
                        IsPreview       = workerParameter.IsPreview,
                        PercentComplete = i / workerParameter.SelectedEpisodes.Count * 100,
                        BusyMessage     = $"Completed: S{workerParameter.SeasonNumber}E{currentEpisodeNumber:00}...",
                        FileName        = newName
                    };

                    renumberWorker.ReportProgress(progressParameter.PercentComplete, progressParameter);
                }

                e.Result = new WorkerResult()
                {
                    FinalMessage = $"Complete, renumbered {workerParameter.SelectedEpisodes.Count} episodes.",
                    IsPreview    = workerParameter.IsPreview
                };
            }
            catch (Exception ex)
            {
                WriteOutput(ex.Message, OutputMessageLevel.Error);

                Crashes.TrackError(ex, new Dictionary <string, string>
                {
                    { "Renumber Episode", "TV Show" }
                });
            }
        }