示例#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);
        }
 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;
 }
        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);
        }
        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);
        }
        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]);
        }
        /// <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);
        }
        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());
        }
        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));
            }
 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");
 }
 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;
            }
        }
 public TaskExceptionMatcher(TaskException[] expectedExceptions)
 {
     this.expectedExceptions = expectedExceptions;
 }
        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();
        }
        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
 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);
 }
        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);
 }
 public void TaskException(RemoteTask remoteTask, TaskException[] exceptions)
 {
     Add(TaskMessage.TaskException(remoteTask, exceptions));
     ReportExceptions(exceptions);
 }
        // 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);
        }
 private static void AssertTaskExceptionsCalled(TaskException[] expectedTaskExceptions, List<TaskException[]> actualTaskExceptions)
 {
     Assert.Equal(expectedTaskExceptions, actualTaskExceptions);
 }
            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;
            }
        // 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);
        }