Oct
27
2006
I recently wanted to have a method I could call to get a type-safe AppSetting, with an optional default value if the AppSetting wasn’t set. In C# 2.0, I came up with this:
public static T GetSetting<T>(string name, T defaultValue)
{
string input = ConfigurationManager.AppSettings[name];
if (input != null)
{
return (T)Convert.ChangeType(input, typeof(T));
}
else
{
return defaultValue;
}
}
Related posts
Oct
01
2006
Mark came up with an idea to use Enums to drive lookups. I told him I could go one better by providing user-friendly names instead of programmer-friendly enum value names. The idea is to loop through the literal fields of the enum type and check for a DescriptionAttribute on each field. Anyway, here’s the source, with caching for top performance.
Related posts
Apr
08
2006
A few new features added to the open source url rewriter, including:
- Logging support (you can add adapters for log4net, etc)
- The rewriter now adds the original and final querystring as Items in the HttpContext. To access, you would use:
RewriterHttpModule.OriginalQueryString
RewriterHttpModule.QueryString
- FIXED: Added checking for too many restarts
- FIXED: Case sensitivity in pattern matching
Download UrlRewriter.NET 1.6 here.
Related posts
Mar
11
2006
The TestDriven.NET tool is fantastic. I love the agility it gives you, as you can quickly build your unit tests, write your code and at a right-click, you can run your unit tests from Visual Studio.
One of the problems it currently has (I notice somebody has asked for this in their wishlist) is custom configuration. If the code you’re testing requires settings that would normally be in your web.config or App.config file, you have to ensure these settings are in a file called <your-assembly-name>.dll.config in your bin\Debug directory. A bit inconvenient. NUnit allows you to have a .config file in the root of your project with the same name as your project (e.g., Foo.Bar.config), so why should you do without this feature in Visual Studio?
Well, until the author adds this enhancement (hopefully soon), one workaround I’ve come across for this is to create a Post-Build event in Visual Studio.NET, which copies the config file from the root of your project to the required place in your bin directory.
To set this up, right-click Properties on your Project in Visual Studio.NET. Under Common Properties, click on Build Events. In the Post-build Event Command Line property, add the following: copy $(ProjectDir)$(ProjectName).config $(TargetPath).config
Then, whenever you have a successful build, your latest config changes will be available to TestDriven.NET’s in-built TestRunner.
Related posts
Nov
30
2005
An article on MSDN published a quick roundup of ten tips for achieving high-performance in your ASP.NET web application:
- Return multiple resultsets from your data access layer
- Use paged data access to only return the data you need
- Use Connection Pooling
- Use the ASP.NET Cache API to cache frequently used, rarely changing information
- Cache frequently used request-specific information for the duration of the request
- Process as much in the background (offline, out of the request) as possible
- Use Page Output Caching and Proxy Servers (mmmm…depends)
- Run IIS 6.0
- Use Gzip Compression
- Reduce Server Control View State
This is a great list. We’re running 9/10 on this (we don’t cache page output because everything is dynamic), and the web servers are pretty much idling most of the time.
Related posts
Nov
18
2005
Quite often when developers are developing ASP.NET applications and they’ve added exception handling, they will have some code like the following:
try
{
...
Response.Redirect("/default.aspx", true);
}
catch (Exception exc)
{
... // proper exception handling.
}
Funny thing is, many developers don’t realise it, but Response.Redirect throws a ThreadAbortException, which gets caught by the catch filter.
What’s the right way to handle this? I can outline three ways, each of which may be applicable in a given scenario:
- Simple. Move the Response.Redirect outside the try/catch statement. Problem solved. The catch filter will not receive the exception.
- Follow some exception handling best practices and only catch the exception type you really know how to handle:
try
{
...
Response.Redirect("/default.aspx", true);
}
catch (ArgumentOutOfRangeException exc)
{
... // proper exception handling.
}
- Catch the ThreadAbortException and rethrow it:
try
{
...
Response.Redirect("/default.aspx", true);
}
catch (ThreadAbortException)
{
throw;
}
catch (Exception exc)
{
… // proper exception handling.
}
Hope that’s answered “why am I getting a ThreadAbortException?” and given you some ideas of how to work around it.
ASP.NET, web development, exception management
Related posts
Nov
18
2005
I really love code reviews where I tell developers that they need to better plan for and handle exceptions, and in the followup code review, they present the following:
try
{
// do some dangerous stuff that may throw an exception.
}
catch (Exception e)
{
throw (e);
}
My usual reaction is to grit my teeth, administer an icy stare and ask a calm, measured question: “And what exactly, are you aiming to accomplish here? (besides, of course, losing your stack trace and the real source of the exception)”.
The problems I have with this “pattern” are many:
- You lose your stack trace when you call
throw(e);. The stack trace now points directly to this line, so you no longer know the real culprit.
- There’s no real “handling” going on here, now is there? What’s the code saying when you read it? “Hey! I can handle ‘Exception’. Oops, no I can’t, gonna have to throw this one on up the chain.”.
- Almost always, too generic of an exception is being caught. Come on, tell me that you know how to handle an OutOfMemoryException (or any other exception that derives from the Exception class…that’s almost* every exception) in this case. Really?
When I’ve finished with the code review, the above code is usually refactored into one of two forms:
// do some dangerous stuff that may throw an exception.
This is most often my favourite refactoring. It accomplishes the same effect as the above code…passing the buck.
try
{
// do some dangerous stuff that may throw an exception.
}
catch (InvalidOperationException e)
{
throw MyFacadeException("There was a problem doing the dangerous thing.", e);
}
This is the form of the refactor I prefer if there is truly a need to handle the exception and do something with it (in this case throwing a new exception, wrapping the thrown exception).
There are plenty of exception management best practices, but I typically use the following simple rules:
- Avoid an exception if you can (e.g., check for a zero denominator instead of just dividing by zero; check if a file exists rather than just trying to open it).
- If you can’t avoid an exception, catch the most specific exception you can (e.g., catch (ArgumentOutOfRangeException) instead of catch (Exception)…) and never, ever catch without a filter.
- Only catch the exception if you know what to do with it. If you don’t know what to do with an exception, don’t catch it.
- If you’re going to rethrow an exception, do it properly so the stack trace is maintained:
throw; instead of throw(e);.
- Valid things to do in a catch are:
- Do nothing. Swallow the exception if you expect it to happen, and rely on the fact that things weren’t done in the try clause to signal the exceptional case.
- Set some flags, or reset some local variables. Let these be the signal to the exceptional case.
- Throw a new exception, wrapping it around the thrown exception and providing either a facade exception type or providing better exception information (e.g., the message may be more specific about what was intended rather than the actual nuts-and-bolts error as in “Could not create the lock file required for exclusive write access” would be better than “Access denied”).
- Rethrow the thrown exception (using
throw;, not throw (e);). This is useful if you need to handle some more generic exceptions, but you want to bubble some more specific exceptions.
- Log a message and return (if you must). Least preferred, as it may be hiding some exceptions from you.
* Some obscure runtime exceptions actually don’t inherit from Exception, and these get caught in the following code:
try
{
...
}
catch
{
...
}
exceptions, code reviews, quality, wtf
Related posts