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):
1 2 3 4 |
void Application_Error(object sender, EventArgs e) { ApplicationErrorHandler.Application_Error(sender, e); } |
The main class:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 |
/// <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", "unspecified@localhost"); // 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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 |
<?xml version="1.0"?> <configuration> <section name="errorSettings" type="System.Configuration.NameValueSectionHandler" /> </configSections> <system.net> <mailSettings> <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. --> <!-- 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> |
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