Example #1
0
        public static ErrorResult?ShowFallbackProblemDialog(string levelOfProblem, Exception exception, string detailedMessage, string shortUserLevelMessage, bool isShortMessagePreEncoded = false,
                                                            string notifySecondaryButtonLabel = null, ErrorResult?notifySecondaryPressedResult = null)
        {
            var fallbackReporter = new WinFormsErrorReporter();

            if (shortUserLevelMessage == null)
            {
                shortUserLevelMessage = "";
            }

            string decodedShortUserLevelMessage = isShortMessagePreEncoded ? XmlString.FromXml(shortUserLevelMessage).Unencoded : shortUserLevelMessage;
            string message = decodedShortUserLevelMessage;

            if (!String.IsNullOrEmpty(detailedMessage))
            {
                message += $"\n{detailedMessage}";
            }

            if (levelOfProblem == ProblemLevel.kFatal)
            {
                if (exception != null)
                {
                    fallbackReporter.ReportFatalException(exception);
                }
                else
                {
                    fallbackReporter.ReportFatalMessageWithStackTrace(message, null);
                }

                return(null);
            }
            else if (levelOfProblem == ProblemLevel.kNonFatal || levelOfProblem == ProblemLevel.kUser)
            {
                // FYI, if levelOfProblem==kUser, we're unfortunately going to be
                // using the messaging from NonFatal even though we would ideally like to have the customized messaging for levelOfProblem==kUser,
                // but we'll just live with it because there's no easy way to customize it. It's probably an extremely rare situation anyway
                if (String.IsNullOrEmpty(message))
                {
                    fallbackReporter.ReportNonFatalException(exception, new ShowAlwaysPolicy());
                }
                else
                {
                    fallbackReporter.ReportNonFatalExceptionWithMessage(exception, message);
                }

                return(null);
            }
            else             // Presumably, levelOfProblem = "notify" now
            {
                if (String.IsNullOrEmpty(notifySecondaryButtonLabel) || notifySecondaryPressedResult == null)
                {
                    return(fallbackReporter.NotifyUserOfProblem(new ShowAlwaysPolicy(), null, ErrorResult.OK,
                                                                message));
                }
                else
                {
                    return(fallbackReporter.NotifyUserOfProblem(new ShowAlwaysPolicy(), notifySecondaryButtonLabel, notifySecondaryPressedResult ?? ErrorResult.OK, message));
                }
            }
        }
Example #2
0
 public static void CatchWinFormsExeptions(this CoderrConfiguration configurator)
 {
     if (configurator == null)
     {
         throw new ArgumentNullException(nameof(configurator));
     }
     WinFormsErrorReporter.Activate();
     Err.Configuration.ContextProviders.Add(new OpenFormsCollector());
 }
Example #3
0
 /// <summary>
 ///     Take a screen shot of every form that is opened when an error happen.
 /// </summary>
 /// <param name="configurator">OneTrueError configurator (accessed through <see cref="Err.Configuration" />).</param>
 public static void TakeScreenshots(this CoderrConfiguration configurator)
 {
     if (configurator == null)
     {
         throw new ArgumentNullException(nameof(configurator));
     }
     WinFormsErrorReporter.Activate();
     Err.Configuration.ContextProviders.Add(new ScreenshotProvider(true));
 }
 /// <summary>
 ///     Take a screen shot of every form that is opened when an error happen.
 /// </summary>
 /// <param name="configurator">OneTrueError configurator (accessed through <see cref="OneTrue.Configuration" />).</param>
 public static void TakeScreenshotOfActiveFormOnly(this OneTrueConfiguration configurator)
 {
     if (configurator == null)
     {
         throw new ArgumentNullException("configurator");
     }
     WinFormsErrorReporter.Activate();
     OneTrue.Configuration.ContextProviders.Add(new ScreenshotProvider());
 }
Example #5
0
        /// <summary>
        /// Notifies the user of a problem, using a browser-based dialog.
        /// Note: This is designed to be called by LibPalaso's ErrorReport class.
        /// </summary>
        /// <param name="policy">Checks if we should notify the user, based on the contents of {message}</param>
        /// <param name="alternateButton1Label">The text that goes on the Report button. However, if speicfied, this.ReportButtonLabel takes precedence over this parameter</param>
        /// <param name="resultIfAlternateButtonPressed">This is the value that this method should return so that the caller (mainly LibPalaso ErrorReport)
        /// can know if the alternate button was pressed, and if so, invoke whatever actions are desired.</param>
        /// <param name="message">The message to show to the user</param>
        /// <returns>If closed normally, returns ErrorResult.OK
        /// If the report button was pressed, returns {resultIfAlternateButtonPressed}.
        /// If the secondary action button was pressed, returns {this.SecondaryActionResult} if that is non-null; otherwise falls back to {resultIfAlternateButtonPressed}
        /// If an exception is throw while executing this function, returns ErrorResult.Abort.
        /// </returns>
        public ErrorResult NotifyUserOfProblem(IRepeatNoticePolicy policy, string alternateButton1Label, ErrorResult resultIfAlternateButtonPressed, string message)
        {
            // Let this thread try to acquire the lock, if necessary
            // Note: It is expected that sometimes this function will need to acquire the lock for this thread,
            //       and sometimes it'll already be acquired.
            //       The reason is because for legacy code that calls ErrorReport directly, this function is the first entry point into this class.
            //       But for code that needs the new secondaryAction functionality, it needs to enter through CustomNotifyUser*().
            //       That function wants to acquire a lock so that the instance variables it sets aren't modified by any other thread before
            //       entering this NotifyUserOfProblem() function.
            bool wasAlreadyLocked = System.Threading.Monitor.IsEntered(_lock);

            if (!wasAlreadyLocked)
            {
                System.Threading.Monitor.Enter(_lock);
            }

            try
            {
                ErrorResult result = ErrorResult.OK;
                if (policy.ShouldShowMessage(message))
                {
                    ErrorReport.OnShowDetails = null;
                    var reportButtonLabel = GetReportButtonLabel(alternateButton1Label);
                    result = ShowNotifyDialog(ProblemLevel.kNotify, message, null, reportButtonLabel, resultIfAlternateButtonPressed, this.SecondaryActionButtonLabel, this.SecondaryActionResult);
                }

                ResetToDefaults();

                return(result);
            }
            catch (Exception e)
            {
                var fallbackReporter = new WinFormsErrorReporter();
                fallbackReporter.ReportNonFatalException(e, new ShowAlwaysPolicy());

                return(ErrorResult.Abort);
            }
            finally
            {
                // NOTE: Each thread needs to make sure it calls Exit() the same number of times as it calls Enter()
                // in order for other threads to be able to acquire the lock later.
                if (!wasAlreadyLocked)
                {
                    System.Threading.Monitor.Exit(_lock);
                }
            }
        }
Example #6
0
        private void ShowNotifyDialog(string severity, string messageText, Exception exception,
                                      string reportButtonLabel, string secondaryButtonLabel)
        {
            // Before we do anything that might be "risky", put the problem in the log.
            ProblemReportApi.LogProblem(exception, messageText, severity);

            // ENHANCE: Allow the caller to pass in the control, which would be at the front of this.
            //System.Windows.Forms.Control control = Form.ActiveForm ?? FatalExceptionHandler.ControlOnUIThread;
            var control        = GetControlToUse();
            var isSyncRequired = false;

            SafeInvoke.InvokeIfPossible("Show Error Reporter", control, isSyncRequired, () =>
            {
                // Uses a browser dialog to show the problem report
                try
                {
                    StartupScreenManager.CloseSplashScreen();                     // if it's still up, it'll be on top of the dialog

                    var message = GetMessage(messageText, exception);

                    if (!Api.BloomServer.ServerIsListening)
                    {
                        // There's no hope of using the HtmlErrorReporter dialog if our server is not yet running.
                        // We'll likely get errors, maybe Javascript alerts, that won't lead to a clean fallback to
                        // the exception handler below. Besides, failure of HtmlErrorReporter in these circumstances
                        // is expected; we just want to cleanly report the original problem, not to report a
                        // failure of error handling.

                        // Note: HtmlErrorReporter supports up to 3 buttons (OK, Report, and [Secondary action]), but the fallback reporter only supports a max of two.
                        // Well, just going to have to drop the secondary action.

                        ShowFallbackProblemDialog(severity, exception, messageText, null, false);
                        return;
                    }

                    object props = new { level = ProblemLevel.kNotify, reportLabel = reportButtonLabel, secondaryLabel = secondaryButtonLabel, message = message };

                    // Precondition: we must be on the UI thread for Gecko to work.
                    using (var dlg = BrowserDialogFactory.CreateReactDialog("problemReportBundle", props))
                    {
                        dlg.FormBorderStyle = FormBorderStyle.FixedToolWindow; // Allows the window to be dragged around
                        dlg.ControlBox      = true;                            // Add controls like the X button back to the top bar
                        dlg.Text            = "";                              // Remove the title from the WinForms top bar

                        dlg.Width = 620;

                        // 360px was experimentally determined as what was needed for the longest known text for NotifyUserOfProblem
                        // (which is "Before saving, Bloom did an integrity check of your book [...]" from BookStorage.cs)
                        // You can make this height taller if need be.
                        // A scrollbar will appear if the height is not tall enough for the text
                        dlg.Height = 360;

                        // ShowDialog will cause this thread to be blocked (because it spins up a modal) until the dialog is closed.
                        BloomServer.RegisterThreadBlocking();

                        try
                        {
                            dlg.ShowDialog();

                            // Take action if the user clicked a button other than Close
                            if (dlg.CloseSource == "closedByAlternateButton" && OnSecondaryActionPressed != null)
                            {
                                OnSecondaryActionPressed(exception, message);
                            }
                            else if (dlg.CloseSource == "closedByReportButton")
                            {
                                if (OnReportButtonPressed != null)
                                {
                                    OnReportButtonPressed(exception, message);
                                }
                                else
                                {
                                    DefaultOnReportPressed(exception, message);
                                }
                            }

                            // Note: With the way LibPalaso's ErrorReport is designed,
                            // its intention is that after OnShowDetails is invoked and closed, you will not come back to the Notify Dialog
                            // This code has been implemented to follow that model
                            //
                            // But now that we have more options, it might be nice to come back to this dialog.
                            // If so, you'd need to add/update some code in this section.
                        }
                        finally
                        {
                            ResetToDefaults();
                            BloomServer.RegisterThreadUnblocked();
                        }
                    }
                }
                catch (Exception errorReporterException)
                {
                    Logger.WriteError("*** HtmlErrorReporter threw an exception trying to display", errorReporterException);
                    // At this point our problem reporter has failed for some reason, so we want the old WinForms handler
                    // to report both the original error for which we tried to open our dialog and this new one where
                    // the dialog itself failed.
                    // In order to do that, we create a new exception with the original exception (if there was one) as the
                    // inner exception. We include the message of the exception we just caught. Then we call the
                    // old WinForms fatal exception report directly.
                    // In any case, both of the errors will be logged by now.
                    var message = "Bloom's error reporting failed: " + errorReporterException.Message;

                    // Fallback to Winforms in case of trouble getting the browser to work
                    var fallbackReporter = new WinFormsErrorReporter();
                    // Food for thought: is it really fatal of the Notify Dialog had an exception? Maybe NonFatal makes more sense
                    fallbackReporter.ReportFatalException(new ApplicationException(message, exception ?? errorReporterException));
                }
            });
        }
Example #7
0
        // ENHANCE: Reduce duplication in HtmlErrorReporter and ProblemReportApi code. Some of the ProblemReportApi code can move to HtmlErrorReporter code.

        // ENHANCE: I think levelOfProblem would benefit from being required and being an enum.

        /// <summary>
        /// Shows a problem dialog.
        /// </summary>
        /// <param name="controlForScreenshotting"></param>
        /// <param name="exception"></param>
        /// <param name="detailedMessage"></param>
        /// <param name="levelOfProblem">"user", "nonfatal", or "fatal"</param>
        /// <param name="additionalPathsToInclude"></param>
        public static void ShowProblemDialog(Control controlForScreenshotting, Exception exception,
                                             string detailedMessage            = "", string levelOfProblem = "user", string shortUserLevelMessage = "", bool isShortMessagePreEncoded = false,
                                             string[] additionalPathsToInclude = null)
        {
            // Before we do anything that might be "risky", put the problem in the log.
            LogProblem(exception, detailedMessage, levelOfProblem);
            if (Program.RunningHarvesterMode)
            {
                Console.WriteLine(levelOfProblem + " Problem Detected: " + shortUserLevelMessage + "  " + detailedMessage + "  " + exception);
                return;
            }
            StartupScreenManager.CloseSplashScreen();             // if it's still up, it'll be on top of the dialog

            lock (_showingProblemReportLock)
            {
                if (_showingProblemReport)
                {
                    // If a problem is reported when already reporting a problem, that could
                    // be an unbounded recursion that freezes the program and prevents the original
                    // problem from being reported.  So minimally report the recursive problem and stop
                    // the recursion in its tracks.
                    //
                    // Alternatively, can happen if multiple async BloomAPI calls go out and return errors.
                    // It's probably not helpful to have multiple problem report dialogs at the same time
                    // in this case either (even if there are theoretically a finite (not infinite) number of them)
                    const string msg = "MULTIPLE CALLS to ShowProblemDialog. Suppressing the subsequent calls";
                    Console.Write(msg);
                    Logger.WriteEvent(msg);
                    return;                     // Abort
                }

                _showingProblemReport = true;
            }

            // We have a better UI for this problem
            // Note that this will trigger whether it's a plain 'ol System.IO.PathTooLongException, or our own enhanced subclass, Bloom.Utiles.PathTooLongException
            if (exception is System.IO.PathTooLongException)
            {
                Utils.LongPathAware.ReportLongPath((System.IO.PathTooLongException)exception);
                return;
            }

            GatherReportInfoExceptScreenshot(exception, detailedMessage, shortUserLevelMessage, isShortMessagePreEncoded);

            if (controlForScreenshotting == null)
            {
                controlForScreenshotting = Form.ActiveForm;
            }
            if (controlForScreenshotting == null)             // still possible if we come from a "Details" button
            {
                controlForScreenshotting = FatalExceptionHandler.ControlOnUIThread;
            }
            ResetScreenshotFile();
            // Originally, we used SafeInvoke for both the screenshot and the new dialog display. SafeInvoke was great
            // for trying to get a screenshot, but having the actual dialog inside
            // of it was causing problems for handling any errors in showing the dialog.
            // Now we use SafeInvoke only inside of this extracted method.
            TryGetScreenshot(controlForScreenshotting);

            if (BloomServer._theOneInstance == null)
            {
                // We got an error really early, before we can use HTML dialogs. Report using the old dialog.
                // Hopefully we're still on the one main thread.
                HtmlErrorReporter.ShowFallbackProblemDialog(levelOfProblem, exception, detailedMessage, shortUserLevelMessage, isShortMessagePreEncoded);
                return;
            }

            SafeInvoke.InvokeIfPossible("Show Problem Dialog", controlForScreenshotting, false, () =>
            {
                // Uses a browser ReactDialog (if possible) to show the problem report
                try
                {
                    // We call CloseSplashScreen() above too, where it might help in some cases, but
                    // this one, while apparently redundant might be wise to keep since closing the splash screen
                    // needs to be done on the UI thread.
                    StartupScreenManager.CloseSplashScreen();

                    if (!BloomServer.ServerIsListening)
                    {
                        // We can't use the react dialog!
                        HtmlErrorReporter.ShowFallbackProblemDialog(levelOfProblem, exception, detailedMessage, shortUserLevelMessage, isShortMessagePreEncoded);
                        return;
                    }

                    // Precondition: we must be on the UI thread for Gecko to work.
                    using (var dlg = new ReactDialog("problemReportBundle", new { level = levelOfProblem }, "Problem Report"))
                    {
                        _additionalPathsToInclude = additionalPathsToInclude;
                        dlg.FormBorderStyle       = FormBorderStyle.FixedToolWindow; // Allows the window to be dragged around
                        dlg.ControlBox            = true;                            // Add controls like the X button back to the top bar
                        dlg.Text = "";                                               // Remove the title from the WinForms top bar

                        dlg.Width  = 731;
                        dlg.Height = 616;

                        // ShowDialog will cause this thread to be blocked (because it spins up a modal) until the dialog is closed.
                        BloomServer._theOneInstance.RegisterThreadBlocking();
                        try
                        {
                            // Keep dialog on top of program window if possible.  See https://issues.bloomlibrary.org/youtrack/issue/BL-10292.
                            if (controlForScreenshotting is Bloom.Shell)
                            {
                                dlg.ShowDialog(controlForScreenshotting);
                            }
                            else
                            {
                                dlg.ShowDialog();
                            }
                        }
                        finally
                        {
                            BloomServer._theOneInstance.RegisterThreadUnblocked();
                            _additionalPathsToInclude = null;
                        }
                    }
                }
                catch (Exception problemReportException)
                {
                    Logger.WriteError("*** ProblemReportApi threw an exception trying to display", problemReportException);
                    // At this point our problem reporter has failed for some reason, so we want the old WinForms handler
                    // to report both the original error for which we tried to open our dialog and this new one where
                    // the dialog itself failed.
                    // In order to do that, we create a new exception with the original exception (if there was one) as the
                    // inner exception. We include the message of the exception we just caught. Then we call the
                    // old WinForms fatal exception report directly.
                    // In any case, both of the errors will be logged by now.
                    var message = "Bloom's error reporting failed: " + problemReportException.Message;

                    // Fallback to Winforms in case of trouble getting the browser up
                    var fallbackReporter = new WinFormsErrorReporter();
                    // ENHANCE?: If reporting a non-fatal problem failed, why is the program required to abort? It might be able to handle other tasks successfully
                    fallbackReporter.ReportFatalException(new ApplicationException(message, exception ?? problemReportException));
                }
                finally
                {
                    lock (_showingProblemReportLock)
                    {
                        _showingProblemReport = false;
                    }
                }
            });
        }