Fri
Aug 3
2007

Global exception handling

Some general notes on exception handling:

  • Setup a global exception handler to catch and handle unexpected exceptions.
  • Only catch exceptions where you can take more intelligent action than the global exception handler.
  • Be careful with exceptions on any thread other than the main thread (spawned threads, asynchronous delegates, timers, etc…)
    • In .NET 1.1, the CLR eats any exceptions, killing the thread but allowing your app to continue.
    • In .NET 2.0, unhandled exceptions take down the entire appdomain (more info).

In ASP.NET
1. Add the following to global.asax:

void Application_Error(object sender, EventArgs e) 
{
    Exception ex = Server.GetLastError();
    if (ex is System.Web.HttpUnhandledException)
    {
       ex = ex.InnerException;
    }
    LogHelper.Log.Error("Unhandled exception", ex);
    Server.Transfer("~/Error.aspx");
}

2. Create an Error.aspx page:
Use Server.GetLastError() to retrieve the exception.
Ensure the exception is logged in global.asax in case the Server.Transfer() fails.
Do not display the exception to the user to prevent hackers from gleaning information.

3. If you are using Forms Authentication, add the following to your web.config. It ensures unauthenticated users can see the Error.aspx page in case an error occurs during logon/logoff. You should do the same for any images and stylesheets as well.

<configuration>
	<location path="Error.aspx">
		<system.web>
			<authorization>
				<allow users="?"/>
			</authorization>
		</system.web>
	</location>
</configuration>

4. If you are using AJAX, you have to add an event handler on every page (are there any better solutions?):

protected void ScriptManager1_AsyncPostBackError(object sender, AsyncPostBackErrorEventArgs e)
{
    LogHelper.Log.Error("Unhandled exception during asyncpostback", e.Exception);
    ScriptManager1.AsyncPostBackErrorMessage = 
        "An unexpected error occured. Please try again or contact the Help Desk.";
}

ASP.NET Web Services
The Global.Application_Error does not fire in a web service.

using System;
using System.Web.Services.Protocols;
using TDR.Common.Utility;
 
namespace MySolution.MyProject.SoapExtensions
{
    public class LoggingSoapExtension : SoapExtension
    {
        public override object GetInitializer(LogicalMethodInfo methodInfo, SoapExtensionAttribute attribute)
        {
            return null;
        }
 
        public override object GetInitializer(Type serviceType)
        {
            return null;
        }
 
        public override void Initialize(object initializer)
        {
        }
 
        public override void ProcessMessage(SoapMessage message)
        {
            if (message.Stage == SoapMessageStage.AfterSerialize)
            {
                if (message.Exception != null)
                {
                    LogManager.Log.Error(message.Exception.Message, message.Exception);
                }
            }
        }
    }
}

2. Add this to your web.config:

<system.web>
    <webServices>
        <soapExtensionTypes>
            <add type="MySolution.MyProject.SoapExtensions.LoggingSoapExtension,MySolution" priority="1" group="1" />
        </soapExtensionTypes>
    </webServices>
</system.web>

Note: SoapExtensions are not called when invoking the a webservice from the built-in test webpage.

WinForms, Console Apps and Services
1. Hook into the domain’s unhandled exception event:

static void Main()
{
    AppDomain.CurrentDomain.UnhandledException +=
        new UnhandledExceptionEventHandler(
            CurrentDomain_UnhandledException);
}
 
/// <summary>
/// Log unhandled exceptions that occur anywhere in the appdomain.
/// </summary>
static void CurrentDomain_UnhandledException(object sender, 
                                     UnhandledExceptionEventArgs e)
{
    try 
    {
 
        LogHelper.Log.Error("Unhandled exception.", 
                   e.ExceptionObject as Exception); 
    }
    catch { }
}
Fri
Aug 3
2007

MSBuild Automated Deploy Scripts for Web Applications

These are suggested steps for creating batch scripts that will deploy a solution to DEV, TEST and PROD. If this article looks like it is more complicated than it should be, I agree. I think batch scripts with an XML read/write utility or NAnt would be a better choice:

  • The syntax for batch files and NAnt are both easier to read/understand
  • NAnt allows custom tasks can be written in C# directly in the build file. MSBuild requires a separate assembly (and associated solution and project files).
  • The big advantage with MSBuild is it it built-in. However this advantage is eliminated as we need to use the MSBuildCommunityTasks DLL to read/write config files.

Here is the MyApp.build file:

<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
 <!--
       MY WEB APPLICATION DEPLOY SCRIPT
 
       To deploy this application use the batch files DeployToXXX.bat
 -->
 <Import Project="..\..\Utilities\MSBuildCommunityTasks\MSBuild.Community.Tasks.Targets"/>
 
 <PropertyGroup>
 
   <TempFolder>..\..\_tempfolder</TempFolder>
   <DevFolder>\\mydevserver\wwwroot\myapp</DevFolder>
   <TestFolder>\\mytestserver\wwwroot\myapp</TestFolder>
 
 </PropertyGroup>
 
 
 
 <Target Name="DeployToDev">
 
   <AspNetCompiler
       VirtualPath="MyApp"
       PhysicalPath="..\ "
       TargetPath="$(TempFolder)"
       Clean="true"
       Force="true"
       Debug="false"
       Updateable="false" />
 
   <XmlRead XmlFileName="$(TempFolder)\web.config"
            XPath="/configuration/appSettings/add[@key='DEV.Log4NetConnectionString']/@value">
     <Output TaskParameter="Value" PropertyName="Log4NetConnectionString"/>
   </XmlRead>
 
   <XmlUpdate XmlFileName="$(TempFolder)\web.config"
              XPath="/configuration/appSettings/add[@key='Environment']/@value"
              Value="DEV" />
 
   <XmlUpdate XmlFileName="$(TempFolder)\web.config"
              XPath="/configuration/log4net/appender[@type='log4net.Appender.ADONetAppender']/connectionString/@value"
              Value="$(Log4NetConnectionString)" />
 
   <XmlUpdate XmlFileName="$(TempFolder)\web.config"
              XPath="/configuration/system.web/compilation/@debug"
              Value="false" />
 
   <CreateItem
       Include="$(DevFolder)\**\*"
     <Output TaskParameter="Include" ItemName="FilesToCleanFromTarget" />
   </CreateItem>
 
   <Delete Files="@(FilesToCleanFromTarget)" />
 
   <CreateItem
     Include="$(TempFolder)\**\*"
     Exclude="$(TempFolder)\Deploy\*">
     <Output TaskParameter="Include" ItemName="FilesToDeploy"/>
   </CreateItem>
 
   <Copy SourceFiles="@(FilesToDeploy)"
         DestinationFiles="@(FilesToDeploy->'$(DevFolder)\%(RecursiveDir)%(Filename)%(Extension)')"
   />
 
   <RemoveDir Directories="$(TempFolder)" />
 
 </Target>
 
 
 
 <Target Name="DeployToTest">
 
   <CreateItem
       Include="$(DevFolder)\**\*"
       Exclude="$(DevFolder)\Deploy\*">
     <Output TaskParameter="Include" ItemName="FilesToDeploy"/>
   </CreateItem>
 
   <Copy SourceFiles="@(FilesToDeploy)"
         DestinationFiles="@(FilesToDeploy->'$(TestFolder)\%(RecursiveDir)%(Filename)%(Extension)')" />
 
   <XmlRead XmlFileName="$(TestFolder)\web.config"
            XPath="/configuration/appSettings/add[@key='TEST.Log4NetConnectionString']/@value">
     <Output TaskParameter="Value" PropertyName="Log4NetConnectionString"/>
   </XmlRead>
 
   <XmlUpdate XmlFileName="$(TestFolder)\web.config"
              XPath="/configuration/appSettings/add[@key='Environment']/@value"
              Value="TEST" />
 
   <XmlUpdate XmlFileName="$(TestFolder)\web.config"
              XPath="/configuration/log4net/appender[@type='log4net.Appender.ADONetAppender']/connectionString/@value"
              Value="$(Log4NetConnectionString)" />
 
   <XmlUpdate XmlFileName="$(TestFolder)\web.config"
              XPath="/configuration/system.web/compilation/@debug"
              Value="false" />
 
 </Target>
 
 
 
 <Target Name="DeployToProd">
 
   <Copy SourceFiles="$(TestFolder)\web.config"
         DestinationFiles="$(TestFolder)\Web.config.test" />
 
   <XmlRead XmlFileName="$(TestFolder)\web.config"
            XPath="/configuration/appSettings/add[@key='PROD.Log4NetConnectionString']/@value">
     <Output TaskParameter="Value" PropertyName="Log4NetConnectionString"/>
   </XmlRead>
 
   <XmlUpdate XmlFileName="$(TestFolder)\web.config"
              XPath="/configuration/appSettings/add[@key='Environment']/@value"
              Value="PROD" />
 
   <XmlUpdate XmlFileName="$(TestFolder)\web.config"
              XPath="/configuration/log4net/appender[@type='log4net.Appender.ADONetAppender']/connectionString/@value"
              Value="$(Log4NetConnectionString)" />
 
   <XmlUpdate XmlFileName="$(TestFolder)\web.config"
              XPath="/configuration/system.web/compilation/@debug"
              Value="false" />
 
   <Prompt Text="Please ask the production administrator to copy MyApp from test to production. Press Enter when complete."/>
 
   <Copy SourceFiles="$(TestFolder)\Web.config.test"
         DestinationFiles="$(TestFolder)\Web.config" />
   <Delete Files="$(TestFolder)\Web.config.test" />
 
 </Target>
 
</Project>

Then to run use the following batch script:

@echo off
echo.
echo --------------------------------------------------
echo.
echo   Deploy the Application to Dev
echo.
echo   Ensure you have retrieved the latest version
echo   from source control.
echo.
echo --------------------------------------------------
echo.
 
call "%VS80COMNTOOLS%\vsvars32.bat" 
 
set MSBuildCommunityTasksPath=..\..\Utilities\MSBuildCommunityTasks
 
msbuild deploy.build /target:DeployToDev
 
pause

This requires the MSBuildCommunityTasks DLLs. Download, install, copy the DLLs to your project directory under Utilities, checkin to VSS and then uninstall. Placing the DLLs in VSS ensures subsequent developers can use the project without hacking their way through a bunch of dependencies.

Fri
Aug 3
2007

Multi-Environment Config

The following class allows you to easily switch between DEV, TEST and PROD appConfig settings. Settings are stored in one location (your web.config or app.config file). You can define settings global to all environments and override settings for each environment as neccessary.

1. In your app, access your settings with:

MessageBox.Show("The current environment is " + Config.Name);
MessageBox.Show("The connection timeout is " + Config.ConnectionTimeout);

2. Setup your web.config or app.config as follows, with an Environment appSetting:

<?xml version="1.0"?>
<configuration>
 <appSettings>
 
   <!-- ENVIRONMENT
        Use the "Environment" key below to select the environment (DEV | TEST | PROD). 
 
        For settings common to all environments, add a normal appSetting key (e.g. "Name").
        To change a setting for a specific environment, add an appSetting key with
        the environment name (e.g. "DEV.Name"). An environment-specific setting
        will override a common setting.
 
        In the example below, the DEV environment will have a connection timeout of 
        2 minutes while the TEST and PROD environments will use 90 minutes.
   -->
 
   <add key="Environment" value="DEV"/>
 
   <add key="DEV.Name"  value="Development"/>
   <add key="TEST.Name" value="Test"/>
   <add key="PROD.Name" value="Production"/>
 
   <add key="ConnectionTimeout"     value="90"/>
   <add key="DEV.ConnectionTimeout" value="2"/>
 
 </appSettings>
</configuration>

3. Add the following Config.cs class to your project.

using System;
using System.Configuration;
using System.Collections.Generic;
using System.Text;
 
/// <summary>
/// A type-safe wapper around the project's config file. This class ensures 
/// all appSetting keys are located in one place and should provide more
/// readable code. This also allow settings to be easily moved to a database
/// or other store.
/// </summary>
public class Config
{
   /// <summary>
   /// Retrieve a value from the config file. The "environment" appsetting
   /// configures the environment (e.g. Fort Hills development, Edmonton test).
   /// Prefix appsetting with this environment value to specifiy an appsetting
   /// that is specific to the environment. 
   /// 
   /// Note: Do NOT make this method public as we want to provide a 
   /// type-safe wrapper and ensure all  constants (the appSetting keys) 
   /// are located in one place (this class).
   /// </summary>
   private static string GetValue(string key)
   {
       string env = ConfigurationManager.AppSettings["environment"];
       string fullKey = env + "." + key;
       string value = ConfigurationManager.AppSettings[fullKey];
 
       if (value == null || value == "")
           value = ConfigurationManager.AppSettings[key];
 
       if (value == null)
           value = "";
 
       return value;
   }
 
   /// <summary>
   /// Name of the environment
   /// </summary>
   public static string Name
   {
       get { return GetValue("Name").Trim(); }
   }
 
   /// <summary>
   /// Note we convert this to a TimeSpan so that users of this class
   /// don't need to know if the timeout is specified in seconds, 
   /// minutes or hours. When adding new settings convert them 
   /// to a data type that will be most useful to users of this class.
   /// </summary>
   public static TimeSpan ConnectionTimeout
   {
        get 
        { 
             return TimeSpan.FromMinutes(
                 Convert.ToDouble(GetValue("ConnectionTimeout"))); 
        }
   }
}

© 2009 Brian Low. All rights reserved.