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);
}

Be the first to rate this post

  • Currently 0/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

0

Using test frameworks for "To Do" lists

by Jeremy 21. October 2009 17:28
Many times during a development cycle, you find bugs and/or receive new feature requests that you need to keep track of.  Typically, this is added to a list of some sort, be it a bug tracking system or just a post-it note on your monitor.  While there is certainly value in having items like this documented and tracked in a formal (or informal) fashion, I find it helpful to create a stubbed test that reminds me of my outstanding coding tasks.  

As an example of adding a "to do" test, consider the following scenario.  I am currently working on a system which allows the logging of activities; attachments can be associated with those activites.  While manually testing this system that is currently under development, I noticed that upon saving one of these logs, the attachment was not being saved.  Rather than add this to a list of todo tasks for myself - I went ahead and created a test called "ShouldAddAnAttachmentToExistingLogUponUpdate" that simply throws a NotImplementedException (for now).  (Note: I am using mbUnit, but any unit testing framework will work with this concept).

As a result, when I go to run all tests for my solution, I will see this exception and remember that I need to fix this bug by making this test pass.  In my opinion, this is a helpful way to keep track of the items that you need to fix and/or implement, as well as a great way to get in the habit of using test driven development.  Creating tests as "To Do" items reminds you to code the test and, subsequently, code the logic to pass the test.

Be the first to rate this post

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

Tags: ,

TDD

1

TDD = CDD?

by Jeremy 21. August 2009 12:05
There's been a big industry focus on test driven development over the past few years.  Many advocates of TDD make it a point to say that TDD is not really about testing, it's about design.  Writing tests before application code forces you to think about the goal(s) of the application code.  For example, what should the input to a certain method be, and what output should it supply?  TDD forces you to think in terms of inputs/outputs and code interaction.  What input should be provided to the callee, what output should be provided to the caller - essentially, how will multiple objects (e.g. classes, methods, etc) interface.  

I've recently started practicing TDD a bit, and have found that instead of always writing unit tests with some type of testing framework (e.g. nUnit), I sometimes create a console application that calls certain methods and reveals the output.  Granted, these are perhaps more "integration" tests than unit tests, as I'm using them to view database contents.  None-the-less, it got me thinking about TDD, and the notion that "Test"-Driven development isn't really about tests.  In my opinion, a more appropriate name might be "Client"-Driven Development.  I'm not referring to the clients that pay your bills, but the client portions of your application (e.g. the UI which calls another application layer).  There are clients at every layer of your app - the UI calls one layer, that layer calls another layer.  Each caller is a client, and when writing tests first, we need to think in terms of the "client", what it should input, and what the result should be.

Isn't CDD essentially the goal of TDD?

Be the first to rate this post

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

Tags: , ,

Abstraction | Software Maintainability | TDD

1

Html tables...still?

by Jeremy 27. July 2009 10:29
Over the past several years, I've heard many arguments for the benefits of using CSS over Html tables for page layout.  Having been abstracted away into the land of server controls via my usage of ASP.NET, I had not taken much time to fully utilize css.  I've recently been involved in a project that benefited significantly from the usage of CSS over table layouts.  This is not to say that the same output could not have been accomplished using tables, but the ease of maintenance and elegance of css blows away the table competition (or lack thereof).  

The following are my recommendations in relation to CSS:

1) Take the time to learn it
Some web developers (my old self included) think of CSS as something that falls into the land of designers.  While designers may have a more natural interest in CSS, developers should be just as interested, if not more so than designers.  As a web developer, adding CSS to your toolbelt is one of the most effective uses of your self-training time.  As developers, we often get caught up in the latest feature of a language or some "cool" technology, that, in practicality, we seldom use.  If you learn CSS and use it correctly, you will use it on 100% of your web projects.

2) Layout your content logically before thinking about style
This separation of concerns is really the foundation of implementing CSS.  CSS is only intended to affect the look of your pages.  When you add your content and try to style it at the same time, you often end up with a lot of junk that you don't really need, creating more of a maintenance headache.  Laying out content first, using the correct logical tags (e.g. a menu is simply a bunch of list items with links <li><a>Item</a></li>) will save you time now and in the future.

3) "Cascade"
Object-oriented developers are already familiar with the concept of inheritance.  We know its effectiveness in programming, and that same effectiveness applies in CSS.  Want to style every item in a list?  Put the class (or id) on the list header tag (e.g. <ul>), not on every individual list item.  Learn how to use inheritance and how to override styles correctly, and your stylesheet will shrink and be easier to maintain.

Currently rated 3.0 by 1 people

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

Tags: ,

CSS

3

You accidentally deleted how many rows in the database?

by Jeremy 30. June 2009 12:21
Every developer that has worked with SQL for any length of time has most likely been there...  You are running an ad-hoc DML (data manipulation language) SQL statement against a database.  Depending on the security processes in place at your company/client, you may be executing this statement against a development database, staging database, or (gasp) a production database.  You've written an update statement and are thoroughly convinced it will update only the select few rows that you would like changed.  However, you execute the statement and see the message "30072 row(s) affected".  Depending on the environment you executed this in, you are either mildly frustrated (development environment) or your heart is in your throat (production environment).

So, how do you avoid this?  Test against data you don't care about?  Run a select statement that mimics the update or delete statement before you actually execute it?  These are both a step in the right direction, but another way to verify that your SQL will do what you intend is to utilize transactions.

Instead of:

UPDATE Product
SET Price = 10.99
WHERE ProductName LIKE 'Football%'


(Which will cause the price of your nerf footballs to be 10.99, however the Football stadium that you happen to have for sale will also be quite the bargain.)

Why not use:

BEGIN TRANSACTION

SELECT ProductName -- View the "Before" data
FROM Product
WHERE Price = 10.99
    AND ProductName LIKE 'Football%'

UPDATE Product
SET Price = 10.99
WHERE ProductName LIKE 'Football%'

SELECT ProductName -- View the "After" data
FROM Product
WHERE Price = 10.99
    AND ProductName LIKE 'Football%'
   
ROLLBACK TRANSACTION



Utilizing a transaction and then rolling it back allows you to see the number of rows affected and, if you choose, the "before" and "after" state of the database without actually committing the changes.

The concept is simple, but re-using it as a best practice will save you time, headaches, and perhaps even disaster.

Currently rated 4.0 by 1 people

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

Tags: ,

SQL

2

When is abstraction a bad thing?

by Jeremy 21. May 2009 08:50
Abstraction is a powerful concept in software development.  Abstracting away certain parts of an application can heavily reduce develop time and make for a maintainable solution.  One shining example of this is the multitude of Object-Relational Mappers on the market, which abstract away a large amount of details about database interaction.  However, as with most things in life, abstraction's highest value is realized when used in moderation.  

While picking up ASP.NET MVC, I've started to realize the significant abstraction that asp.net server controls provide.  ASP.NET MVC doesn't have the parallel (at this point) to the server controls of web forms.  There are html helpers, but those are a very minor abstraction in comparison.  

Whether using web forms or ASP.NET MVC, one could argue that there are always abstractions that don't pull their weight.  For example, it's not unheard of for developers to use label controls for every message they put on a page.  The label abstraction doesn't provide anything that an html span tag wouldn't.  As another example, html helpers in ASP.NET MVC don't always provide much bang for the buck.  In some cases, it's harder to learn the syntax of the html helper than to simply write the html itself.  Learning how to write the html always applies to web development, the helpers only apply to ASP.NET MVC.

Abstractions can make us lose sight of how something actually works.  I will certainly admit that asp.net server controls have prevented me from learning the inner workings of some html tags over the years.  At the same time, they have sped up my development in many cases.  Whether you use abstractions or not, you should first understand what each is doing under the covers.  This allows you to determine if it is adding value or just tacking on an extra maintenance burden.

Currently rated 2.0 by 1 people

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

Tags: , ,

Software Maintainability | Abstraction

2

jQuery is more than animation

by Jeremy 30. April 2009 16:51
jQuery is all the rage these days with website development.  It seems that a good amount of demos out there just show its flashiness and ability to provide animations.  However, there's a functional side of jQuery that should not be overlooked.  Here's a simple example that can be useful on every web page that collects user input.  

The usability of web forms (forms allowing data entry, not asp.net web forms) can be enhanced by putting the focus on the first input field in the form.  ASP.NET developers often perform this task using server-side code (e.g. txtFirstField.Focus() called in Page_Load).  Using jQuery, you can apply the following script to any web page that has input fields.  Apply this script once across your site and eliminate the need to put the focus on specific fields on each individual page.

$(document).ready(
    function() {
        $("input:text:first").focus();
    }
)

Currently rated 3.0 by 1 people

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

Tags:

jQuery

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