Working around global.asax at runtime

While this doesn't classify as great development practice, sometimes a well tested hotfix to a production site is just the right thing to solve a client's problem quickly.  In our case, the problem was too many emails being sent due to ClientScriptExceptions (our own custom Exception that is thrown when a Javascript onerror event fires in the browser ... yes, we do some tricky stuff with an Image in Javascript to get the message back to the server).  Anyway, the exception is caught in global.asax.cs in the Application_Error method.

So, how do we override this behavior at runtime?  Change the global.asax to the following:

  1 <%@ Application Codebehind="Global.asax.cs" Inherits="Thycotic.xxx.Web.Global" %>
  2 <script runat="server" language="C#">
  3 protected new void Application_Error(Object sender, EventArgs e)
  4 {
  5 	if (System.Web.HttpContext.Current != null) 
  6 	{
  7 		Exception outer = HttpContext.Current.Server.GetLastError();
  8 		Exception inner = outer.InnerException;
  9 		Exception actualException = (inner == null) ? outer : inner;
 10 		if (!(actualException is Thycotic.Foundation.WebControls.ClientScriptException)) 
 11 		{
 12 			 Thycotic.Foundation.ExceptionManager.HandleApplicationErrorEvent();
 13 		}
 14 	}
 15 }
 16 </script>	
Voila!  Problem fixed without a recompile or binary redeployment!  Unfortunately, we hadn't marked the original method as virtual so we had to use "new" on the method signature - something we very seldom use.

Hope you find this trick useful and never have to use it! :-)

Jonathan Cogley is the CEO and founder of thycotic, a .NET consulting company and ISV in Washington DC.  thycotic has just released Thycotic Secret Server which is a secure web-based solution to both "Where is my Hotmail password?" and "Who has the password for our domain name?".  Secret Server is the leader in secret management and sharing within companies and teams.

No Comments