コード例 #1
0
        private StringBuilder GetExceptionDetails(SerializableException exception, string exceptionInfo, string?additionalInfo)
        {
            StringBuilder exceptionDetails = new();

            if (!string.IsNullOrEmpty(exceptionInfo))
            {
                // Tests may be run on VMs, and AppendLine() could be either \r\n or \n
                exceptionDetails.Append('\n');
                exceptionDetails.Append(exceptionInfo.Trim());
                exceptionDetails.Append('\n');
                exceptionDetails.Append('\n');
            }

            exceptionDetails.Append("```\n");
            exceptionDetails.Append(exception.ToString().Trim());
            exceptionDetails.Append('\n');
            exceptionDetails.Append("```\n");
            exceptionDetails.Append('\n');

            if (!string.IsNullOrWhiteSpace(additionalInfo))
            {
                exceptionDetails.Append(additionalInfo.Trim());
                exceptionDetails.Append('\n');
            }

            return(exceptionDetails);
        }
コード例 #2
0
ファイル: ConsoleUI.cs プロジェクト: ytak01/NBug
 internal static UIDialogResult ShowDialog(UIMode uiMode, SerializableException exception, Report report)
 {
     if (uiMode == UIMode.Minimal)
     {
         // Do not interact with the user
         Console.WriteLine(Environment.NewLine + Settings.Resources.UI_Console_Minimal_Message);
         return(new UIDialogResult(ExecutionFlow.BreakExecution, SendReport.Send));
     }
     else if (uiMode == UIMode.Normal)
     {
         // ToDo: Create normal console UI
         Console.WriteLine(Environment.NewLine + Settings.Resources.UI_Console_Normal_Message);
         return(new UIDialogResult(ExecutionFlow.BreakExecution, SendReport.Send));
     }
     else if (uiMode == UIMode.Full)
     {
         // ToDo: Create full console UI
         Console.WriteLine(Environment.NewLine + Settings.Resources.UI_Console_Full_Message);
         return(new UIDialogResult(ExecutionFlow.BreakExecution, SendReport.Send));
     }
     else
     {
         throw NBugConfigurationException.Create(() => Settings.UIMode, "Parameter supplied for settings property is invalid.");
     }
 }
コード例 #3
0
    public SerializableException(Exception exception)
    {
        Type = exception.GetType().Name;

        if (exception.InnerException != null)
        {
            InnerException = new SerializableException(exception.InnerException);
        }

        HelpLink   = exception.HelpLink;
        HResult    = exception.HResult;
        Message    = exception.Message;
        Source     = exception.Source;
        StackTrace = exception.StackTrace;

        var propertiesToExclude = new string[] {
            nameof(Type), nameof(InnerException), nameof(HelpLink), nameof(HResult), nameof(Message), nameof(Source), nameof(StackTrace), nameof(exception.TargetSite)
        };

        foreach (var propertyInfo in exception.GetType().GetProperties())
        {
            if (propertiesToExclude.Any(p => p == propertyInfo.Name))
            {
                continue;
            }
            if (propertyInfo.CanRead)
            {
                Data.Add(propertyInfo.Name, propertyInfo.GetValue(exception));
            }
        }
    }
コード例 #4
0
        private void WriteException(SerializableException exception, StringBuilder sb)
        {
            var        serializer = new XmlSerializer(typeof(SerializableException));
            TextWriter writer     = new StringWriter(sb);

            serializer.Serialize(writer, exception);
        }
コード例 #5
0
        internal UIDialogResult ShowDialog(SerializableException exception, Report report)
        {
            Text = string.Format("{0} {1}", report.GeneralInfo.HostApplication, Settings.Resources.UI_Dialog_Full_Title);

            _lastException = exception;

            // Scaling
            //sendAndQuitButton.Image = DpiUtil.Scale(Resources.Send);
            //btnCopy.Image = DpiUtil.Scale(Resources.CopyToClipboard);
            //exceptionTypeLabel.Image = DpiUtil.Scale(Resources.NBug_Icon_PNG_16);
            //exceptionDetails.InformationColumnWidth = DpiUtil.Scale(350);
            //exceptionDetails.PropertyColumnWidth = DpiUtil.Scale(101);

            // Fill in the 'General' tab
            warningPictureBox.Image      = SystemIcons.Warning.ToBitmap();
            exceptionTextBox.Text        = exception.Type;
            exceptionMessageTextBox.Text = exception.Message;
            targetSiteTextBox.Text       = exception.TargetSite;
            applicationTextBox.Text      = $@"{report.GeneralInfo.HostApplication} [{report.GeneralInfo.HostApplicationVersion}]";
            nbugTextBox.Text             = report.GeneralInfo.NBugVersion;
            dateTimeTextBox.Text         = report.GeneralInfo.DateTime;
            clrTextBox.Text = report.GeneralInfo.CLRVersion;

            // Fill in the 'Exception' tab
            exceptionDetails.Initialize(exception);

            // ToDo: Fill in the 'Report Contents' tab);
            ShowDialog();

            // Write back the user description (as we passed 'report' as a reference since it is a reference object anyway)
            report.GeneralInfo.UserDescription = descriptionTextBox.Text;
            return(_uiDialogResult);
        }
コード例 #6
0
        internal GeneralInfo(SerializableException serializableException)
        {
            // this.HostApplication = Settings.EntryAssembly.GetName().Name; // Does not get the extensions of the file!
            this.HostApplication = Settings.EntryAssembly.GetLoadedModules()[0].Name;

            // this.HostApplicationVersion = Settings.EntryAssembly.GetName().Version.ToString(); // Gets AssemblyVersion not AssemblyFileVersion
            this.HostApplicationVersion = this.NBugVersion = FileVersionInfo.GetVersionInfo(Settings.EntryAssembly.Location).ProductVersion;

            this.NBugVersion = System.Reflection.Assembly.GetCallingAssembly().GetName().Version.ToString();             // Gets AssemblyVersion not AssemblyFileVersion

            this.CLRVersion = Environment.Version.ToString();

            this.DateTime = System.DateTime.UtcNow.ToString();

            if (serializableException != null)
            {
                this.ExceptionType = serializableException.Type;

                if (!string.IsNullOrEmpty(serializableException.TargetSite))
                {
                    this.TargetSite = serializableException.TargetSite;
                }
                else if (serializableException.InnerException != null && !string.IsNullOrEmpty(serializableException.InnerException.TargetSite))
                {
                    this.TargetSite = serializableException.InnerException.TargetSite;
                }

                this.ExceptionMessage = serializableException.Message;
            }
        }
コード例 #7
0
        public static bool TryParseSerializableException(this object value, out SerializableException exception)
        {
            exception = null;

            if (value is SerializableException serializableException)
            {
                exception = serializableException;
            }
            if (value is Newtonsoft.Json.Linq.JToken jTokens)
            {
                exception = jTokens.ToObject <SerializableException>();
            }
#if NETCOREAPP3_0
            if (value is System.Text.Json.JsonElement jsonElement)
            {
                var str = jsonElement.GetRawText();

                var settings = new Newtonsoft.Json.JsonSerializerSettings
                {
                    ContractResolver = new Newtonsoft.Json.Serialization.DefaultContractResolver
                    {
                        IgnoreSerializableAttribute = true,
                        IgnoreSerializableInterface = true
                    }
                };

                exception = Newtonsoft.Json.JsonConvert.DeserializeObject <SerializableException>(str, settings);
            }
#endif

            return(exception != null);
        }
コード例 #8
0
        public void ExceptionNonSerializableDictionary()
        {
            SerializableException sException;

            System.Exception exception;
            string           message = "test";

            Guid   guid         = Guid.NewGuid();
            Stream memoryStream = new MemoryStream();
            Dictionary <object, object> data = new Dictionary <object, object>
            {
                { guid, 16 },
                { "test", 16 },
                { "foo", memoryStream }
            };

            try
            {
                throw new CustomException(4, "a stack trace", message, data, null);
            }
            catch (CustomException ex)
            {
                exception  = ex;
                sException = new SerializableException(exception, false, true);
            }

            Assert.Equal(16, (int)(sException.Data[guid]));
            Assert.Null(sException.Data["foo"]);
            Assert.Equal(16, (int)(sException.Data["test"]));
            AssertEqualExceptions(sException, exception, false, true);
            memoryStream.Dispose();
        }
コード例 #9
0
 public void SetShowCrashReport(string base64ExceptionString, int attempts)
 {
     Attempts = attempts;
     Base64ExceptionString = base64ExceptionString;
     SerializedException   = SerializableException.FromBase64String(Base64ExceptionString);
     IsReport = true;
 }
コード例 #10
0
 internal CustomUIEventArgs(UIMode uiMode, SerializableException exception, Report report)
 {
     this.UIMode    = uiMode;
     this.Report    = report;
     this.Exception = exception;
     this.Result    = new UIDialogResult(ExecutionFlow.BreakExecution, SendReport.DoNotSend);
 }
コード例 #11
0
        public void ExceptionObjectDictionary()
        {
            SerializableException sException;

            System.Exception exception;
            string           message = "test";

            Guid guid = Guid.NewGuid();
            SerializableException       serializableException = new SerializableException(new InvalidOperationException(message));
            Dictionary <object, object> data = new Dictionary <object, object>
            {
                { guid, 16 },
                { "foo", serializableException }
            };

            try
            {
                throw new CustomException(4, "a stack trace", message, data, null);
            }
            catch (CustomException ex)
            {
                exception  = ex;
                sException = new SerializableException(exception, false, true);
            }

            Assert.Equal(16, (int)(sException.Data[guid]));
            Assert.Equal((object)serializableException, sException.Data["foo"]);
            AssertEqualExceptions(sException, exception, false, true);
        }
コード例 #12
0
 internal static UIDialogResult ShowDialog(UIMode uiMode, SerializableException exception, Report report)
 {
     if (uiMode == UIMode.Minimal)
     {
         // ToDo:  Create WPF dialogs
         return(new Minimal().ShowDialog(report));
     }
     if (uiMode == UIMode.Normal)
     {
         // ToDo:  Create WPF dialogs
         using (var ui = new Normal())
         {
             return(ui.ShowDialog(report));
         }
     }
     if (uiMode == UIMode.Full)
     {
         // ToDo:  Create WPF dialogs
         using (var ui = new Full())
         {
             return(ui.ShowDialog(exception, report));
         }
     }
     throw NBugConfigurationException.Create(() => Settings.UIMode,
                                             "Parameter supplied for settings property is invalid.");
 }
コード例 #13
0
        public void ExceptionFullyMixedDictionary()
        {
            SerializableException sException;

            System.Exception exception;
            string           message      = "test";
            string           innerMessage = "inner test";

            Guid   guid         = Guid.NewGuid();
            Stream memoryStream = new MemoryStream();
            SerializableException       serializableException = new SerializableException(new InvalidOperationException(message));
            Dictionary <object, object> data = new Dictionary <object, object>
            {
                { guid, 16 },
                { "test", serializableException },
                { "foo", memoryStream }
            };

            try
            {
                throw new CustomException(4, "a stack trace", message, data, new CustomException(4, "a stack trace", innerMessage, null, null));
            }
            catch (CustomException ex)
            {
                exception  = ex;
                sException = new SerializableException(exception, true, true);
            }

            Assert.Equal(16, (int)(sException.Data[guid]));
            Assert.Null(sException.Data["foo"]);
            Assert.Equal((object)serializableException, sException.Data["test"]);
            AssertEqualExceptions(sException, exception, true, true);
            memoryStream.Dispose();
        }
コード例 #14
0
        public void ExceptionPrimativeDictionary()
        {
            SerializableException sException;

            System.Exception exception;
            string           message = "test";

            Dictionary <string, object> data = new Dictionary <string, object>
            {
                { "test", 16 },
                { "foo", "bar" }
            };

            try
            {
                throw new CustomException(4, "a stack trace", message, data, null);
            }
            catch (CustomException ex)
            {
                exception  = ex;
                sException = new SerializableException(exception, false, true);
            }

            Assert.Equal((object)"bar", sException.Data["foo"]);
            Assert.Equal(16, (int)(sException.Data["test"]));
            AssertEqualExceptions(sException, exception, false, true);
        }
コード例 #15
0
        internal UIDialogResult ShowDialog(SerializableException exception, Report report)
        {
            this.Text = string.Format("{0} {1}", report.GeneralInfo.HostApplication, Settings.Resources.UI_Dialog_Full_Title);

            // Fill in the 'General' tab
            this.warningPictureBox.Image      = SystemIcons.Warning.ToBitmap();
            this.exceptionTextBox.Text        = exception.Type;
            this.exceptionMessageTextBox.Text = exception.Message;
            this.targetSiteTextBox.Text       = exception.TargetSite;
            this.applicationTextBox.Text      = report.GeneralInfo.HostApplication + " [" + report.GeneralInfo.HostApplicationVersion + "]";
            this.nbugTextBox.Text             = report.GeneralInfo.NBugVersion;
            this.dateTimeTextBox.Text         = report.GeneralInfo.DateTime;
            this.clrTextBox.Text = report.GeneralInfo.CLRVersion;

            // Fill in the 'Exception' tab
            this.exceptionDetails.Initialize(exception);

            // ToDo: Fill in the 'Report Contents' tab);
            this.ShowDialog();
            this.descriptionTextBox.Focus();

            // Write back the user description (as we passed 'report' as a reference since it is a refence object anyway)
            report.GeneralInfo.UserDescription = this.descriptionTextBox.Text;
            return(this.uiDialogResult);
        }
コード例 #16
0
    public static bool TryGetExceptionFromCliArgs(string[] args, [NotNullWhen(true)] out SerializableException?exception)
    {
        exception = null;
        try
        {
            var commandArgument   = args.SingleOrDefault(x => x == "crashreport");
            var parameterArgument = args.SingleOrDefault(x => x.Contains("-exception="));

            if (commandArgument is not null && parameterArgument is not null)
            {
                var exceptionString = parameterArgument.Split("=", count: 2)[1].Trim('"');

                exception = SerializableException.FromBase64String(exceptionString);
                return(true);
            }
        }
        catch (Exception ex)
        {
            // Report the current exception.
            exception = ex.ToSerializableException();

            Logger.LogCritical($"There was a problem: '{ex}'.");
            return(true);
        }

        return(false);
    }
コード例 #17
0
        private static void GetExceptionDescription(SerializableException itemEx, StringBuilder sbuilder)
        {
            while (true)
            {
                if (itemEx.Data == null || itemEx.Data.Count == 0)
                {
                    sbuilder.AppendFormat("\tType: {0}\r\n\tMessage: {1}\r\n\tStack: {2}\r\n\r\n", itemEx.ExceptionType, itemEx.Message.Replace("\r", "\\r").Replace("\n", "\\n"), itemEx.StackTrace);
                }
                else
                {
                    sbuilder.AppendFormat("\tType: {0}\r\n\tMessage: {1}\r\n\tData:\r\n",
                                          itemEx.ExceptionType,
                                          itemEx.Message.Replace("\r", "\\r").Replace("\n", "\\n"));

                    foreach (var dataItem in itemEx.Data)
                    {
                        sbuilder.AppendFormat("\t\t{0}: {1}\r\n", dataItem.Key, dataItem.Value);
                    }

                    sbuilder.AppendFormat("\tStack: {0}\r\n\r\n",
                                          itemEx.StackTrace);
                }
                if (itemEx.InnerException is null)
                {
                    break;
                }
                itemEx = itemEx.InnerException;
            }
        }
コード例 #18
0
        internal ExecutionFlow Report(Exception exception, ExceptionThread exceptionThread)
        {
            try
            {
                Logger.Trace("Starting to generate a bug report for the exception.");
                var serializableException = new SerializableException(exception);
                var report = new Report(serializableException);

                var handler = ProcessingException;
                if (handler != null)
                {
                    Logger.Trace("Notifying the user before handling the exception.");

                    // Allowing user to add any custom information to the report
                    handler(exception, report);
                }

                //var uiDialogResult = UISelector.DisplayBugReportUI(exceptionThread, serializableException, report);
                //if (uiDialogResult.Report == SendReport.Send)
                //{
                //	this.CreateReportZip(serializableException, report);
                //}

                //return uiDialogResult.Execution;
            }
            catch (Exception ex)
            {
                Logger.Error("An exception occurred during bug report generation process. See the inner exception for details.", ex);
                //return ExecutionFlow.BreakExecution; // Since an internal exception occured
            }
            return(default(ExecutionFlow)); //  uiDialogResult.Execution;
        }
コード例 #19
0
        public static bool TryGetExceptionFromCliArgs(string[] args, [NotNullWhen(true)] out SerializableException?exception)
        {
            exception = null;
            try
            {
                if (args.Length < 2)
                {
                    return(false);
                }

                if (args[0].Contains("crashreport") && args[1].Contains("-exception="))
                {
                    var exceptionString = args[1].Split("=", count: 2)[1].Trim('"');

                    exception = SerializableException.FromBase64String(exceptionString);
                    return(true);
                }
            }
            catch (Exception ex)
            {
                // Report the current exception.
                exception = ex.ToSerializableException();

                Logger.LogCritical($"There was a problem: '{ex}'.");
                return(true);
            }

            return(false);
        }
コード例 #20
0
        /// <summary>
        /// Generates a URL to create a new issue on GitHub.
        /// <see href="https://help.github.com/en/articles/about-automation-for-issues-and-pull-requests-with-query-parameters"/>
        /// </summary>
        /// <param name="url">url to create a new issue for the project.</param>
        /// <param name="exception">The exception to report.</param>
        /// <param name="exceptionInfo">Info string for GE specific exceptions (like GitExtUtils.ExternalOperationException) unknown in BugReporter.</param>
        /// <param name="environmentInfo">Git version, directory etc.</param>
        /// <param name="additionalInfo">Information from the popup textbox.</param>
        /// <returns>The URL as a string</returns>
        public string?Build(string url, SerializableException exception, string exceptionInfo, string?environmentInfo, string?additionalInfo)
        {
            if (string.IsNullOrWhiteSpace(url) || exception is null)
            {
                return(null);
            }

            if (!Uri.TryCreate(url, UriKind.Absolute, out Uri validatedUri) ||
                !(validatedUri.Scheme == Uri.UriSchemeHttp || validatedUri.Scheme == Uri.UriSchemeHttps))
            {
                return(null);
            }

            string separator = !string.IsNullOrWhiteSpace(validatedUri.Query) ? "&" : "?";

            string subject = $"[NBug] {exception.Message}";

            if (subject.Length > 69)
            {
                // if the subject is longer than 70 characters, trim it
                subject = subject.Substring(0, 66) + "...";
            }

            string urlEncodedError = _errorReportUrlBuilder.Build(exception, exceptionInfo, environmentInfo, additionalInfo);

            return($"{validatedUri}{separator}title={Uri.EscapeDataString(subject)}&{urlEncodedError}");
        }
コード例 #21
0
        public DialogResult ShowDialog(Exception exception, string environmentInfo)
        {
            _lastException   = new SerializableException(exception);
            _lastReport      = new Report(_lastException);
            _environmentInfo = environmentInfo;

            Text = $@"{_lastReport.GeneralInfo.HostApplication} {_title.Text}";

            // Fill in the 'General' tab
            warningPictureBox.Image      = SystemIcons.Warning.ToBitmap();
            exceptionTextBox.Text        = _lastException.Type;
            exceptionMessageTextBox.Text = _lastException.Message;
            targetSiteTextBox.Text       = _lastException.TargetSite;
            applicationTextBox.Text      = $@"{_lastReport.GeneralInfo.HostApplication} [{_lastReport.GeneralInfo.HostApplicationVersion}]";
            gitTextBox.Text      = _lastReport.GeneralInfo.GitVersion;
            dateTimeTextBox.Text = _lastReport.GeneralInfo.DateTime;
            clrTextBox.Text      = _lastReport.GeneralInfo.ClrVersion;

            // Fill in the 'Exception' tab
            exceptionDetails.Initialize(_lastException);

            DialogResult = DialogResult.None;

            // ToDo: Fill in the 'Report Contents' tab);
            var result = ShowDialog();

            // Write back the user description (as we passed 'report' as a reference since it is a reference object anyway)
            _lastReport.GeneralInfo.UserDescription = descriptionTextBox.Text;

            return(result);
        }
コード例 #22
0
                public void CompleteDeserialization(object _exception)
                {
                    SerializableException exception = (SerializableException)_exception;

                    exception.SerializeObjectState += HandleSerialization;

                    exception.Data = Data;
                }
コード例 #23
0
 internal CustomSubmissionEventArgs(string fileName, Stream file, Report report, SerializableException exception)
 {
     FileName  = fileName;
     File      = file;
     Report    = report;
     Exception = exception;
     Result    = false;
 }
コード例 #24
0
            public override bool Send(string fileName, Stream file, Report report, SerializableException exception)
            {
                report.CustomInfo = new BugReportExtraInfo();

                var data = string.Concat("<BugReport>", report.ToString(), exception.ToString(), "</BugReport>");

                return(_sender.SendData(CompressionTools.ZipString(data)));
            }
コード例 #25
0
        /** <inheritDoc /> */
        protected override void CheckError(Exception err)
        {
            Assert.IsTrue(err != null);

            SerializableException err0 = err as SerializableException;

            Assert.IsTrue(err0 != null);
            Assert.AreEqual(ErrMsg, err0.Msg);
        }
コード例 #26
0
 private void RunFormTest(Func <BugReportForm, Task> testDriverAsync, SerializableException exception, string environmentInfo, DialogResult expected)
 {
     UITest.RunForm(
         () =>
     {
         Assert.AreEqual(expected, _form.ShowDialog(owner: null, exception, environmentInfo, canIgnore: true, showIgnore: false, focusDetails: false));
     },
         testDriverAsync);
 }
コード例 #27
0
        private void FillInnerExceptionTree(SerializableException innerException, TreeNode innerNode)
        {
            _exceptionDetailsList.Add(innerNode.Nodes.Add(innerException.Type), innerException);

            if (innerException.InnerException != null)
            {
                FillInnerExceptionTree(innerException.InnerException, innerNode.Nodes[0]);
            }
        }
コード例 #28
0
        public void TryParseSerializableException_Should_ReturnTrue_ForTypeOfExceptionInfo()
        {
            var exception = new SerializableException(new ApplicationException());

            var result = exception.TryParseSerializableException(out var parsedException);

            result.Should().BeTrue();
            parsedException.Should().NotBeNull();
        }
コード例 #29
0
        // This is not static for future performance improvements (like totally eliminating calls to Storer object)
        private void VerifyIndividualReportItems(Stream reportFile, bool verifyCustomReport)
        {
            var zipStorer = ZipStorer.Open(reportFile, FileAccess.Read);

            using (var zipItemStream = new MemoryStream())
            {
                SerializableException serializableException = null;
                Report report       = null;
                uint   fileSize     = 0;
                var    zipDirectory = zipStorer.ReadCentralDir();

                foreach (var entry in zipDirectory)
                {
                    if (Path.GetFileName(entry.FilenameInZip) == StoredItemFile.Exception)
                    {
                        zipItemStream.SetLength(0);
                        zipStorer.ExtractFile(entry, zipItemStream);
                        zipItemStream.Position = 0;
                        var deserializer = new XmlSerializer(typeof(SerializableException));
                        serializableException  = (SerializableException)deserializer.Deserialize(zipItemStream);
                        zipItemStream.Position = 0;
                        Assert.NotNull(XElement.Load(zipItemStream));
                    }
                    else if (Path.GetFileName(entry.FilenameInZip) == StoredItemFile.Report)
                    {
                        zipItemStream.SetLength(0);
                        zipStorer.ExtractFile(entry, zipItemStream);
                        zipItemStream.Position = 0;
                        var deserializer = new XmlSerializer(typeof(Report));
                        report = (Report)deserializer.Deserialize(zipItemStream);
                        zipItemStream.Position = 0;
                        Assert.NotNull(XElement.Load(zipItemStream));
                        if (verifyCustomReport)
                        {
                            Assert.NotNull(report.CustomInfo);
                        }
                    }
                    else if (Path.GetFileName(entry.FilenameInZip) == StoredItemFile.MiniDump)
                    {
                        fileSize = entry.FileSize;
                    }
                    else
                    {
                        Assert.True(false, "A new file type has been added to the compressed report file. A new validation check for the file should be added.");
                    }
                }

                Assert.NotNull(serializableException);
                Assert.NotNull(report);

                if (Settings.MiniDumpType != MiniDumpType.None)
                {
                    Assert.True(fileSize != 0);
                }
            }
        }
コード例 #30
0
        public void ExceptionFullyMixedDictionarySerialization()
        {
            SerializableException sException;

            System.Exception exception;
            string           message      = "test";
            string           innerMessage = "inner test";

            Guid   guid         = Guid.NewGuid();
            Stream memoryStream = new MemoryStream();
            SerializableException       serializableException = new SerializableException(new InvalidOperationException(message));
            Dictionary <object, object> data = new Dictionary <object, object>
            {
                { guid, 16 },
                { "test", serializableException },
                { "foo", memoryStream }
            };

            try
            {
                throw new CustomException(4, "a stack trace", message, data, new CustomException(4, "a stack trace", innerMessage, null, null));
            }
            catch (CustomException ex)
            {
                exception  = ex;
                sException = new SerializableException(exception, true, true);
            }

            Assert.Equal(16, (int)(sException.Data[guid]));
            Assert.Null(sException.Data["foo"]);
            Assert.Equal((object)serializableException, sException.Data["test"]);
            AssertEqualExceptions(sException, exception, true, true);

            string jsonString = sException.SerializeJson();

            Assert.NotNull(jsonString);
            Assert.NotEmpty(jsonString);
            SerializableException deserialized = jsonString.DeserializeJson <SerializableException>();

            Assert.NotNull(deserialized);
            // the data can't be verified this way (they are new instances when deserialized)
            AssertEqualExceptionsSerializable(sException, deserialized, true, false);
            Assert.Equal(sException.Data.Count, deserialized.Data.Count);
            string guidKeyString = deserialized.Data.Keys.OfType <string>().FirstOrDefault(k => k == guid.ToString());

            Assert.NotNull(guidKeyString);
            Assert.NotEmpty(guidKeyString);
            Guid guidKey = Guid.Parse(guidKeyString);

            Assert.NotNull(deserialized.Data[guidKeyString]);
            Assert.Equal(sException.Data[guid], deserialized.Data[guidKeyString]);
            AssertEqualExceptionsSerializable(serializableException, (SerializableException)deserialized.Data["test"], true, true);
            Assert.Null(deserialized.Data["foo"]);

            memoryStream.Dispose();
        }
コード例 #31
0
ファイル: Exceptions.cs プロジェクト: ItsVeryWindy/mono
		public void Exception_SerializeObjectState () {
			SerializableException exception = new SerializableException ("success");
			SerializableException deserializedException;
			BinaryFormatter binaryFormatter = new BinaryFormatter ();

			using (MemoryStream memoryStream = new MemoryStream ())
			{
				binaryFormatter.Serialize (memoryStream, exception);
				memoryStream.Flush ();

				memoryStream.Seek (0, SeekOrigin.Begin);

				deserializedException = (SerializableException)binaryFormatter.Deserialize (memoryStream);
			}

			Assert.AreEqual ("success", deserializedException.Data);
		}
コード例 #32
0
		public static void Can_Serialize_An_Exception()
		{
			var ex1 = new Exception("My Inner Exception 2");
			var ex2 = new Exception("My Exception 1", ex1);

			SerializableException originalException = new SerializableException(ex2);

			// Save the full ToString() value, including the exception message and stack trace.

			var rawBytes = originalException.SerializeException();
			SerializableException newException = rawBytes.DeSerializeException();

			string originalExceptionAsString = originalException.ToString();
			string newExceptionAsString = newException.ToString();

			// Double-check that the exception message and stack trace (owned by the base Exception) are preserved
			Assert.AreEqual(originalExceptionAsString, newExceptionAsString);
		}
コード例 #33
0
ファイル: ErrorReporter.cs プロジェクト: mgnslndh/NCrash
        /// <summary>
        /// Report exception and show UI in given thread.
        /// </summary>
        /// <param name="exception"></param>
        /// <returns></returns>
        protected virtual ExecutionFlow Report(Exception exception)
        {
            try
            {
                Logger.Trace("Starting to generate a bug report for the exception.");
                var serializableException = new SerializableException(exception);
                var report = new Report(serializableException);

                if (_settings.Plugins != null && _settings.Plugins.Count > 0)
                {
                    Logger.Trace("Processing plugins.");
                    foreach (IPlugin plugin in _settings.Plugins)
                    {
                        plugin.PreProcess(_settings);
                    }
                }

                var handler = ProcessingException;
                if (handler != null)
                {
                    Logger.Trace("Notifying the user before handling the exception.");

                    // Allowing user to add any custom information to the report
                    handler(exception, report);
                }

                var uiDialogResult = _settings.UserInterface.DisplayBugReportUI(report);

                if (uiDialogResult.SendReport)
                {
                    // Test if it has NOT been more than x many days since entry assembly was last modified)
                    if (_settings.StopReportingAfter >= 0 &&
                        InstallationDate.AddDays(_settings.StopReportingAfter).CompareTo(DateTime.Now) <= 0)
                    {
                        // TODO: this should be moved to task
                        // clear written reports
                        Logger.Trace("As per setting 'Settings.StopReportingAfter(" + _settings.StopReportingAfter +
                                        ")', bug reporting feature was enabled for a certain amount of time which has now expired: Truncating all expired bug reports. Bug reporting is now disabled.");
                        _storage.Clear();
                    }
                    else
                    {
                        _storage.Write(report);

                        // notify dispatcher to dispatch
                        lock (_backgroundLock)
                        {
                            Monitor.PulseAll(_backgroundLock);
                        }
                    }

                }

                if (_settings.Plugins != null && _settings.Plugins.Count > 0)
                {
                    Logger.Trace("PostProcessing plugins.");
                    foreach (IPlugin plugin in _settings.Plugins)
                    {
                        plugin.PostProcess(_settings);
                    }
                }

                return uiDialogResult.Execution;
            }
            catch (Exception ex)
            {
                Logger.Error("An exception occurred during bug report generation process. See the inner exception for details.", ex);
                return ExecutionFlow.BreakExecution; // Since an internal exception occured
            }
        }
コード例 #34
0
ファイル: MailSender.cs プロジェクト: mgnslndh/NCrash
 private void WriteException(SerializableException exception, StringBuilder sb)
 {
     var serializer = new XmlSerializer(typeof(SerializableException));
     TextWriter writer = new StringWriter(sb);
     serializer.Serialize(writer, exception);
 }
コード例 #35
0
ファイル: ReportStorage.cs プロジェクト: mgnslndh/NCrash
 private void WriteException(ZipStorer zipStorer, SerializableException serializableException)
 {
     using (var stream = new MemoryStream())
     {
         // Store the exception as separate file
         var serializer = new XmlSerializer(typeof(SerializableException));
         serializer.Serialize(stream, serializableException);
         stream.Position = 0;
         zipStorer.AddStream(ZipStorer.Compression.Deflate, StoredItemFile.Exception, stream, DateTime.UtcNow,
                             string.Empty);
     }
 }
コード例 #36
0
ファイル: UI_Home.cs プロジェクト: 9001/Loopstream
        private void pictureBox1_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == System.Windows.Forms.MouseButtons.Right)
            {
                long time = DateTime.UtcNow.Ticks / 10000;
                if (time < lastclick + 1000)
                {
                    z("Faking crash");
                    try
                    {
                        Program.popception();
                    }
                    catch (Exception ex)
                    {
                        throw ex; // UNCOMMENT for production
                        SerializableException se = new SerializableException(ex);
                        GeneralInfo gi = new GeneralInfo(se, ex);
                        string serialized = gi.ToString();
                    }

                    Clipboard.Clear();
                    Application.DoEvents();
                    Clipboard.SetText(Program.DBGLOG);
                    Application.DoEvents();
                    MessageBox.Show("Debug information placed on clipboard\n\nGo to pastebin and Ctrl-V");
                }
                lastclick = time;
            }
        }