Dot Net

Syrinx .NET Development Blog
Need help on your project? info@syrinx.com, or toll free (888) 579-7469, press 1

Know your application and its running context

Rather than talk about particular pieces of coding, I like to focus on the few concepts of coding and development, which are universal to any development practice. I recently finished working on a .NET enterprise project recently.  It was a typical multi-tiered application with Windows client, Web, and database tiers.   I observed some code which was easy to overlook and identified a problem lurking within. 

 In a multi-tiered application, some code is specific to a particular tier, some is shared across the tiers providing some common services, frame work etc. When developing common module code in a multi tiered application, it is easy to forget and overlook the context in which code will be executed (any of the tiers, potentially).  
 As an example, a simple piece of code such as (made very simple to embolden the point)
 
        
public void LogException(Exception ex)
{
            if (!EventLog.SourceExists(ex.Source))
              { // raises exception in Web tier
               
EventLog.CreateEventSource(ex.Source, "Application");  
}
             EventLog myLog = new EventLog();
            myLog.Source = ex.Source;
             myLog.WriteEntry(ex.Message);

}

In a Windows client context and unit tests the code worked as intended by the developer.  In a web application context, CreateEventSource would raise a Security Exception.  It’s because the web application is by default running under a low-privileged account.  Now add a few layers of encapsulation, delegation (typical in an enterprise application) and wrap it around an empty try catch block. You then have no idea what happened when an exception occurs. 

 When writing common code and the unit tests around it, we tend to forget the context in which the code could get executed.  I am not going to explain how to create an event log entry or how to improve the code to better handle these exceptions.  There are many web sites that dive deep into event logging and the entire exception handling API.  My point, is rather very primal – “know your application running context and consider its ramifications.” Now, why would anybody add an empty try/catch block, especially in an enterprise level application?  That’s a topic for another day. 

Comments

No Comments