Esempio n. 1
0
        private static IEnumerable<WorkerTask> GenerateNormalRandomList(EngineType? tasktype)
        {
            var tasks = new List<WorkerTask>();

            var random = new Random();
            var numberOfTasks = random.Next(16, 32);

            for (int i = 1; i <= numberOfTasks; i++)
            {
                var loopTask = Task.Factory.StartNew(t => FakeTaskActionMethod(), TaskCreationOptions.LongRunning);
                WorkerTask cloudTask;
                const string operationName = "Test Operation";
                if (tasktype.HasValue)
                {
                    cloudTask = new WorkerTask(operationName, loopTask,
                                                  FakeTaskActionMethod,
                                                  tasktype.Value);
                }
                else
                {
                    cloudTask = new WorkerTask(operationName, loopTask,
                                                  FakeTaskActionMethod,
                                                  i % 2 == 0 ? EngineType.ScheduledTask : (i % 3 == 0 ? EngineType.Workflow : EngineType.Maintenance));
                }

                tasks.Add(cloudTask);
            }

            return tasks;
        }
        public override IEnumerable<WorkerTask> CreateTaskThreads()
        {
            var loopTask = Task.Factory.StartNew(ScheduledTaskMonitorLoop, TaskCreationOptions.LongRunning);
            var cloudTask = new WorkerTask(OperationContext.LoggingCategory, loopTask, ScheduledTaskMonitorLoop, EngineType.ScheduledTask);

            return new[] { cloudTask };
        }
 private static ulong CorrectBlockSize(WorkerTask task, ulong I)
 {
     ulong maxValue = I + PerformanceConstants.WorkerBlockSize;
     ulong blockSize = maxValue > task.MainTask.To
                       	? PerformanceConstants.WorkerBlockSize - (maxValue - task.MainTask.To)
                       	: PerformanceConstants.WorkerBlockSize;
     return blockSize;
 }
Esempio n. 4
0
        public override IEnumerable<WorkerTask> CreateTaskThreads()
        {
            var tasks = new List<WorkerTask>();
            var parallelThreadCount = ((WorkflowContext) OperationContext).ParallelThreadCount;

            for (var i = 1; i <= parallelThreadCount; i++)
            {
                var loopTask = Task.Factory.StartNew(t => WorkflowMonitorLoop(), TaskCreationOptions.LongRunning);
                var cloudTask = new WorkerTask(OperationContext.LoggingCategory, loopTask, WorkflowMonitorLoop, EngineType.Workflow);
                tasks.Add(cloudTask);
            }
            return tasks;
        }
Esempio n. 5
0
    public void GiveTask(WorkerTask task)
    {
        _targetReached = false;

        if (_task)
            _task.SetInUse(false);

        if (task)
        {
            _task = task;
            GoToTarget();
        }
        else
        {
            _task = null;
            _status = WorkerStatus.Idle;
        }
    }
 public void RetryTask(WorkerTask task)
 {
     task.Errors.Clear();
     task.MyWorker = CreateWorker();
     task.PublishData();
 }
        private void ExecuteInThread(WorkerTask task)
        {
            var primes = task.KnownPrimes.ToArray();
            List<ulong> primesResult = new List<ulong>();
            Dictionary<ulong, List<ulong>> ordered = new Dictionary<ulong, List<ulong>>();

            Parallel.ForEach(SplitTask(task.MainTask),
                I =>
                {
                    var blockSize = CorrectBlockSize(task, I);
                    var sieve = BuildSieve(blockSize);

                    Sifting(sieve, blockSize, I, primes);

                    var partResult = BuildPartResult(I, sieve);

                    if (partResult.Count > 0)
                        lock (_sync)
                            ordered.Add(partResult[0], partResult);
                });

            foreach (var pair in ordered.OrderBy(x => x.Key))
            {
                primesResult.AddRange(pair.Value);
            }

            _pauseEvent.Reset();
            _free = true;
            _receiver.CalculationEnd(new WorkerResult(task.MainTask, primesResult));
            _pauseEvent.Set();
        }
        public override void CaptureRectRegionClipboard()
        {
            WorkerTask hkrcTask = CreateTask(WorkerTask.JobLevel2.CaptureRectRegionClipboard);

            RunWorkerAsync(hkrcTask);
        }
        public override void CaptureFreeHandRegion()
        {
            WorkerTask hkfhrTask = CreateTask(WorkerTask.JobLevel2.CaptureFreeHandRegion);

            RunWorkerAsync(hkfhrTask);
        }
        public override void BwApp_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            WorkerTask task = (WorkerTask)e.Result;

            PostWorkerTasks();
            if (task == null)
            {
                return;
            }

            this.Text  = Engine.GetProductName();
            niTray.Tag = task;

            if (task.UploadResults.Count > 0)
            {
                UploadManager.UploadResultLast = task.UploadResults[task.UploadResults.Count - 1];
                UploadManager.ResetCumulativePercentage();
            }

            try
            {
                if (task.IsError && task.Errors[0].Contains(ExceptionMessage.ProxyAuthenticationRequired))
                {
                    ProxyUI ui = new ProxyUI();
                    if (ui.ShowDialog() == DialogResult.OK)
                    {
                        Engine.ConfigUI.ConfigProxy.ProxyList.Add(ui.Proxy);
                        Engine.ConfigUI.ConfigProxy.ProxyConfigType = EProxyConfigType.ManualProxy;
                        Uploader.ProxySettings = Adapter.CheckProxySettings();
                    }
                    RetryTask(task);
                }

                WorkerTask checkTask = RetryUpload(task);

                if (checkTask.States.Contains(WorkerTask.TaskState.RetryPending))
                {
                    string message = string.Format("{0}\r\n\r\nAutomatically retrying upload for {1}.", string.Join("\r\n", task.Errors.ToArray()), checkTask.WorkflowConfig.DestConfig.ToStringImageUploaders());
                    niTray.ShowBalloonTip(5000, Application.ProductName, message, ToolTipIcon.Warning);
                }
                else
                {
                    task.States.Add(WorkerTask.TaskState.Finished);

                    if (task.WorkflowConfig.DestConfig.TaskClipboardContent.Contains(ClipboardContentEnum.Local) && Engine.ConfigUI.ShowSaveFileDialogImages)
                    {
                        string fp = task.WriteImageAs();
                        if (!string.IsNullOrEmpty(fp))
                        {
                            task.UpdateLocalFilePath(fp);
                        }
                    }

                    switch (task.Job1)
                    {
                    case EDataType.Text:
                        if (task.Job2 == WorkerTask.JobLevel2.Translate)
                        {
                            UpdateGoogleTranslateGUI(task.TranslationInfo);

                            Loader.MyGTGUI.btnTranslate.Enabled   = true;
                            Loader.MyGTGUI.btnTranslateTo.Enabled = true;
                        }
                        break;

                    case EDataType.Image:
                        if (!task.WorkflowConfig.DestConfig.TaskClipboardContent.Contains(ClipboardContentEnum.Local) && Engine.ConfigOptions.DeleteLocal && File.Exists(task.Info.LocalFilePath))
                        {
                            try
                            {
                                File.Delete(task.Info.LocalFilePath);
                            }
                            catch (Exception ex)     // TODO: sometimes file is still locked... delete those files sometime
                            {
                                DebugHelper.WriteException(ex, "Error while finalizing job");
                            }
                        }
                        break;
                    }

                    if (Engine.ConfigOptions.TwitterEnabled)
                    {
                        Adapter.TwitterMsg(task);
                    }

                    bool bLastSourceButtonsEnabled = task.UploadResults.Count > 0 && !string.IsNullOrEmpty(task.UploadResults[task.UploadResults.Count - 1].Source);
                    this.btnOpenSourceText.Enabled    = bLastSourceButtonsEnabled;
                    this.btnOpenSourceBrowser.Enabled = bLastSourceButtonsEnabled;
                    this.btnOpenSourceString.Enabled  = bLastSourceButtonsEnabled;

                    if (task.UploadResults.Count > 0 || File.Exists(task.Info.LocalFilePath) || task.Job2 == WorkerTask.JobLevel2.Translate)
                    {
                        if (Engine.ConfigOptions.CompleteSound)
                        {
                            if (Engine.ConfigWorkflow.EnableSoundTaskCompleted && !string.IsNullOrEmpty(Engine.ConfigWorkflow.SoundPath) && File.Exists(Engine.ConfigWorkflow.SoundPath))
                            {
                                new SoundPlayer(Engine.ConfigWorkflow.SoundPath).Play();
                            }
                            else
                            {
                                SystemSounds.Exclamation.Play();
                            }
                        }

                        if (Engine.ConfigOptions.ShowBalloonTip)
                        {
                            ShowBalloonTip(task);
                        }
                    }

                    if (task.IsError)
                    {
                        foreach (string error in task.Errors)
                        {
                            DebugHelper.WriteLine(error);
                        }
                        niTray.ShowBalloonTip(5000, Application.ProductName, niTray.BalloonTipText + Environment.NewLine + task.Errors[task.Errors.Count - 1], ToolTipIcon.Error);
                    }
                }

                if (!task.IsError)
                {
                    AddHistoryItem(task);
                }

                // do this last
                UploadManager.ShowUploadResults(task, false);
            }
            catch (Exception ex)
            {
                DebugHelper.WriteException(ex, "Job Completed with errors: ");
            }
            finally
            {
                UploadManager.Commit(task.Id);

                if (TaskbarManager.IsPlatformSupported)
                {
                    Adapter.TaskbarSetProgressState(this, TaskbarProgressBarState.NoProgress);
                }
            }

            DebugHelper.WriteLine(string.Format("Job completed: {0}", task.Job2));
            DebugHelper.WriteLine(string.Format("Task duration: {0} ms", task.UploadDuration));
            PostWorkerTasks();
        }
        public override void CaptureActiveMonitor()
        {
            WorkerTask hkesTask = CreateTask(WorkerTask.JobLevel2.CaptureActiveMonitor);

            RunWorkerAsync(hkesTask);
        }
Esempio n. 12
0
 /// <summary>
 /// Start the background operation.
 /// </summary>
 /// <exception cref="InvalidOperationException">When <see cref="IsBusy"/> is true.</exception>
 public void RunWorkerAsync()
 {
     if (IsBusy)
         throw new InvalidOperationException();
     task = new WorkerTask(this, null);
 }
Esempio n. 13
0
        private static void task_UploadCompleted(WorkerTask task)
        {
            try
            {
                if (ListViewControl != null && task != null && task.Result != null)
                {
                    ListViewItem lvi = ListViewControl.Items[task.Id];
                    lvi.Tag = task.Result;

                    if (task.Result.IsError)
                    {
                        string errors = string.Join("\r\n\r\n", task.Result.Errors.ToArray());

                        DebugHelper.WriteLine("Upload failed. ID: {0}, Filename: {1}, Errors:\r\n{2}", task.Id, task.Info.FileName, errors);

                        lvi.SubItems[1].Text = "Error";
                        lvi.SubItems[8].Text = string.Empty;
                        lvi.ImageIndex       = 1;

                        if (Engine.ConfigOptions.CompleteSound)
                        {
                            SystemSounds.Asterisk.Play();
                        }
                    }
                    else
                    {
                        DebugHelper.WriteLine("Upload completed. ID: {0}, Filename: {1}, URL: {2}, Duration: {3}ms", task.Id, task.Info.FileName,
                                              task.Result.URL, (int)task.UploadDuration);

                        lvi.SubItems[1].Text = task.Status.GetDescription();
                        lvi.ImageIndex       = 2;

                        if (!string.IsNullOrEmpty(task.Result.URL))
                        {
                            string url = string.IsNullOrEmpty(task.Result.ShortenedURL) ? task.Result.URL : task.Result.ShortenedURL;

                            lvi.SubItems[8].Text = url;

                            if (Engine.ConfigWorkflow.ClipboardOverwrite)
                            {
                                ZAppHelper.CopyTextSafely(url);
                            }

                            if (Engine.ConfigOptions.HistorySave)
                            {
                                HistoryManager.AddHistoryItemAsync(Engine.HistoryPath, task.GenerateHistoryItem());
                            }
                        }

                        if (Engine.ConfigOptions.CompleteSound)
                        {
                            SystemSounds.Exclamation.Play();
                        }
                    }

                    lvi.EnsureVisible();
                }
            }
            finally
            {
                StartTasks();
                //  UpdateTrayIcon();
            }
        }
Esempio n. 14
0
 protected override void OnNewWorkerTask(WorkerTask workerTask, bool firstCreation)
 {
     workerTask.Updater.RefreshRate = 1;
     workerTask.SynchronizationType = EudiSynchronizationType.TrueMultiThreading;
 }
Esempio n. 15
0
 internal void OnDone()
 {
     task = null;
 }
        /// <summary>
        /// Sets Clipboard text and returns the content
        /// </summary>
        /// <returns></returns>
        public static string SetClipboardText(WorkerTask task, bool showDialog)
        {
            string clipboardText = "";

            switch (task.JobCategory)
            {
            case JobCategoryType.PICTURES:
            case JobCategoryType.SCREENSHOTS:
            case JobCategoryType.BINARY:
                ScreenshotsHistory = task.LinkManager;
                if (GraphicsMgr.IsValidImage(task.LocalFilePath))
                {
                    if (Engine.conf.ShowClipboardModeChooser || showDialog)
                    {
                        ClipboardOptions cmp = new ClipboardOptions(task);
                        cmp.Icon = Resources.zss_main;
                        if (showDialog)
                        {
                            cmp.ShowDialog();
                        }
                        else
                        {
                            cmp.Show();
                        }
                    }

                    if (task.MyImageUploader == ImageDestType.FILE)
                    {
                        clipboardText = task.LocalFilePath;
                    }
                    else
                    {
                        clipboardText = ScreenshotsHistory.GetUrlByType(Engine.conf.ClipboardUriMode).ToString().Trim();
                        if (task.MakeTinyURL)
                        {
                            string tinyUrl = ScreenshotsHistory.GetUrlByType(ClipboardUriType.FULL_TINYURL);
                            if (!string.IsNullOrEmpty(tinyUrl))
                            {
                                clipboardText = tinyUrl.Trim();
                            }
                        }
                    }
                }
                break;

            case JobCategoryType.TEXT:
                switch (task.Job)
                {
                case WorkerTask.Jobs.LANGUAGE_TRANSLATOR:
                    if (null != task.TranslationInfo)
                    {
                        clipboardText = task.TranslationInfo.Result.TranslatedText;
                    }
                    break;

                default:
                    if (!string.IsNullOrEmpty(task.RemoteFilePath))
                    {
                        clipboardText = task.RemoteFilePath;
                    }
                    else if (null != task.MyText)
                    {
                        clipboardText = task.MyText.LocalString;
                    }
                    else
                    {
                        clipboardText = task.LocalFilePath;
                    }
                    break;
                }
                break;
            }

            // after all this the clipboard text can be null

            if (!string.IsNullOrEmpty(clipboardText))
            {
                Engine.ClipboardUnhook();
                FileSystem.AppendDebug("Setting Clipboard with URL: " + clipboardText);
                Clipboard.SetText(clipboardText);

                // optional deletion link
                string linkdel = ScreenshotsHistory.GetDeletionLink();
                if (!string.IsNullOrEmpty(linkdel))
                {
                    FileSystem.AppendDebug("Deletion Link: " + linkdel);
                }

                Engine.zClipboardText = clipboardText;
                Engine.ClipboardHook();
            }
            return(clipboardText);
        }
Esempio n. 17
0
 public TaskManager(WorkerTask task)
 {
     this.mTask = task;
 }
Esempio n. 18
0
        /// <summary>
        /// Sets Clipboard text and returns the content
        /// </summary>
        /// <returns></returns>
        public static void ShowUploadResults(WorkerTask task, bool showDialog)
        {
            if (!task.WorkflowConfig.ClipboardOverwrite && !Clipboard.ContainsFileDropList() && !Clipboard.ContainsImage() && !Clipboard.ContainsText() || task.WorkflowConfig.ClipboardOverwrite)
            {
                if (task.UploadResults.Count > 0)
                {
                    if (task.WorkflowConfig.DestConfig.TaskClipboardContent.Count > 1 || Engine.ConfigUI.ShowUploadResultsWindow || showDialog)
                    {
                        ClipboardOptions cmp = new ClipboardOptions(task);
                        cmp.Icon = Resources.zss_main;
                        if (showDialog)
                        {
                            cmp.ShowDialog();
                        }
                        else
                        {
                            NativeMethods.ShowWindow(cmp.Handle, (int)WindowShowStyle.ShowNoActivate);
                        }
                        showDialog = true;
                    }
                }

                if (task.WorkflowConfig.DestConfig.Outputs.Contains(OutputEnum.Clipboard))
                {
                    StringBuilder clipboardText = new StringBuilder();

                    if (task.JobIsImageToClipboard())
                    {
                        Adapter.CopyImageToClipboard(task.TempImage, task.WorkflowConfig.ClipboardForceBmp);
                    }
                    else if (task.WorkflowConfig.DestConfig.TaskClipboardContent.Contains(ClipboardContentEnum.Local))
                    {
                        foreach (UploadResult ur in task.UploadResults)
                        {
                            if (Engine.ConfigUI.ConfLinkFormat.Count > 0)
                            {
                                clipboardText.AppendLine(ur.GetUrlByType((LinkFormatEnum)task.WorkflowConfig.DestConfig.LinkFormat[0], ur.LocalFilePath));
                            }

                            if (!Engine.ConfigUI.ClipboardAppendMultipleLinks && clipboardText.Length > 0)
                            {
                                break;
                            }
                        }
                    }
                    else if (task.WorkflowConfig.DestConfig.TaskClipboardContent.Contains(ClipboardContentEnum.OCR))
                    {
                        if (!string.IsNullOrEmpty(task.OCRText))
                        {
                            clipboardText.Append(task.OCRText);
                        }
                    }

                    // If the user requests for the full image URL, preference is given for the Shortened URL is exists
                    else if (task.Job1 == EDataType.Image && task.WorkflowConfig.DestConfig.LinkFormat.Contains((int)LinkFormatEnum.FULL))
                    {
                        if (task.Job3 == WorkerTask.JobLevel3.ShortenURL && !string.IsNullOrEmpty(task.UploadResults[0].ShortenedURL))
                        {
                            foreach (UploadResult ur in task.UploadResults)
                            {
                                if (!string.IsNullOrEmpty(ur.ShortenedURL))
                                {
                                    clipboardText.AppendLine(ur.ShortenedURL);
                                    if (!Engine.ConfigUI.ClipboardAppendMultipleLinks && clipboardText.Length > 0)
                                    {
                                        break;
                                    }
                                }
                            }
                        }
                        // If no shortened URL exists then default full URL will be used
                        else
                        {
                            foreach (UploadResult ur in task.UploadResults)
                            {
                                if (!string.IsNullOrEmpty(ur.URL))
                                {
                                    clipboardText.AppendLine(FileSystem.GetBrowserFriendlyUrl(ur.URL));
                                    if (!Engine.ConfigUI.ClipboardAppendMultipleLinks && clipboardText.Length > 0)
                                    {
                                        break;
                                    }
                                }
                            }
                            if (clipboardText.Length == 0 && task.WorkflowConfig.DestConfig.TaskClipboardContent.Contains(ClipboardContentEnum.Local))
                            {
                                foreach (UploadResult ur in task.UploadResults)
                                {
                                    if (!string.IsNullOrEmpty(ur.LocalFilePath))
                                    {
                                        clipboardText.AppendLine(ur.LocalFilePath);
                                        if (!Engine.ConfigUI.ClipboardAppendMultipleLinks && clipboardText.Length > 0)
                                        {
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                    }

                    else
                    {
                        // From this point onwards app needs to respect all other Clipboard URL modes for Images
                        if (task.UploadResults.Count > 0 && task.Job1 == EDataType.Image)
                        {
                            foreach (UploadResult ur in task.UploadResults)
                            {
                                if (task.WorkflowConfig.DestConfig.LinkFormat.Count > 0)
                                {
                                    clipboardText.AppendLine(ur.GetUrlByType((LinkFormatEnum)task.WorkflowConfig.DestConfig.LinkFormat[0], ur.URL));
                                }

                                if (!Engine.ConfigUI.ClipboardAppendMultipleLinks && clipboardText.Length > 0)
                                {
                                    break;
                                }
                            }
                        }
                        // Text and File catagories are still left to process. Exception for Google Translate
                        else if (task.Job1 == EDataType.Text && task.Job2 == WorkerTask.JobLevel2.Translate)
                        {
                            if (task.TranslationInfo != null)
                            {
                                clipboardText.AppendLine(task.TranslationInfo.Result);
                            }
                        }
                        // Text and File catagories are still left to process. If shortened URL exists, preference is given to that
                        else if (task.UploadResults.Count > 0 && task.Job3 == WorkerTask.JobLevel3.ShortenURL && !string.IsNullOrEmpty(task.UploadResults[0].ShortenedURL))
                        {
                            foreach (UploadResult ur in task.UploadResults)
                            {
                                if (!string.IsNullOrEmpty(ur.ShortenedURL))
                                {
                                    clipboardText.AppendLine(ur.ShortenedURL);
                                    break;
                                }
                            }
                        }
                        // Otherwise full URL for Text or File is used
                        else if (task.UploadResults.Count > 0)
                        {
                            clipboardText.AppendLine(FileSystem.GetBrowserFriendlyUrl(task.UploadResults[0].URL));
                        }
                    }

                    if (clipboardText.Length > 0)
                    {
                        bool bClipboardFormatOnLongUrl = Engine.ConfigUI.EnableClipboardFormatForLongURLs && task.Job1 == EDataType.URL;
                        bool bClipboardFormat          = bClipboardFormatOnLongUrl || task.Job1 != EDataType.URL;
                        var  np = new NameParser(NameParserType.Clipboard)
                        {
                            Link     = clipboardText.ToString().Trim(),
                            FileSize = task.Info.FileSize,
                            FileName = task.Info.FileName
                        };
                        if (bClipboardFormat)
                        {
                            np.WindowText = task.Info.WindowTitleText;
                        }

                        string tempText = bClipboardFormat ? np.Convert(Engine.ConfigUI.ClipboardFormat) : clipboardText.ToString().Trim();

                        if (!string.IsNullOrEmpty(tempText))
                        {
                            DebugHelper.WriteLine("Setting Clipboard with URL: " + tempText);
                            Clipboard.SetText(tempText); // auto
                            Engine.zPreviousSetClipboardText = tempText;
                            Engine.IsClipboardUploading      = false;

                            // optional deletion link
                            if (task.UploadResults != null)
                            {
                                foreach (UploadResult ur in task.UploadResults)
                                {
                                    string linkdel = ur.DeletionURL;
                                    if (!string.IsNullOrEmpty(linkdel))
                                    {
                                        DebugHelper.WriteLine("Deletion Link: " + linkdel);
                                    }
                                }
                            }
                        }
                    }
                }

                if (!showDialog)
                {
                    task.Dispose();
                }
            }
        }
Esempio n. 19
0
 /// <summary>
 /// Start the background operation.
 /// </summary>
 /// <exception cref="InvalidOperationException">When <see cref="IsBusy"/> is true.</exception>
 public void RunWorkerAsync(object argument)
 {
     if (IsBusy)
         throw new InvalidOperationException();
     task = new WorkerTask(this, argument);
 }
Esempio n. 20
0
        public string ShowBalloonTip(WorkerTask task)
        {
            StringBuilder sbMsg = new StringBuilder();
            ToolTipIcon   tti   = ToolTipIcon.Info;

            if (task.Job2 == WorkerTask.JobLevel2.Translate)
            {
                sbMsg.AppendLine(task.TranslationInfo.SourceLanguage + " -> " + task.TranslationInfo.TargetLanguage);
                sbMsg.AppendLine("Text: " + task.TranslationInfo.Text);
                sbMsg.AppendLine("Result: " + task.TranslationInfo.Result);
            }
            else
            {
                sbMsg.AppendLine("Name: " + task.GetDescription());

                switch (task.Job1)
                {
                case EDataType.Text:
                    string dest = string.Empty;
                    switch (task.Job3)
                    {
                    case WorkerTask.JobLevel3.ShortenURL:
                        dest = task.WorkflowConfig.DestConfig.ToStringLinkUploaders();
                        break;

                    default:
                        dest = task.WorkflowConfig.DestConfig.ToStringTextUploaders();
                        break;
                    }
                    sbMsg.AppendLine(string.Format("Destination: {0}", dest));
                    break;

                default:
                    sbMsg.Append("Outputs: ");
                    sbMsg.AppendLine(task.WorkflowConfig.DestConfig.ToStringOutputs());
                    break;
                }

                foreach (UploadResult ur in task.UploadResults)
                {
                    if (!string.IsNullOrEmpty(ur.URL))
                    {
                        sbMsg.AppendLine(ur.URL);
                        break;
                    }
                }

                if (task.UploadResults.Count == 0 && task.IsError)
                {
                    tti = ToolTipIcon.Warning;
                    sbMsg.AppendLine("Warnings: ");
                    foreach (string err in task.Errors)
                    {
                        sbMsg.AppendLine(err);
                    }
                }

                if (Engine.ConfigOptions.ShowUploadDuration && task.UploadDuration > 0)
                {
                    sbMsg.AppendLine("Upload duration: " + task.UploadDuration + " ms");
                }
            }

            string message = sbMsg.ToString();

            if (!string.IsNullOrEmpty(message))
            {
                niTray.ShowBalloonTip(1000, Application.ProductName, message, tti);
            }

            return(message);
        }
Esempio n. 21
0
        private async Task ExecuteNextTask(IServiceProvider scopedServiceProvider)
        {
            var        workerTasksData = scopedServiceProvider.GetService <IWorkerTasksDataService>();
            WorkerTask workerTask;

            try
            {
                workerTask = workerTasksData.GetForProcessing();
            }
            catch (Exception ex)
            {
                this.logger.LogCritical($"Unable to get task for processing. Error: {ex}");
                await Task.Delay(WaitTimeOnErrorInSeconds * 1000);

                return;
            }

            if (workerTask == null)
            {
                // No task available.
                return;
            }

            if (!TasksIds.TryAdd(workerTask.Id, true))
            {
                // Other thread is processing the same task.
                return;
            }

            try
            {
                workerTask.Processing = true;
                await workerTasksData.UpdateAsync(workerTask);
            }
            catch (Exception ex)
            {
                TasksIds.TryRemove(workerTask.Id, out _);
                this.logger.LogError($"Unable to set workerTask.{nameof(WorkerTask.Processing)} to true! Error: {ex}");
                await Task.Delay(WaitTimeOnErrorInSeconds * 1000);

                return;
            }

            this.logger.LogInformation($"Task #{workerTask.Id} started with parameters: {workerTask.Parameters}");

            ITask task = null;

            try
            {
                task = this.GetTaskInstance(workerTask.TypeName, scopedServiceProvider);
            }
            catch (Exception ex)
            {
                this.logger.LogError($"Exception in {nameof(this.GetTaskInstance)} on task #{workerTask.Id}: {ex}");
                workerTask.ProcessingComment = $"Error in {nameof(this.GetTaskInstance)}: {ex}";
            }

            if (task == null)
            {
                try
                {
                    workerTask.Processed  = true;
                    workerTask.Processing = false;
                    await workerTasksData.UpdateAsync(workerTask);

                    TasksIds.TryRemove(workerTask.Id, out _);
                }
                catch (Exception ex)
                {
                    this.logger.LogError($"Unable to save final changes on task #{workerTask.Id}! Error: {ex}");
                    await Task.Delay(WaitTimeOnErrorInSeconds * 1000);
                }

                return;
            }

            // Call DoWork()
            string result          = null;
            var    doWorkStopwatch = Stopwatch.StartNew();

            try
            {
                result = await task.DoWork(workerTask.Parameters);

                doWorkStopwatch.Stop();
                this.logger.LogInformation(
                    $"Task #{workerTask.Id} completed in {doWorkStopwatch.Elapsed} ({DateTime.UtcNow}) with result: {result}");
            }
            catch (Exception ex)
            {
                this.logger.LogError($"Error in {nameof(ITask.DoWork)} on task #{workerTask.Id}: {ex}");
                workerTask.ProcessingComment = $"Error in {nameof(ITask.DoWork)}: {ex}";
            }

            // Call Recreate()
            WorkerTask nextTask = null;

            try
            {
                nextTask = task.Recreate(workerTask);
            }
            catch (Exception ex)
            {
                this.logger.LogError($"Error in {nameof(ITask.Recreate)} on task #{workerTask.Id}: {ex}");
                workerTask.ProcessingComment += $"Error in {nameof(ITask.Recreate)}: {ex}";
            }

            // Save result
            try
            {
                workerTask.Result   = result;
                workerTask.Duration = doWorkStopwatch.Elapsed.TotalDays >= 1.0
                                          ? new TimeSpan(0, 23, 59, 59)
                                          : doWorkStopwatch.Elapsed;
                workerTask.Processed  = true;
                workerTask.Processing = false;
                await workerTasksData.UpdateAsync(workerTask);

                TasksIds.TryRemove(workerTask.Id, out _);
            }
            catch (Exception ex)
            {
                this.logger.LogError($"Unable to save result on task #{workerTask.Id}! Error: {ex}");
                await Task.Delay(WaitTimeOnErrorInSeconds * 1000);

                return;
            }

            // Save the new task
            if (nextTask != null)
            {
                try
                {
                    await workerTasksData.AddAsync(nextTask);
                }
                catch (Exception ex)
                {
                    this.logger.LogError($"Unable to recreate task #{workerTask.Id}! Error: {ex}");
                    await Task.Delay(WaitTimeOnErrorInSeconds * 1000);
                }
            }
        }
Esempio n. 22
0
        public async Task CreatedTask(string message)
        {
            var createdTask = JsonConvert.DeserializeObject <TaskCreation>(message);

            using (var applicationDbContext = ApplicationDbContext.FromConnectionString(_config))
            {
                var username = Context.User.FindFirstValue(ClaimTypes.NameIdentifier);
                var user     = await applicationDbContext.Users.Where(x => x.NormalizedEmail == username.ToUpper())
                               .Select(x => new { x.Id, x.Credits })
                               .FirstOrDefaultAsync();

                if (user.Credits <= 0)
                {
                    var error = new CannotCreateTask
                    {
                        Reason = "Insufficient credits."
                    };
                    await Clients.Caller.SendAsync("CannotCreateTask", JsonConvert.SerializeObject(error));

                    return;
                }

                var userId = user.Id;

                var dbRequestorTask = new RequestorTask
                {
                    RequestorId = userId,
                    WasmB64     = createdTask.WasmB64,
                    WorkerTasks = new List <WorkerTask>()
                };
#if DEBUG
                var allConnections = await applicationDbContext.Workers
                                     .Where(x => x.ConnexionId != null)
                                     .OrderBy(x => Guid.NewGuid())
                                     .ToDictionaryAsync(x => x.ConnexionId, x => new { WorkerId = x.Id, x.UserId });
#else
                var allConnections = await applicationDbContext.Workers
                                     .Where(x => x.ConnexionId != null && x.UserId != userId)
                                     .OrderBy(x => Guid.NewGuid())
                                     .ToDictionaryAsync(x => x.ConnexionId, x => new { WorkerId = x.Id, x.UserId });
#endif
                var i = 0;
                Dictionary <string, string> tasksToSend = new Dictionary <string, string>();

                foreach (var conn in allConnections)
                {
                    var workerTask = new WorkerTask
                    {
                        Parameter  = i,
                        ProviderId = conn.Value.UserId,
                        WorkerId   = conn.Value.WorkerId
                    };
                    dbRequestorTask.WorkerTasks.Add(workerTask);
                    var response = new ReceivedTask
                    {
                        Parameter      = i,
                        WasmB64        = createdTask.WasmB64,
                        TaskId         = workerTask.Id,
                        SubTaskTimeout = 3600000
                    };
                    tasksToSend.Add(conn.Key, JsonConvert.SerializeObject(response));
                    i++;
                    if (i == createdTask.NumberOfNodes)
                    {
                        break;
                    }
                }

                if (tasksToSend.Count < createdTask.NumberOfNodes)
                {
                    var error = new CannotCreateTask
                    {
                        Reason = "Not enough nodes."
                    };
                    await Clients.Caller.SendAsync("CannotCreateTask", JsonConvert.SerializeObject(error));

                    return;
                }

                applicationDbContext.RequestorTasks.Add(dbRequestorTask);
                await applicationDbContext.SaveChangesAsync();

                foreach (var task in tasksToSend)
                {
                    await Clients.Client(task.Key).SendAsync("NewTask", task.Value);
                }

                await SendNewStatisicsInternal(username.ToUpper(), true);
            }
        }
Esempio n. 23
0
		internal void OnDone() 
		{
			task = null;
		}
Esempio n. 24
0
        private static void Main(string[] args)
        {
            string dirImages         = string.Empty;
            string dirRoot           = string.Empty;
            string mSettingsFilePath = string.Empty;
            string dirTorrents       = string.Empty;

            bool mFileCollection = false;
            bool mShowHelp       = false;

            var p = new OptionSet()
            {
                { "c", "Treat multiple files as a collection", v => mFileCollection = v != null },
                { "m|media=", "Location of the media file/folder", v => mMediaLoc = v },
                { "o|options=", "Location of the settings file", v => mSettingsFilePath = v },
                { "rd=", "Root directory for screenshots, torrent and all other output files. Overrides all other custom folders.", v => dirRoot = v },
                { "s", "Create screenshots", v => mScreenshotsCreate = v != null },
                { "sd=", "Create screenshots in a custom folder and upload", v => dirImages = v },
                { "t", "Create torrent file in the parent folder of the media file", v => mTorrentCreate = v != null },
                { "td=", "Create torrent file in a custom folder", v => dirTorrents = v },
                { "u", "Upload screenshots", v => mScreenshotsUpload = v != null },
                { "x|xml", "Folder path of the XML torrent description file", v => mXmlCreate = v != null },
                { "h|help", "Show this message and exit", v => mShowHelp = v != null }
            };

            if (args.Length == 0)
            {
                mShowHelp = true;
            }

            // give cli the ability to replace environment variables
            string[] args2 = new string[args.Length];
            int      count = 0;

            foreach (string arg in args)
            {
                args2[count++] = arg.Replace("%appdata%", Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData));
            }

            try
            {
                p.Parse(args2);

                // set root folder for images or set images dir if set one
                mScreenshotDir = Directory.Exists(dirRoot) ? dirRoot : dirImages;

                // set root folder for torrents or set torrents dir if set one
                mTorrentsDir = Directory.Exists(dirRoot) ? dirRoot : dirTorrents;
            }
            catch (Exception ex)
            {
                Console.Write("tdmakercli: ");
                Console.WriteLine(ex.Message);
                Console.WriteLine("Try 'tdmakercli --help' for more information.");
                return;
            }

            if (mShowHelp)
            {
                ShowHelp(p);
                return;
            }

            if (!File.Exists(mSettingsFilePath))
            {
                mSettingsFilePath = App.SettingsFilePath;
            }

            if (File.Exists(mSettingsFilePath))
            {
                App.Settings        = Settings.Load(mSettingsFilePath);
                App.UploadersConfig = UploadersConfig.Load(App.UploadersConfigPath);
            }

            if (App.Settings != null)
            {
                App.InitializeDefaultFolderPaths();

                List <string> listFileOrDir = new List <string>()
                {
                    mMediaLoc
                };
                MediaWizardOptions mwo = Adapter.GetMediaType(listFileOrDir, true);
                if (mwo.MediaTypeChoice == MediaType.MediaIndiv && mFileCollection)
                {
                    mwo.MediaTypeChoice = MediaType.MediaCollection;
                }

                TaskSettings ts = new TaskSettings();
                ts.MediaOptions.CreateScreenshots = mScreenshotsCreate;
                ts.MediaOptions.UploadScreenshots = mScreenshotsUpload;

                WorkerTask task = new WorkerTask(ts);
                MediaInfo2 mi   = new MediaInfo2(mwo, mMediaLoc);
                mi.ReadMedia();

                if (mScreenshotsUpload)
                {
                    TakeScreenshots(task);
                    task.UploadScreenshots();
                }
                else if (mScreenshotsCreate)
                {
                    TakeScreenshots(task);
                }

                //  CreatePublish(ti);
                //  CreateTorrent(ti);
            }
        }
        public override void CaptureEntireScreen()
        {
            WorkerTask hkesTask = CreateTask(WorkerTask.JobLevel2.CaptureEntireScreen);

            RunWorkerAsync(hkesTask);
        }
Esempio n. 26
0
        private void AnalyzeMedia(List <string> files)
        {
            if (!ValidateInput())
            {
                return;
            }

            DialogResult        dlgResult        = DialogResult.OK;
            List <TaskSettings> taskSettingsList = new List <TaskSettings>();

            MediaWizardOptions mo = Adapter.GetMediaType(files);

            if (mo.ShowWizard)
            {
                ShowMediaWizard(ref mo, files);
            }

            if (mo.PromptShown)
            {
                dlgResult = mo.DialogResult;
            }
            else
            {
                // fill previous settings
                mo.CreateTorrent     = App.Settings.ProfileActive.CreateTorrent;
                mo.CreateScreenshots = App.Settings.ProfileActive.CreateScreenshots;
                mo.UploadScreenshots = App.Settings.ProfileActive.UploadScreenshots;
            }

            if (!mo.PromptShown && App.Settings.ShowMediaWizardAlways)
            {
                MediaWizard mw = new MediaWizard(files);
                dlgResult = mw.ShowDialog();
                if (dlgResult == DialogResult.OK)
                {
                    mo = mw.Options;
                }
            }

            if (dlgResult == DialogResult.OK)
            {
                if (mo.MediaTypeChoice == MediaType.MediaCollection)
                {
                    TaskSettings ts = new TaskSettings();
                    ts.MediaOptions = mo;

                    files.Sort();
                    string firstPath = files[0];
                    PrepareNewMedia(ts, File.Exists(firstPath) ? Path.GetDirectoryName(files[0]) : firstPath);
                    foreach (string p in files)
                    {
                        if (File.Exists(p))
                        {
                            ts.Media.FileCollection.Add(p);
                        }
                    }
                    taskSettingsList.Add(ts);
                }
                else
                {
                    foreach (string fd in files)
                    {
                        if (File.Exists(fd) || Directory.Exists(fd))
                        {
                            TaskSettings ts = new TaskSettings();
                            ts.MediaOptions = mo;

                            PrepareNewMedia(ts, fd);
                            ts.Media.DiscType = MediaHelper.GetSourceType(fd);

                            if (ts.Media.DiscType == SourceType.Bluray)
                            {
                                ts.Media.Overall         = new MediaFile(FileSystemHelper.GetLargestFilePathFromDir(fd), cboSource.Text);
                                ts.Media.Overall.Summary = BDInfo(fd);
                            }

                            if (!string.IsNullOrEmpty(txtTitle.Text))
                            {
                                ts.Media.SetTitle(txtTitle.Text);
                            }

                            taskSettingsList.Add(ts);
                        }
                    }
                }

                foreach (TaskSettings ts in taskSettingsList)
                {
                    WorkerTask task = WorkerTask.CreateTask(ts);
                    task.UploadProgressChanged  += Task_UploadProgressChanged;
                    task.MediaLoaded            += Task_MediaLoaded;
                    task.StatusChanged          += Task_StatusChanged;
                    task.ScreenshotUploaded     += Task_ScreenshotUploaded;
                    task.TorrentInfoCreated     += Task_TorrentInfoCreated;
                    task.TorrentProgressChanged += Task_TorrentProgressChanged;
                    task.TaskCompleted          += Task_TaskCompleted;
                    TaskManager.Start(task);
                }

                UpdateGuiControls();
                pBar.Value = 0;
            }
        }
        public override void CaptureSelectedWindow()
        {
            WorkerTask hkswTask = CreateTask(WorkerTask.JobLevel2.CaptureSelectedWindow);

            RunWorkerAsync(hkswTask);
        }
Esempio n. 28
0
 private void Task_TorrentProgressChanged(WorkerTask task)
 {
     pBar.Value = (int)task.Info.TorrentProgress;
 }
        public override void CaptureRectRegionLast()
        {
            WorkerTask hkrclTask = CreateTask(WorkerTask.JobLevel2.CaptureLastCroppedWindow);

            RunWorkerAsync(hkrclTask);
        }
Esempio n. 30
0
 private void Task_UploadProgressChanged(WorkerTask task)
 {
     pBar.Value = TaskManager.GetAverageProgress();
 }
        public bool UploadUsingFileSystem(params string[] fileList)
        {
            List <string> strListFilePath = new List <string>();
            bool          succ            = true;

            foreach (string fp in fileList)
            {
                try
                {
                    if (!string.IsNullOrEmpty(fp) && File.Exists(fp))
                    {
                        if (HelpersLib.GraphicsHelper.Core.IsValidImage(fp))
                        {
                            string dirfp = Path.GetDirectoryName(fp);
                            string fsfp  = FileSystem.GetUniqueFilePath(Engine.ConfigWorkflow, Engine.ImagesDir, Path.GetFileName(fp));
                            if (fp != fsfp && dirfp != Engine.ImagesDir)
                            {
                                string dir = Path.GetDirectoryName(fsfp);
                                if (!Directory.Exists(dir))
                                {
                                    Directory.CreateDirectory(dir);
                                }
                                try
                                {
                                    File.Copy(fp, fsfp, true);
                                    if (Path.GetDirectoryName(fp) == Engine.ConfigUI.FolderMonitorPath)
                                    {
                                        File.Delete(fp);
                                    }
                                }
                                catch (Exception e)
                                {
                                    fsfp = fp;
                                    DebugHelper.WriteException(e);
                                }
                                strListFilePath.Add(fsfp);
                            }
                            else
                            {
                                strListFilePath.Add(fp);
                            }
                        }
                        else
                        {
                            strListFilePath.Add(fp); // yes we use the orignal file path
                        }
                    }
                }
                catch (Exception ex)
                {
                    DebugHelper.WriteException(ex, "Error while uploading using file system");
                    succ = false;
                }
            }

            strListFilePath.Sort();
            List <Image> tempImages = new List <Image>();
            bool         bCreateAni = strListFilePath.Count > 1 && strListFilePath.Count < Engine.ConfigWorkflow.ImageAnimatedFramesMax && HelpersLib.GraphicsHelper.Core.HasIdenticalImages(strListFilePath, out tempImages);

            if (bCreateAni)
            {
                WorkerTask agifTask = CreateTask(WorkerTask.JobLevel2.UploadFromExplorer);
                agifTask.SetImages(tempImages);
                agifTask.RunWorker();
            }
            else
            {
                foreach (string fp in strListFilePath)
                {
                    var tifs = new TaskInfo()
                    {
                        ExistingFilePath = fp
                    };
                    var fpdataTask = CreateTask(WorkerTask.JobLevel2.UploadFromExplorer, tifs);
                    fpdataTask.UpdateLocalFilePath(fp);
                    fpdataTask.RunWorker();
                }
            }
            return(succ);
        }
Esempio n. 32
0
 private void Task_StatusChanged(WorkerTask task)
 {
     sBar.Text = task.Info.Status;
 }
        public override void BwApp_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            switch ((WorkerTask.ProgressType)e.ProgressPercentage)
            {
            case WorkerTask.ProgressType.PrintImage:
                Adapter.PrintImage(e.UserState as Image);
                break;

            case WorkerTask.ProgressType.PrintText:
                Adapter.PrintText(e.UserState as string);
                break;

            case (WorkerTask.ProgressType) 102:
                throw new Exception("Unsupported progress");

            case (WorkerTask.ProgressType) 103:
                throw new Exception("Unsupported progress");

            case (WorkerTask.ProgressType) 104:
                Adapter.CopyDataToClipboard(e.UserState);
                break;

            case WorkerTask.ProgressType.CopyToClipboardImage:
                if (e.UserState.GetType() == typeof(string))
                {
                    Adapter.CopyImageToClipboard(e.UserState as string);
                }
                else if (e.UserState is Image)
                {
                    Adapter.CopyImageToClipboard((Image)e.UserState, false);
                }

                break;

            case WorkerTask.ProgressType.FlashIcon:
                Adapter.FlashNotifyIcon(this.niTray, e.UserState as Icon);
                break;

            case WorkerTask.ProgressType.UpdateCropMode:
                this.cboCropGridMode.Checked = Engine.ConfigUI.CropGridToggle;
                break;

            case WorkerTask.ProgressType.ChangeTrayIconProgress:
                UploadManager.SetCumulativePercentatge((int)((ProgressManager)e.UserState).Percentage);
                Adapter.UpdateNotifyIconProgress(this.niTray, UploadManager.CumulativePercentage);
                Adapter.TaskbarSetProgressValue(this, UploadManager.CumulativePercentage);
                this.Text = string.Format("{0}% - {1}", UploadManager.CumulativePercentage, Engine.GetProductName());
                break;

            case WorkerTask.ProgressType.UpdateProgressMax:
                TaskbarProgressBarState tbps = (TaskbarProgressBarState)e.UserState;
                Adapter.TaskbarSetProgressState(this, tbps);
                break;

            case WorkerTask.ProgressType.ShowBalloonTip:
                WorkerTask task = e.UserState as WorkerTask;
                if (Engine.ConfigOptions.ShowBalloonTip)
                {
                    ShowBalloonTip(task);
                }
                break;

            case WorkerTask.ProgressType.ShowTrayWarning:
                Adapter.TaskbarSetProgressValue(this, 33);
                Adapter.TaskbarSetProgressState(this, TaskbarProgressBarState.Error);
                Adapter.SetNotifyIconBalloonTip(this.niTray, this.Text, e.UserState as string, ToolTipIcon.Warning);
                break;
            }

            rtbDebugLog.Text = Engine.EngineLogger.ToString();
        }
Esempio n. 34
0
        public void ParallelForEachExceptionTest()
        {
            ExceptionCollector ec = new ExceptionCollector();

            AsyncQueue <int> q1 = new AsyncQueue <int>(5);

            Func <Task> t1 = async delegate()
            {
                for (int i = 0; i < 100; ++i)
                {
                    await q1.Enqueue(i, ec.CancellationToken);
                }
                q1.WriteEof();
            };

            AsyncQueue <int> q2 = new AsyncQueue <int>(5);

            Func <Task> t2 = WorkerTask.ForEach
                             (
                q1,
                async delegate(ForEachInfo <int> fi)
            {
                await q2.Enqueue(fi.Item * 100, fi.CancellationToken);
                if (fi.Item == 53)
                {
                    throw new InvalidOperationException("test 1");
                }
            },
                delegate()
            {
                q2.WriteEof();
                return(Task.CompletedTask);
            },
                ec
                             );

            List <int> items = new List <int>();

            Func <Task> t3 = WorkerTask.ForEach
                             (
                q2,
                delegate(ForEachInfo <int> fi)
            {
                items.Add(fi.Item);
                return(Task.CompletedTask);
            },
                delegate()
            {
                return(Task.CompletedTask);
            },
                ec
                             );

            Task T1 = Task.Run(t1);
            Task T2 = Task.Run(t2);
            Task T3 = Task.Run(t3);

            bool threwException = false;

            try
            {
                ec.WaitAll(T1, T2, T3);
            }
            catch (Exception exc)
            {
                System.Diagnostics.Debug.WriteLine(exc);
                threwException = true;
            }

            Assert.IsTrue(threwException);
        }
 public void CalculationBegin(WorkerTask task)
 {
     _free = false;
     _thread = new Thread(() => ExecuteInThread(task));
     _thread.Start();
 }
Esempio n. 36
0
        public void ParallelMultiSourceForEachTest()
        {
            object rSyncRoot = new object();
            Random r         = new Random((int)((System.Diagnostics.Stopwatch.GetTimestamp() >> 3) & 0x7FFFFFFF));

            ExceptionCollector ec = new ExceptionCollector();

            AsyncQueue <int> q1 = new AsyncQueue <int>(5);

            Func <Task> t1 = async delegate()
            {
                for (int i = 0; i < 100; ++i)
                {
                    await q1.Enqueue(i, ec.CancellationToken);
                }
                q1.WriteEof();
            };

            AsyncQueue <int> q2 = new AsyncQueue <int>(5);

            Func <Task> t2 = async delegate()
            {
                for (int i = 100; i < 200; ++i)
                {
                    await q2.Enqueue(i, ec.CancellationToken);
                }
                q2.WriteEof();
            };

            AsyncQueue <int> q3 = new AsyncQueue <int>(5);

            ParallelWorker pw = new ParallelWorker(8);

            Func <Task> t3 = WorkerTask.ParallelForEach
                             (
                new IQueueSource <int>[] { q1, q2 },
                InputPriorities.RoundRobin,
                pw,
                async fei =>
            {
                await q3.Enqueue(fei.Item, fei.CancellationToken);

                int time;
                lock (rSyncRoot)
                {
                    time = 100 + r.Next(800);
                }
                await Task.Delay(time);
            },
                () =>
            {
                q3.WriteEof();
                return(Task.CompletedTask);
            },
                ec
                             );

            Func <Task> t4 = WorkerTask.ForEach
                             (
                q3,
                fei =>
            {
                System.Diagnostics.Debug.WriteLine(fei.Item);
                return(Task.CompletedTask);
            },
                null,
                ec
                             );

            Task T1 = Task.Run(t1);
            Task T2 = Task.Run(t2);
            Task T3 = Task.Run(t3);
            Task T4 = Task.Run(t4);

            ec.WaitAll(T1, T2, T3, T4);
        }
Esempio n. 37
0
 protected override WorkerTask Recreate(WorkerTask currentTask, Input currentParameters, Output currentResult) =>
 new WorkerTask(currentTask, DateTime.UtcNow.AddDays(7).Date.AddHours(4));
 public void LogTaskRefusedAsync(WorkerTask task, Guid poolId)
 {
     throw new NotImplementedException();
 }
Esempio n. 39
0
        public void ParallelForEachTest()
        {
            object rSyncRoot = new object();
            Random r         = new Random((int)((System.Diagnostics.Stopwatch.GetTimestamp() >> 3) & 0x7FFFFFFF));

            ExceptionCollector ec = new ExceptionCollector();

            AsyncQueue <int> q1 = new AsyncQueue <int>(5);

            Func <Task> t1 = async delegate()
            {
                for (int i = 0; i < 100; ++i)
                {
                    await q1.Enqueue(r.Next(1000), ec.CancellationToken);
                }
                q1.WriteEof();
            };

            AsyncQueue <int> q2 = new AsyncQueue <int>(5);

            ParallelWorker pw = new ParallelWorker(8);

            Func <Task> t2 = WorkerTask.ParallelForEach
                             (
                q1,
                pw,
                async delegate(ForEachInfo <int> fi)
            {
                await q2.Enqueue(fi.Item * 100, fi.CancellationToken);

                int time;
                lock (rSyncRoot)
                {
                    time = 100 + r.Next(800);
                }
                await Task.Delay(time);
            },
                delegate()
            {
                q2.WriteEof();
                return(Task.CompletedTask);
            },
                ec
                             );

            List <int> items = new List <int>();

            Func <Task> t3 = WorkerTask.ForEach
                             (
                q2,
                delegate(ForEachInfo <int> fi)
            {
                items.Add(fi.Item);
                System.Diagnostics.Debug.WriteLine(fi.Item);
                return(Task.CompletedTask);
            },
                delegate()
            {
                return(Task.CompletedTask);
            },
                ec
                             );

            Task T1 = Task.Run(t1);
            Task T2 = Task.Run(t2);
            Task T3 = Task.Run(t3);

            Task.WaitAll(T1, T2, T3);

            Assert.AreEqual(0, ec.Exceptions.Count);
            Assert.AreEqual(100, items.Count);
        }
Esempio n. 40
0
 private static void task_UploadPreparing(WorkerTask info)
 {
     Engine.EngineLogger.WriteLine("Upload preparing. ID: {0}", info.Id);
     ChangeListViewItemStatus(info);
 }
Esempio n. 41
0
        public void MultiSourceForEachExceptionTest()
        {
            ExceptionCollector ec = new ExceptionCollector();

            AsyncQueue <int> q1 = new AsyncQueue <int>(5);

            Func <Task> t1 = async delegate()
            {
                for (int i = 0; i < 100; ++i)
                {
                    await q1.Enqueue(i, ec.CancellationToken);
                }
                q1.WriteEof();
            };

            AsyncQueue <int> q2 = new AsyncQueue <int>(5);

            Func <Task> t2 = async delegate()
            {
                for (int i = 100; i < 200; ++i)
                {
                    await q2.Enqueue(i, ec.CancellationToken);
                }
                q2.WriteEof();
            };

            AsyncQueue <int> q3 = new AsyncQueue <int>(5);

            Func <Task> t3 = WorkerTask.ForEach
                             (
                new IQueueSource <int>[] { q1, q2 },
                InputPriorities.RoundRobin,
                async fei =>
            {
                if (fei.Item == 133)
                {
                    throw new InvalidOperationException("test");
                }
                await q3.Enqueue(fei.Item, fei.CancellationToken);
            },
                () =>
            {
                q3.WriteEof();
                return(Task.CompletedTask);
            },
                ec
                             );

            Func <Task> t4 = WorkerTask.ForEach
                             (
                q3,
                fei =>
            {
                System.Diagnostics.Debug.WriteLine(fei.Item);
                return(Task.CompletedTask);
            },
                null,
                ec
                             );

            Task T1 = Task.Run(t1);
            Task T2 = Task.Run(t2);
            Task T3 = Task.Run(t3);
            Task T4 = Task.Run(t4);

            try
            {
                ec.WaitAll(T1, T2, T3, T4);
            }
            catch (Exception exc)
            {
                System.Diagnostics.Debug.WriteLine(exc);
            }
        }
Esempio n. 42
0
    public void SetTask(GameObject selectedTaskObject)
    {
        var tree = selectedTaskObject.GetComponent<ChristmasTree>();
        var wareHouse = selectedTaskObject.GetComponent<Warehouse>();

        if(tree != null)
        {

            //Debug.Log("ChristmasTree!");

            currentTask = WorkerTask.Lumberjack;

            // Official statement: Please note that this function is very slow. It is not recommended to use this function every frame.
            // In most cases you can use the singleton pattern instead. So what its saying is that I should be manually registering objects. F that!
            //Warehouse[] ob = FindObjectsOfType(typeof(Warehouse)) as Warehouse[];
            //Warehouse nearestWareHouse = null;
            //foreach(var o in ob)
            //{
            //	if(nearestWareHouse == null)
            //	{
            //		nearestWareHouse = o;
            //	}
            //	else if(Vector3.Distance(o.transform.position, this.transform.position) <
            //		Vector3.Distance(nearestWareHouse.transform.position, this.transform.position))
            //	{
            //		nearestWareHouse = o;
            //	}
            //}

            Warehouse nearestWareHouse = RTSUnitQueryCollection.FindNearestObjectOfType<Warehouse>(this.transform.gameObject);

            // find nearest warehouse

            woodChopping = null; // hopefully this will dispose of the object? It doesn't have any unmanaged res.
            woodChopping = new ChoppingWoodState(tree, nearestWareHouse, this.gameObject);
        }

        if(wareHouse != null)
        {
            currentTask = WorkerTask.Lumberjack;
            ChristmasTree nearestTree = RTSUnitQueryCollection.FindNearestObjectOfType<ChristmasTree>(this.transform.gameObject);

            woodChopping = null;
            woodChopping = new ChoppingWoodState(nearestTree, wareHouse, this.gameObject);
        }
    }
Esempio n. 43
0
 public WorkerTaskInfo(WorkerTask task, int index)
 {
     this.task = task;
     roomTaskIndex = index;
 }
Esempio n. 44
0
 //set base condition to null, so that we may move into idle state.
 public void SetTask(Vector3 moveTo, int unitsCount, int i, WorkerTask taskContext = WorkerTask.Idle)
 {
     currentTask = taskContext;
     MoveTo(moveTo, unitsCount, i);
 }
 public void LogTaskDoneAsync(WorkerTask task, Guid workerId, Guid poolId)
 {
     throw new NotImplementedException();
 }
Esempio n. 46
0
 protected override WorkerTask Recreate(WorkerTask currentTask, Input currentParameters, Output currentResult)
 {
     currentParameters.LastId = currentResult.LastId;
     return(new WorkerTask(currentTask, JsonConvert.SerializeObject(currentParameters), DateTime.UtcNow.AddHours(1)));
 }