コード例 #1
0
        public void SerializationBinary()
        {
            var exception0 = new Exception("First exception");
              var exception1 = new Exception("Second exception");
              var exception = new TaskException(new[] { exception0, exception1 });

              const string fileName = "SerializationTaskException.bin";
              if (File.Exists(fileName))
            File.Delete(fileName);

              var fileStream = new FileStream(fileName, FileMode.Create);

              var formatter = new BinaryFormatter();
              formatter.Serialize(fileStream, exception);
              fileStream.Close();

              fileStream = new FileStream(fileName, FileMode.Open);
              formatter = new BinaryFormatter();
              var deserializedException = (TaskException)formatter.Deserialize(fileStream);
              fileStream.Close();

              Assert.AreEqual(exception.Message, deserializedException.Message);
              Assert.AreEqual(exception0.Message, deserializedException.InnerExceptions[0].Message);
              Assert.AreEqual(exception1.Message, deserializedException.InnerExceptions[1].Message);
        }
コード例 #2
0
        /// <summary>
        ///   Displays a generic task exception dialog
        /// </summary>
        /// <remarks>
        ///   TODO: consider moving this to a UI helper class
        /// </remarks>
        /// <param name="exception">An instance of <see cref="TaskException" />.</param>
        /// <returns>The <see cref="TaskDialogButton" /> that had been activated.</returns>
        private static TaskDialogButton DisplayTaskExceptionDialog(TaskException exception) => new TaskDialog
        {
            WindowTitle             = System.Windows.Forms.Application.ProductName,
            MainIcon                = TaskDialogIcon.Error,
            WindowIcon              = Resources.AppIcon,
            AllowDialogCancellation = true,
            Width   = 200,
            Buttons =
            {
                new TaskDialogButton(ButtonType.Close)
                {
                    Default = true
                },
                new TaskDialogButton(ButtonType.Retry),
                new TaskDialogButton(Resources.TaskHelper_DisplayTaskExceptionDialog_ReportButtonCaption)
                {
                    Enabled = false
                } // TODO: implement bug reporter helper
            },
            MainInstruction     = exception.ShortMessage,
            Content             = exception.Message,
            ExpandFooterArea    = true,
            ExpandedInformation = exception.InnerException?.ToString() ?? exception.ToString()
        }

        .ShowDialog();
コード例 #3
0
        public void SerializationBinary()
        {
            var exception0 = new Exception("First exception");
            var exception1 = new Exception("Second exception");
            var exception  = new TaskException(new[] { exception0, exception1 });

            const string fileName = "SerializationTaskException.bin";

            if (File.Exists(fileName))
            {
                File.Delete(fileName);
            }

            var fileStream = new FileStream(fileName, FileMode.Create);

            var formatter = new BinaryFormatter();

            formatter.Serialize(fileStream, exception);
            fileStream.Close();

            fileStream = new FileStream(fileName, FileMode.Open);
            formatter  = new BinaryFormatter();
            var deserializedException = (TaskException)formatter.Deserialize(fileStream);

            fileStream.Close();

            Assert.AreEqual(exception.Message, deserializedException.Message);
            Assert.AreEqual(exception0.Message, deserializedException.InnerExceptions[0].Message);
            Assert.AreEqual(exception1.Message, deserializedException.InnerExceptions[1].Message);
        }
コード例 #4
0
 public static TaskException CreateTaskException(string type, string message, string stackTrace)
 {
     // Note: We explicitly use the same boxed TaskException struct for all 3 operations.
     object ex = new TaskException();
     typeField.SetValue(ex, type);
     messageField.SetValue(ex, message);
     stackTraceField.SetValue(ex, stackTrace);
     return (TaskException)ex;
 }
コード例 #5
0
        public void Should_notify_all_methods_as_finished_and_failed()
        {
            testRun.Run();

            var methodTasks = testClass.Methods.Select(m => m.Task).ToList();

            var taskException = new TaskException(null, string.Format("Class failed in {0}", testClass.ClassTask.TypeName), null);
            testRun.Messages.OfTask(methodTasks[0]).AssertTaskException(taskException);
            testRun.Messages.OfTask(methodTasks[1]).AssertTaskException(taskException);
        }
コード例 #6
0
        public static TaskException CreateTaskException(string type, string message, string stackTrace)
        {
            // Note: We explicitly use the same boxed TaskException struct for all 3 operations.
            object ex = new TaskException();

            typeField.SetValue(ex, type);
            messageField.SetValue(ex, message);
            stackTraceField.SetValue(ex, stackTrace);
            return((TaskException)ex);
        }
コード例 #7
0
        public void Should_notify_all_methods_as_finished_and_failed()
        {
            testRun.Run();

            var methodTasks = testClass.Methods.Select(m => m.Task).ToList();

            var taskException = new TaskException(null, string.Format("Class failed in {0}", testClass.ClassTask.TypeName), null);

            testRun.Messages.OfTask(methodTasks[0]).AssertTaskException(taskException);
            testRun.Messages.OfTask(methodTasks[1]).AssertTaskException(taskException);
        }
コード例 #8
0
        public void TestConstructors()
        {
            var exception0 = new Exception("First exception");
              var exception1 = new Exception("Second exception");
              var exception = new TaskException(new [] { exception0, exception1 });

              Assert.IsFalse(String.IsNullOrEmpty(exception.Message));
              Assert.IsNotNull(exception.InnerExceptions);
              Assert.AreEqual(2, exception.InnerExceptions.Length);
              Assert.AreEqual(exception0, exception.InnerExceptions[0]);
              Assert.AreEqual(exception1, exception.InnerExceptions[1]);
        }
コード例 #9
0
        public void TestConstructors()
        {
            var exception0 = new Exception("First exception");
            var exception1 = new Exception("Second exception");
            var exception  = new TaskException(new [] { exception0, exception1 });

            Assert.IsFalse(String.IsNullOrEmpty(exception.Message));
            Assert.IsNotNull(exception.InnerExceptions);
            Assert.AreEqual(2, exception.InnerExceptions.Length);
            Assert.AreEqual(exception0, exception.InnerExceptions[0]);
            Assert.AreEqual(exception1, exception.InnerExceptions[1]);
        }
コード例 #10
0
        /// <summary>
        /// Write Template-Text to logfile: Task Exception
        /// </summary>
        /// <param name="exception">Exception that was thrown</param>
        public void WriteException(TaskException exception)
        {
            if (!CheckWriteLine())
            {
                return;
            }
            object[] Args = new object[4];
            Args[0] = DateTime.Now;
            Args[1] = exception.Source;
            Args[2] = exception.Target;
            Args[3] = exception.Text;

            this.WriteLogLine(string.Format(LogTemplates.WriteException, Args));
        }
コード例 #11
0
 internal void RemoveProductCode(Guid productCode)
 {
     TaskLogger.LogEnter();
     base.SetLogging();
     try
     {
         MsiUtility.PushExternalUI(base.UIHandler, (InstallLogMode)10115);
         try
         {
             string text = productCode.ToString("B").ToUpper(CultureInfo.InvariantCulture);
             base.WriteVerbose(Strings.RemovingPackageByProductCode(productCode));
             uint num = MsiNativeMethods.ConfigureProduct(text, InstallLevel.Default, InstallState.Default, base.PropertyValues);
             if (num != 0U)
             {
                 Win32Exception ex = new Win32Exception((int)num);
                 if (num == 3010U)
                 {
                     if (this.WarnOnRebootRequests)
                     {
                         TaskException ex2 = new TaskException(Strings.MsiRebootRequiredToFinish(text), ex);
                         TaskLogger.SendWatsonReport(ex2);
                         base.WriteWarning(ex2.Message);
                     }
                     else if (UninstallMsi.rebootRequiredException == null)
                     {
                         UninstallMsi.rebootRequiredException = new TaskException(Strings.MsiRebootRequiredToContinue(text), ex);
                     }
                 }
                 else if (string.IsNullOrEmpty(base.LastMsiError))
                 {
                     base.WriteError(new TaskException(Strings.MsiCouldNotRemoveProduct(productCode, ex.Message, (int)num), ex), ErrorCategory.InvalidOperation, null);
                 }
                 else
                 {
                     base.WriteError(new TaskException(Strings.MsiCouldNotRemoveProductDetailed(productCode, ex.Message, (int)num, base.LastMsiError), ex), ErrorCategory.InvalidOperation, null);
                 }
             }
         }
         finally
         {
             MsiUtility.PopExternalUI();
         }
     }
     catch (ArgumentOutOfRangeException exception)
     {
         base.WriteError(exception, ErrorCategory.InvalidArgument, 0);
     }
     TaskLogger.LogExit();
 }
コード例 #12
0
        public override Task RunAsync()
        {
            var awaitableTask = Task.Run(() =>
            {
                Logger.LogInformation($"Running '{AwaitableTaskName}' during '{AwaitableTaskDurationInSeconds}' sec");
                return(Task.Delay(TimeSpan.FromSeconds(AwaitableTaskDurationInSeconds)));
            }).ContinueWith(previousTask => TaskHelper.OnTerminatedTask(previousTask, AwaitableTaskName));

            var fireAndForgetTask = Task.Run(async() =>
            {
                Logger.LogInformation($"Running '{FireAndForgetTaskName}' during '{FireAndForgetTaskDurationInSeconds}' sec");
                await Task.Delay(TimeSpan.FromSeconds(FireAndForgetTaskDurationInSeconds));
                throw TaskException.TaskHasFailed(FireAndForgetTaskName);
            }).ContinueWith(previousTask => TaskHelper.OnTerminatedTask(previousTask, FireAndForgetTaskName));

            TaskHelper.FireAndForgetTask(fireAndForgetTask, FireAndForgetTaskName);
            return(awaitableTask);
        }
コード例 #13
0
        public void Failed(TaskException[] exceptions, string exceptionMessage, string childMessage = null)
        {
            if (childMessage != null)
            {
                Reset();

                var childExceptions = new[] { new TaskException(null, childMessage, null) };
                foreach (var child in children ?? EmptyList<RemoteTaskWrapper>.InstanceList)
                    child.Error(childExceptions, childMessage);
            }

            if (result == TaskResult.Inconclusive)
            {
                result = TaskResult.Exception;
                message = exceptionMessage;
                server.TaskException(RemoteTask, exceptions);
            }
        }
コード例 #14
0
        public IHttpActionResult ExecuteTask()
        {
            TaskException task = new TaskException(exceptionService);

            RecurringJob.AddOrUpdate(Environment.MachineName + "--ExceptionOrder", () => task.ExecuteEmail("test", null), Cron.MinuteInterval(5), queue: Environment.MachineName.ToLower(CultureInfo.CurrentCulture));

            TaskSyncLineShiftPerfLastShift taskSyncLineShiftPerf = new TaskSyncLineShiftPerfLastShift(glLineService);

            //同步GoldenLine 模组: 专案报表数据
            RecurringJob.AddOrUpdate(Environment.MachineName + "--SyncLineShiftPerf", () => taskSyncLineShiftPerf.SyncLineShiftPerf(null), Cron.MinuteInterval(5), queue: Environment.MachineName.ToLower(CultureInfo.CurrentCulture));
            //RecurringJob.AddOrUpdate("SyncLineShiftPerf", () => taskSyncLineShiftPerf.SyncLineShiftPerf(null), "*/5 * * * *", TimeZoneInfo.Local);
            //同步GoldenLine 模组: 专案报表当前班次的其他班次数据
            RecurringJob.AddOrUpdate(Environment.MachineName + "--SyncLineShiftPerfLastShift", () => taskSyncLineShiftPerf.SyncLineShiftPerfLastShift(null), Cron.MinuteInterval(5), queue: Environment.MachineName.ToLower(CultureInfo.CurrentCulture));
            //RecurringJob.AddOrUpdate("SyncLineShiftPerfLastShift", () => taskSyncLineShiftPerf.SyncLineShiftPerfLastShift(null), "*/5 * * * *", TimeZoneInfo.Local);

            ////同步OEE 改善计划的延迟状态
            TaskOEEActionManagement taskSyncOEEActionStatu = new TaskOEEActionManagement(_OEE_Service);

            RecurringJob.AddOrUpdate(Environment.MachineName + "--SyncOEEActionStatus", () => taskSyncOEEActionStatu.UpdateActionStatus(null), Cron.MinuteInterval(5), queue: Environment.MachineName.ToLower(CultureInfo.CurrentCulture));

            return(Ok());
        }
コード例 #15
0
        private void PublishTaskResult(RemoteTask task, FeatureResult result)
        {
            var    taskResult        = GetFeatureTaskResult(result);
            string taskResultMessage = "";

            if (taskResult == TaskResult.Skipped)
            {
                taskResultMessage = "Skipped";
            }
            if (taskResult == TaskResult.Inconclusive)
            {
                taskResultMessage = "Pending";
                server.TaskExplain(task, "See pending step(s) for more information");
            }
            if (taskResult == TaskResult.Error)
            {
                var failure = result.ScenarioResults.First(_ => _.Result is Failed).Result as Failed;
                taskResultMessage = failure.Exception.Message;
                var te = new TaskException(failure.Exception);
                server.TaskException(task, new[] { te });
            }
            server.TaskFinished(task, taskResultMessage, taskResult);
        }
コード例 #16
0
            /// <summary>
            /// Set controles for state: Exception
            /// Add exception to ListView
            /// </summary>
            internal void SetProgress_Exception(TaskException exception)
            {
                System.Drawing.Color ItemBackground;
                switch (exception.Level)
                {
                case TaskException.ExceptionLevel.Slight:
                    ItemBackground = System.Drawing.Color.FromArgb(255, 255, 192);
                    break;

                case TaskException.ExceptionLevel.Medium:
                    ItemBackground = System.Drawing.Color.FromArgb(255, 224, 192);
                    break;

                case TaskException.ExceptionLevel.Critical:
                    ItemBackground = System.Drawing.Color.FromArgb(255, 192, 192);
                    break;

                default:
                    ItemBackground = System.Drawing.SystemColors.Window;
                    break;
                }

                ListViewItem ExItem = new ListViewItem
                {
                    BackColor = ItemBackground,
                    Tag       = exception,
                    Text      = (this._progressControle._exceptionListView.Items.Count + 1).ToString()
                };

                ExItem.SubItems.Add(exception.Source);
                ExItem.SubItems.Add(exception.Target);
                ExItem.SubItems.Add(exception.Text);

                ListViewInv.AddItem(this._progressControle._exceptionListView, ExItem);
                TabPageInv.ImageIndex(this._progressControle._conclusionTabPage, EXCEPTION_ICON_INDEX);
                TextBoxInv.Text(this._progressControle._exceptionCount, string.Format(FORMAT_VALUE, this._progressControle._exceptionListView.Items.Count));
            }
コード例 #17
0
 public bool TaskException(RemoteTask remoteTask, TaskException[] exceptions)
 {
     Add(TaskMessage.TaskException(remoteTask, exceptions));
     ReportExceptions(exceptions);
     return true;
 }
コード例 #18
0
 public TaskResult(TaskException exception)
 {
     Success   = false;
     Exception = exception;
 }
コード例 #19
0
 private void POnTaskException(object?sender, TaskException e)
 {
     Console.WriteLine("Task Exception");
 }
コード例 #20
0
 public void TaskException(RemoteTask remoteTask, TaskException[] exceptions)
 {
     ShouldContinue = server.TaskException(remoteTask, exceptions);
 }
コード例 #21
0
        private async Task Next(CancellationToken cancellationToken)
        {
            if (cancellationToken.IsCancellationRequested)
            {
                return;
            }

            if (!_isBusy)
            {
                if (queue.Count > 0)
                {
                    // Optional delay.

                    if (Delay > default(TimeSpan))
                    {
                        await Task.Delay(Delay);
                    }

                    // Peek the current task.

                    var context = queue.Peek();

                    try
                    {
                        _isRunning = true;
                        _isBusy    = true;

                        // Execute the current task.

                        TaskExecuting?.Invoke(this, new TaskEventArgs(context.Tag));

                        await context.Action(context, cts.Token);
                    }
                    catch (Exception exc)
                    {
                        // Handle any exception thrown inside a task.
                        // Invoke the Exception event handlers.

                        TaskException?.Invoke(this, new TaskEventArgs(context.Tag, exc));

                        if (CancelOnException)
                        {
                            // Cancel the queue.

                            ClearInternal();
                        }
                    }

                    TaskExecuted?.Invoke(this, new TaskEventArgs(context.Tag));

                    // Dequeue the currently finished task and request the next.

                    if (queue.Count > 0)
                    {
                        queue.Dequeue();
                    }
                    _isBusy = false;
                    await Next(cts.Token);
                }
            }
            else
            {
                _isRunning = false;
            }
        }
コード例 #22
0
 public TaskExceptionMatcher(TaskException[] expectedExceptions)
 {
     this.expectedExceptions = expectedExceptions;
 }
コード例 #23
0
        private void Error(TaskException[] exceptions, string errorMessage)
        {
            Reset();

            foreach (var child in children ?? EmptyList<RemoteTaskWrapper>.InstanceList)
                child.Error(exceptions, errorMessage);

            result = TaskResult.Error;
            message = errorMessage;
            server.TaskException(RemoteTask, exceptions);

            // Error implies Finished. Also, if we're calling Error on grand-children, we need
            // to call Finished on them too, and this is the easiest way
            Finished();
        }
コード例 #24
0
        public bool TaskException(RemoteTask remoteTask, TaskException[] exceptions)
        {
            Assert.NotNull(remoteTask);
            Assert.Same(tasks.Peek(), remoteTask);

            if (!TaskExceptionCalls.ContainsKey(remoteTask))
                TaskExceptionCalls.Add(remoteTask, new List<TaskException[]>());
            TaskExceptionCalls[remoteTask].Add(exceptions);

            return true;
        }
コード例 #25
0
ファイル: ScheduledTask.cs プロジェクト: fossabot/web-host
 protected virtual void OnTaskException(TaskExceptionEventArgs args)
 {
     //TODO: (jmd 2015-09-30) Consider wrapping in try catch. They can force the thread to close the app.
     TaskException?.Invoke(this, args);
 }
コード例 #26
0
        protected override void InternalProcessRecord()
        {
            TaskLogger.LogEnter();
            if (string.IsNullOrEmpty(base.ExeName))
            {
                base.WriteError(new ArgumentException(Strings.ErrorFileNameCannotBeEmptyOrNull, "ExeName"), ErrorCategory.InvalidArgument, "ExeName");
            }
            base.WriteVerbose(Strings.ProcessStart(base.ExeName, base.Args));
            int       num  = 6;
            int       num2 = 0;
            Exception ex;

            for (;;)
            {
                num2++;
                ex = null;
                try
                {
                    string outputString;
                    string errorString;
                    int    num3;
                    if (num2 == 1)
                    {
                        num3 = ProcessRunner.Run(base.ExeName, base.Args, new Dictionary <string, string>
                        {
                            {
                                "COMPLUS_NGENWORKERCOUNT",
                                "3"
                            }
                        }, base.Timeout, null, out outputString, out errorString);
                    }
                    else
                    {
                        base.WriteVerbose(new LocalizedString(string.Format("Attempt {0} to execute '{1}'", num2, base.ExeName)));
                        num3 = ProcessRunner.Run(base.ExeName, base.Args, new Dictionary <string, string>
                        {
                            {
                                "COMPLUS_EnableMultiproc",
                                "0"
                            }
                        }, base.Timeout, null, out outputString, out errorString);
                        base.WriteVerbose(new LocalizedString(string.Format("'{0}' returned exitCode {1}", base.ExeName, num3)));
                    }
                    this.HandleProcessOutput(outputString, errorString);
                    if (num3 != 0)
                    {
                        ex = new TaskException(Strings.ExceptionRunProcessFailed(num3));
                    }
                }
                catch (Win32Exception ex2)
                {
                    ex = ex2;
                }
                catch (TimeoutException ex3)
                {
                    ex = ex3;
                }
                catch (Exception ex4)
                {
                    base.WriteVerbose(Strings.ProcessStandardError(string.Format("Attempt {0} failed and will not be retried. Exception: {1}", num2, ex4.ToString())));
                    throw;
                }
                if (ex == null)
                {
                    goto IL_1C1;
                }
                if (num2 > num)
                {
                    break;
                }
                base.WriteVerbose(Strings.ProcessStandardError(string.Format("Retry({0}/{1}): exception: {2}", num2, num, ex.ToString())));
                Thread.Sleep(num2 * 1000);
            }
            base.WriteVerbose(Strings.ProcessStandardError(string.Format("Reached maximum times of retries({0}): exception: {1}. Ignore and continue.", num, ex.ToString())));
IL_1C1:
            TaskLogger.LogExit();
        }
コード例 #27
0
 public void TaskException(RemoteTask remoteTask, TaskException[] exceptions)
 {
     server.TaskException(remoteTask, exceptions);
 }
コード例 #28
0
 public void TaskException(RemoteTask remoteTask, TaskException[] exceptions)
 {
     Add(TaskMessage.TaskException(remoteTask, exceptions));
     ReportExceptions(exceptions);
 }
コード例 #29
0
        // If more than one test row, show display names in task progress
        // If more than one test row, output display names
        // If more than one test row, output is prefixed with display name
        // If more than one test row, exception message contains display name
        // If more than one test row + multiple exceptions, each exception set includes display name
        // If more than one test row + exceptions progress message contains "one or more theory tests failed"

        private static TaskException[] MatchExceptions(TaskException[] taskExceptions)
        {
            throw new NotSupportedException();
            //return Match.Create(new TaskExceptionMatcher(taskExceptions).Match);
        }
コード例 #30
0
 private static void AssertTaskExceptionsCalled(TaskException[] expectedTaskExceptions, List<TaskException[]> actualTaskExceptions)
 {
     Assert.Equal(expectedTaskExceptions, actualTaskExceptions);
 }
コード例 #31
0
            public bool Match(TaskException[] actualExceptions)
            {
                if (expectedExceptions.Length != actualExceptions.Length)
                    return false;

                for (int i = 0; i < expectedExceptions.Length; i++)
                {
                    if (expectedExceptions[i].Type != actualExceptions[0].Type
                        && expectedExceptions[i].Message != actualExceptions[i].Message
                        && expectedExceptions[i].StackTrace != actualExceptions[i].StackTrace)
                    {
                        return false;
                    }
                }

                return true;
            }
コード例 #32
0
        // If more than one test row, show display names in task progress
        // If more than one test row, output display names
        // If more than one test row, output is prefixed with display name
        // If more than one test row, exception message contains display name
        // If more than one test row + multiple exceptions, each exception set includes display name
        // If more than one test row + exceptions progress message contains "one or more theory tests failed"

        private static TaskException[] MatchExceptions(TaskException[] taskExceptions)
        {
            return Match<TaskException[]>.Create(new TaskExceptionMatcher(taskExceptions).Match);
        }