ASP.Net Unhandled Exception Handling: Email exception with MiniDump

By | 2010-07-02

For most ASP.Net applications I make I add some code that emails me any unhandled exceptions. This way I immediately know when something has gone wrong with an application. The email contains a lot of useful information, including a MiniDump of the process.

If you are not familiar with it, a MiniDump is a snapshot of the process when it failed which can be loaded into Visual Studio as a “paused project”. You can look at stack trace, locals, execute Immediate commands, etc. You can also use WinDbg to load it with CLR extensions for some in-depth debugging. Very handy.

Using this with Microsoft Azure Cloud apps will ensure proper debugging capability even when you can’t attach a debugger or log on and read the event log.

Also: You don’t have to recreate the exception because you already have a breakpoint where it happened in the code. No more poor bug reports or elusive bugs.

A couple of points before we get on to the code:

  • Uses Nini for config reading, so you need to reference it from your project.
  • Needs write-rights to a folder for MiniDump to work.
  • You have to change: Global.asax and Web.Config
  • You have to create a new class called ApplicationErrorHandler and put the main class in it.

To implement, add this to Global.asax (add a Global.asax if you don’t have it already):

        void Application_Error(object sender, EventArgs e)
        {
            ApplicationErrorHandler.Application_Error(sender, e);
        }

The main class:

    /// <summary>
    /// Use this class from Global.asax like this:
    /// void Application_Error(object sender, EventArgs e)
    /// {
    ///     ApplicationErrorHandler.Application_Error(Server, Request, sender, e);
    /// }
    /// And add required config to web.config.
    /// </summary>
    internal static class ApplicationErrorHandler
    {
        #region Application_Error - handle error
        // Config is located in web.config
        public static IConfigSource ConfigSource = new DotNetConfigSource(Utils.ResolvePath(@"~\web.config"));
        public static IConfig ErrorSettings = ConfigSource.Configs["errorSettings"];

        public static void Application_Error(object sender, EventArgs e)
        {
            HttpRequest Request = HttpContext.Current.Request;
            HttpServerUtility Server = HttpContext.Current.Server;

            string assemblyName = System.Reflection.Assembly.GetExecutingAssembly().GetName().FullName;
            string appName = ErrorSettings.GetString("AppName", assemblyName);

            //get reference to the source of the exception chain
            Exception ex = Server.GetLastError().GetBaseException();
            string username = "";
            try
            {
                username = Account.Permissions.currentUserName;
            }
            catch (Exception ex3)
            {
            }

            string text = "ApplicationName: " + System.Reflection.Assembly.GetExecutingAssembly().GetName().FullName +
                          "UserName: " + username +
                          "\nTime: " + DateTime.Now +
                          "\n\nMESSAGE: " + ex.Message +
                          "\nSOURCE: " + ex.Source +
                          "\nFORM: " + Request.Form.ToString() +
                          "\nQUERYSTRING: " + Request.QueryString.ToString() +
                          "\nTARGETSITE: " + ex.TargetSite +
                          "\nSTACKTRACE: " + ex.StackTrace;

            // For MiniDump
            string dumpFolder = Utils.ResolvePath(ErrorSettings.GetString("MiniDumpFolder", @"~\MiniDumps"));
            string dumpFile = Path.Combine(dumpFolder, DateTime.Now.ToString("yyyyMMdd_HHmmss") + "_MiniDump.dmp");
            // For emailing
            string defaultEmail = ErrorSettings.GetString("DefaultEmail", "[email protected]");

            // Log to EventLog?)
            if (ErrorSettings.GetBoolean("EnableEventLog", false))
            {

                try
                {
                    string source = ErrorSettings.GetString("EventLogSource", appName);
                    string logName = ErrorSettings.GetString("EventLogName", "Application");
                    string eventText = text + "\n\nMiniDump file: " + dumpFile + "\n";

                    // Make sure we have source in EventLog
                    if (!EventLog.SourceExists(source))
                        EventLog.CreateEventSource(source, logName);

                    // Write
                    EventLog.WriteEntry(source, eventText, EventLogEntryType.Error, 234);
                }
                catch (Exception ex2)
                {
                    // Ignore exception so we don't get an exception loop
                    Trace.WriteLine(
                        string.Format("Exception while handling unhandled exception: While writing to EventLog: {0}",
                                      ex2.ToString()));
                }
            }

            // Sending exception email?
            if (ErrorSettings.GetBoolean("EnableExceptionEmail", false))
            {

                try
                {
                    // Make message
                    MailMessage message = new MailMessage();
                    message.From =
                        new MailAddress(ErrorSettings.GetString("ExceptionEmailFrom", defaultEmail));
                    message.To.Add(ErrorSettings.GetString("ExceptionEmailTo", defaultEmail));
                    message.Subject = ErrorSettings.GetString("ExceptionEmailSubject", appName + " Exception");
                    message.Body = text;
                    // Create server object
                    //SmtpClient smtp = new SmtpClient(SMTPServer, SMTPPort);
                    SmtpClient smtp = new SmtpClient();
                    // Credentials?
                    //if (!string.IsNullOrEmpty(SMTPUserName) && !string.IsNullOrEmpty(SMTPPassword))
                    //    smtp.Credentials = new NetworkCredential(SMTPUserName, SMTPPassword, SMTPDomain);
                    //smtp.EnableSsl = SMTPSSL;

                    // Send message
                    smtp.Send(message);
                }
                catch (Exception ex2)
                {
                    // Ignore exception so we don't get an exception loop
                    Trace.WriteLine(
                        string.Format(
                            "Exception while handling unhandled exception: While sending Exception email: {0}",
                            ex2.ToString()));
                }
            }

            if (ErrorSettings.GetBoolean("EnableMiniDump", false))
            {

                try
                {

                    // Send e-mail with MiniDump
                    if (!Directory.Exists(dumpFolder))
                        Directory.CreateDirectory(dumpFolder);

                    // Make MiniDump
                    MiniDumper.Write(dumpFile);
                }
                catch (Exception ex2)
                {
                    // Ignore exception so we don't get an exception loop
                    Trace.WriteLine(
                        string.Format(
                            "Exception while handling unhandled exception: While sending writing MiniDump file \"{0}\": {1}",
                            dumpFile,
                            ex2.ToString()));
                }

                try
                {
                    if (ErrorSettings.GetBoolean("EnableMiniDumpEmail", false))
                    {
                        // Make message
                        MailMessage message = new MailMessage();
                        message.From =
                            new MailAddress(ErrorSettings.GetString("MiniDumpEmailFrom", defaultEmail));
                        message.To.Add(ErrorSettings.GetString("MiniDumpEmailTo", defaultEmail));
                        message.Subject = ErrorSettings.GetString("MiniDumpEmailSubject", appName + " Exception MiniDump");
                        message.Body = text;
                        // Make attachment and add to message
                        Attachment miniDumpFileAttachment = new Attachment(dumpFile);
                        message.Attachments.Add(miniDumpFileAttachment);

                        // Create server object
                        //SmtpClient smtp = new SmtpClient(SMTPServer, SMTPPort);
                        SmtpClient smtp = new SmtpClient();

                        // Send message
                        smtp.Send(message);
                    }
                }
                catch (Exception ex2)
                {
                    // Ignore exception so we don't get an exception loop
                    Trace.WriteLine(
                        string.Format(
                            "Exception while handling unhandled exception: While sending Exception MiniDump email: {0}",
                            ex2.ToString()));
                }
            }
        }
        #endregion
        #region Path utils
        public static class Utils
        {
            //private static log4net.ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
            //public static string CurrentDirectory { get { return Directory.GetCurrentDirectory(); } }
            //public static string CurrentAssemblyPath { get { return System.Reflection.Assembly.GetExecutingAssembly().Location; } }
            //public static string CurrentAssemblyFileName { get { return System.IO.Path.GetFileName(CurrentAssemblyPath); } }
            //public static string CurrentAssemblyDirectory { get { return System.IO.Path.GetDirectoryName(CurrentAssemblyPath); } }

            /// <summary>
            /// Resolve a relative/obscure path to a plain directory. Also replaces ~ with current appdir
            /// For example "c:\temp\..\test", would return "c:\test".
            /// </summary>
            /// <param name="File"></param>
            /// <returns></returns>
            public static string ResolvePath(string File)
            {
                if (string.IsNullOrEmpty(File))
                    return File;

                string f = File;

                // Replace %TEMP%
                if (f.Contains("%TEMP%"))
                    f = f.Replace("%TEMP%", System.IO.Path.GetTempPath());

                // Support multiple OS
                f = f.Replace(@"\", Path.DirectorySeparatorChar.ToString());
                f = f.Replace(@"/", Path.DirectorySeparatorChar.ToString());

                // Replace ~
                f = f.Replace("~", System.Web.HttpContext.Current.Request.PhysicalApplicationPath);

                return Path.GetFullPath(f);
            }
        }
        #endregion
        #region MiniDump Writer
        internal class MiniDumper
        {
            [Flags]
            public enum Typ : uint
            {
                // From dbghelp.h:
                MiniDumpNormal = 0x00000000,
                MiniDumpWithDataSegs = 0x00000001,
                MiniDumpWithFullMemory = 0x00000002,
                MiniDumpWithHandleData = 0x00000004,
                MiniDumpFilterMemory = 0x00000008,
                MiniDumpScanMemory = 0x00000010,
                MiniDumpWithUnloadedModules = 0x00000020,
                MiniDumpWithIndirectlyReferencedMemory = 0x00000040,
                MiniDumpFilterModulePaths = 0x00000080,
                MiniDumpWithProcessThreadData = 0x00000100,
                MiniDumpWithPrivateReadWriteMemory = 0x00000200,
                MiniDumpWithoutOptionalData = 0x00000400,
                MiniDumpWithFullMemoryInfo = 0x00000800,
                MiniDumpWithThreadInfo = 0x00001000,
                MiniDumpWithCodeSegs = 0x00002000,
                MiniDumpWithoutAuxiliaryState = 0x00004000,
                MiniDumpWithFullAuxiliaryState = 0x00008000,
                MiniDumpWithPrivateWriteCopyMemory = 0x00010000,
                MiniDumpIgnoreInaccessibleMemory = 0x00020000,
                MiniDumpValidTypeFlags = 0x0003ffff,
            };

            //typedef struct _MINIDUMP_EXCEPTION_INFORMATION {
            //    DWORD ThreadId;
            //    PEXCEPTION_POINTERS ExceptionPointers;
            //    BOOL ClientPointers;
            //} MINIDUMP_EXCEPTION_INFORMATION, *PMINIDUMP_EXCEPTION_INFORMATION;
            [StructLayout(LayoutKind.Sequential, Pack = 4)]  // Pack=4 is important! So it works also for x64!
            struct MiniDumpExceptionInformation
            {
                public uint ThreadId;
                public IntPtr ExceptioonPointers;
                [MarshalAs(UnmanagedType.Bool)]
                public bool ClientPointers;
            }

            //BOOL
            //WINAPI
            //MiniDumpWriteDump(
            //    __in HANDLE hProcess,
            //    __in DWORD ProcessId,
            //    __in HANDLE hFile,
            //    __in MINIDUMP_TYPE DumpType,
            //    __in_opt PMINIDUMP_EXCEPTION_INFORMATION ExceptionParam,
            //    __in_opt PMINIDUMP_USER_STREAM_INFORMATION UserStreamParam,
            //    __in_opt PMINIDUMP_CALLBACK_INFORMATION CallbackParam
            //    );
            [DllImport("dbghelp.dll",
              EntryPoint = "MiniDumpWriteDump",
              CallingConvention = CallingConvention.StdCall,
              CharSet = CharSet.Unicode,
              ExactSpelling = true, SetLastError = true)]
            static extern bool MiniDumpWriteDump(
              IntPtr hProcess,
              uint processId,
              IntPtr hFile,
              uint dumpType,
              ref MiniDumpExceptionInformation expParam,
              IntPtr userStreamParam,
              IntPtr callbackParam);

            [DllImport("kernel32.dll", EntryPoint = "GetCurrentThreadId", ExactSpelling = true)]
            static extern uint GetCurrentThreadId();

            [DllImport("kernel32.dll", EntryPoint = "GetCurrentProcess", ExactSpelling = true)]
            static extern IntPtr GetCurrentProcess();

            [DllImport("kernel32.dll", EntryPoint = "GetCurrentProcessId", ExactSpelling = true)]
            static extern uint GetCurrentProcessId();

            public static bool Write(string fileName)
            {
                return Write(fileName, Typ.MiniDumpWithFullMemory);
            }
            public static bool Write(string fileName, Typ dumpTyp)
            {
                using (var fs = new System.IO.FileStream(fileName, System.IO.FileMode.Create, System.IO.FileAccess.Write, System.IO.FileShare.None))
                {
                    MiniDumpExceptionInformation exp;
                    exp.ThreadId = GetCurrentThreadId();
                    exp.ClientPointers = false;
                    exp.ExceptioonPointers = System.Runtime.InteropServices.Marshal.GetExceptionPointers();
                    bool bRet = MiniDumpWriteDump(
                      GetCurrentProcess(),
                      GetCurrentProcessId(),
                      fs.SafeFileHandle.DangerousGetHandle(),
                      (uint)dumpTyp,
                      ref exp,
                      IntPtr.Zero,
                      IntPtr.Zero);
                    return bRet;
                }
            }
        }
        #endregion
    }

And web.config needs some additional info:

<?xml version="1.0"?>
<configuration>
    <section name="errorSettings" type="System.Configuration.NameValueSectionHandler" />
  </configSections>

  <system.net>
    <mailSettings>
      <smtp from="[email protected]">
        <network host="localhost" port="25" />
      </smtp>
    </mailSettings>
  </system.net>

  <errorSettings>
    <!-- Application name. If not set will attempt to use FullName of assembly. -->
    <add key="AppName" value="MyAwesomeApp" />

    <!-- Default email to set for ExceptionEmailFrom, ExceptionEmailTo, MiniDumpEmailFrom and MiniDumpEmailTo if they are not specified specifically in this config. (For lazy people)
         If this is not set then you must uncomment them bellow. -->
    <add key="DefaultEmail" value="[email protected]" />

    <!-- Send exception on email. Default: false
        Tip: If MiniDump exception sending works then maybe you don't need this.
    -->
    <add key="EnableExceptionEmail" value="true"/>
    <!-- <add key="ExceptionEmailFrom" value="[email protected]"/>-->
    <!-- <add key="ExceptionEmailTo" value="[email protected]"/>-->
    <!-- Will use AppName and default to "appname Exception" if not specified. -->
    <!--<add key="ExceptionEmailSubject" value="AppName Exception"/>-->

    <!-- MiniDumps are images of the app in the state it was at the time of exception.
         They can be loaded into Visual Studio to get a breakpoint and stack trace of when error occurred.
         Enabling them here will write them to a folder on server and email them.
         -->

    <!-- Write MiniDump to file. Default: false -->
    <add key="EnableMiniDump" value="true"/>
    <!-- Send MiniDump on email. Default: false -->
    <add key="EnableMiniDumpEmail" value="true"/>
    <!-- MiniDumpFolder specifies where to store MiniDumps.
         Web application needs write rights to this folder. If folder doesn't exist it will be created, and if so web app needs write rights to the parent folder.
         Use ~ for application root dir.
         Defaults to "~\MiniDumps" if not specified.
    -->
    <!-- <add key="MiniDumpFolder" value="~\MiniDumps"/>-->
    <!-- <add key="MiniDumpEmailFrom" value="[email protected]"/> -->
    <!-- <add key="MiniDumpEmailTo" value="[email protected]"/> -->
    <!-- Will use AppName and default to "AppName Exception MiniDump" if not specified. -->
    <!-- <add key="MiniDumpEmailSubject" value="AppName Exception MiniDump"/> -->

    <!-- Write to EventLog: Default: false
        Note: If EventLogSource doesn't exist then app may need privelegies to create it. -->
    <!--<add key="EnableEventLog" value="true"/>-->
    <!-- Will use AppName if not specified -->
    <!--<add key="EventLogSource" value="AppName"/>-->
    <!-- What event log to use, normally either "Application" or "System". Default: Application -->
    <!--<add key="EventLogName" value="Application"/>-->
  </errorSettings>

</configuration>

One thought on “ASP.Net Unhandled Exception Handling: Email exception with MiniDump

  1. poker regeln

    I should digg your article so more people are able to see it, very helpful, I had a tough time finding the results searching on the web, thanks.

    – Joe

    Reply

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.