0

ELMAH - a benefit to every asp.net website

by Jeremy 4. February 2010 11:33

ELMAH is an open-source .Net dll that allows for simple, pluggable exception notification and logging.  It takes all unhandled exceptions and allows the developer to configure notifications and/or logging of those exceptions.  There are many different configuration options, including where to log (in memory, database, text file, etc), and how to notify (email, twitter, etc.).  The configuration below assumes a common scenario of sending an email and logging to sql server when an unhandled exception occurs.

Steps for setup:

  1. Download the latest zip file (includes dll and documentation) http://code.google.com/p/elmah/
  2. Reference the dll from your website
  3. Run the included database script (located in the "db" folder of the downloaded zip) on the database where you would like to log exceptions
  4. Modify the config (assumes II6, see documentation on elmah site for IIS7)

<sectionGroup name="elmah">
      <section name="errorLog" requirePermission="false" type="Elmah.ErrorLogSectionHandler, Elmah" />
      <section name="errorMail" requirePermission="false" type="Elmah.ErrorMailSectionHandler, Elmah" />
    </sectionGroup>
    
    <httpHandlers>
      <add verb="POST,GET,HEAD" path="elmah.axd" type="Elmah.ErrorLogPageFactory, Elmah" />
    </httpHandlers>
    
    <httpModules>
      <add name="ErrorLog" type="Elmah.ErrorLogModule, Elmah" />
      <add name="ErrorMail" type="Elmah.ErrorMailModule, Elmah" />
    </httpModules>

    <elmah>
        <errorLog type="Elmah.SqlErrorLog, Elmah" connectionStringName="configuredConnectionString" />
        <errorMail from="fromEmail" to="developerEmail" cc="ccEmail" subject="emailSubject" smtpServer="smtpServerIP" />
    </elmah>

 

See sample web.configs: http://elmah.googlecode.com/svn/tags/REL-1.0/samples/web.config 

How to view logged exceptions:
http://website/elmah.axd

How to throw a test exception:
http://website/elmah.axd/test

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

.NET | Exception Handling

0

Try/Catch vs Global Exception-handling

by Jeremy 5. January 2010 17:51

Another developer recently asked me when try/catch blocks should be used in asp.net applications.  In most apps I write, I try not to pepper these statements throughout the code, but rather deal with exception handling on a global level.  The less code you write, the less code you have to maintain.  In my opinion, there are generally only two reasons to use try/catch statements: Either 1) you need to perform some action if the try code fails, or 2) you want to provide a more user-friendly (i.e. maintenance-developer friendly) error message.  Beyond these two cases, all unhandled exceptions can be dealt with on a global application level.  

For global exception handling, I prefer to use the open-source project ELMAH, which provides logging, notification, and UI functionality by simply plugging it in.  ELMAH performs this magic by using an http module to catch unhandled exceptions, combined with an http handler to display those logs via a UI.  However, if you don't want to use Elmah (stop being stubborn - it isn't that hard), you can always just put your exception handling code within the Application_Error method in the global.asax.

As for the two cases where try/catches should be used:
1) You need to execute some code if something fails.  Transactions are a good example - if you have a workflow that requires multiple steps to be completed within a transaction, and the first step fails, you will want to use a try/catch to perform a rollback within the finally block.

try
{
    //Start transaction
    //Perform step one
    //Perform step two
    //Commit transaction
}
catch(Exception)
{
    throw;
}
finally
{
    //Roll back the transaction
}

 

2) You want to provide an "English" error message.  Often-times, .net exception messages are fairly generic and don't always tip the developer off as to why something failed.  In these cases, you can catch the message and throw a new one that provides a more readable message.  Note that when you do this, you should always pass the caught exception to the constructor of your new exception - this way you won't lose the stack trace.


try
{
    //Get data from a vendor web service
}
catch(SqlException ex)
{
    string errorMessage = "The vendor api is not responding.  Give them hell.";
    throw new ServiceException(errorMessage, ex);
}

Currently rated 4.0 by 1 people

  • Currently 4/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

.NET | Software Maintainability | Exception Handling

1

Un-LINQ Stored Procedures

by Jeremy 18. November 2009 15:13

About a year or so ago, I read some developer opinions against the usage of stored procedures.  Jeremy Miller has several blog posts on the topic and Dino Esposito writes about the topic in his enterprise architecture book.  At the time, every application I had ever worked on had utilized stored procedures, so I was a bit perplexed as to how complex data access could be accomplished without them.

On a recent project, I decided to explore the concept that the database should be used for storage only.  I saw some validity in the idea that business logic should reside in the code, not the database (as stored procedures).  The application to which I'm referring is built upon Entity Framework, and utilizes Linq-to-entities for data access.

For simple, straight-forward queries like retrieving a set of journal entries created by a user, you can simply use something like the following:

var query = from log in Db.LogEntry where log.UserId.Equals(1) select log;

However, what about complex logic, like searching these logs while allowing the user to supply and/or choose from a long list of criteria?  Consider the following method signature:

public virtual IEnumerable<Logs> SearchLogs(int? userId, DateTime? beginDateIsAfter, DateTime? endDateIsBefore, bool? hasAttachments)
{
}


You need to search the table by not only the user id, but also a several other parameters that may or may not be provided.  Linq supports this (fluently) through the use of the extension method syntax and method chaining, as seen below.

public virtual IEnumerable<Logs> SearchLogs(int? userId, DateTime? beginDateIsAfter, DateTime? endDateIsBefore, bool? hasAttachments)
{
    var query = Db.LogEntry.Where(log => log.UserId.Equals(1));
    if (beginDateIsAfter.HasValue)
    {
        query = query.Where(x => x.BeginDate >= beginDateIsAfter);
    }
    if (endDateIsBefore.HasValue)
    {
        query = query.Where(x => x.EndDate <= endDateIsBefore);
    }
    if(hasAttachments.HasValue)
    {
        query = query.Where(x => x.HasAttachments == hasAttachments.Value);
    }
    return query.AsEnumerable();
}


You can chain on as many "Where" extensions as you please, as well as "OrderBy" extensions.  I have yet to encounter a sql query that could not be accomplished in Linq to Entities (granted, some require some mind-bending code).

My biggest concern regarding this usage of linq was the performance.  How many queries does this code execute and how efficient can that really be?  Fortunately, due to Linq's deferred execution, no sql is executed until the last possible minute.  So, in the case above, no sql is executed until the query is enumerated (the last line of the method), and only a single, parameterized query is issued.

As a result of utilizing linq and and its built in method-chaining capabilities, all of the if/then logic that would have been in a stored procedure fits nicely within the code.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

.NET | C# | LINQ

0

A simple, practical extension method

by Jeremy 5. November 2009 11:52

Extension methods were introduced to .NET in C# 3.0.  They provide an effective way to extend existing types and provide an intuitive way to add functionality to classes that you may not otherwise have the ability to modify.  One simple example for which I use an extension method is to display booleans in the UI.  Consider an online shop listing products, where you want to tell the user whether the item is "In Stock".  If you bind the boolean directly, the user will see "True" or "False" in the UI.  While this may get the point across to the user, it is far from user-friendly.  You should indicate "Yes" or "No", rather than true/false.  There are certainly several ways to accomplish this easily, but I find an extension method intuitive to code against and re-usable.  

To accomplish this:
1) Create a static class that will house your extension methods.
2) Add the method below to that class.
3) Reference the dll and namespace of your extension method class.
4) Write client code to use it, for example, product.IsInStock.ToYesNo().


public static string ToYesNo(this bool value)

{
    if (value) return "Yes";
    return "No";
}


This is a simple, practical usage of extension methods and how to utilize them.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: ,

C# | .NET

Powered by BlogEngine.NET 1.4.5.0
Original Design by Laptop Geek, Adapted by onesoft