Wintellect  

I am currently enjoying real benefits from an ASP.Net 2.0 feature, called Web Resources, in a project that I am working on. So why not blog about it? However, unlike my usual dissertation-length blogs, this one is going to have to be more about how to get-in, use the feature, and get out.  

When looking-over the HTML generated by an ASP.Net 2.0 page, I discovered a number of mysterious links that looked something like this:
/web/WebResource.axd?d=02Izydq6n-lcgo63dmOZZ8UgQsQMwdKNaScqrnNZgT2bI5odv1Sqsezt8wKaveny-icvswUuLm3GsReVgjnulQ2&t=632618557271718856
I noticed that these were used for resources such as images used by the TreeView control, as well as resources like .js files containing client-side javascript.

So the questions that came to mind were, where do these resources live? And can I use the same publishing facility for resources of my own? A little quality time with reflector revealed the resources are assembly-embedded (or linked) manifest resources, and the publishing mechanism is the Web Resources mechanism.

This is very useful for DLL's that package custom ASP.Net controls, which require supporting (and static) resources of any kind.

Here is the model:

  • Embed a resource of any kind (HTML document, .js file, .gif or .jpg files, etc.) in your assembly. Visual Studio tack's-on the default namespace for the project, so if the file's name was "mouse.gif", then the manifest resource's name would be something like this "MyNamespace.mouse.gif".
  • Apply an assembly-level System.Web.UI.WebResource attribute, which declares the resource (by name) to be a web resource. This attribute serves the dual purposes of declaring the resources content-type (such as "image/gif"), as well as declaring to the system that it is safe (in security terms) to serve this resource to requesting clients. Here is what this attribute looks like in C# syntax:
    [assembly: System.Web.UI.WebResource(
       "MyNamespace.mouse.gif",
       "image/gif")]
  • Finally, you need a URL to publish to the client, which it can use to request this resource from your application. A call to the ClientScriptManager.GetWebResourceURL method accomplishes this. Here is what that code might look like in a custom control:
    Page.ClientScript.GetWebResourceUrl(typeof(MyType), "MyNamespace.mouse.gif");
    The first argument provides the system a way to find the assembly where the resource lives. (Unlike with other "manifest resource getting API's" the type's namespace *is not* added to the string provided.) The second argument should be the fully qualified manifest resource name.

That's the feature, in a nutshell.

I see this feature as having clear benefits over using an ASHX to publish static resources. One major benefit is the ability to encapsulate everything into an assembly full of custom controls. And so, from the consuming application's perspective, no additional configuration is required to publish arbitrary resources from the page.

After reverse-engineering this feature for my own needs, I thought to google the topic, and turned-up this article by Victor Garcia Aprea. Maybe I should have googled first!

Cheers!

A common .NET-related design question that I get is when to define events in your application code; (usually worded something like this, "when would I ever do this?") As a trend, I have noticed that developers tend to become familiar with consuming events defined by the class library after having used C# or VB.Net for just a short amount of time. However, making the leap from writing event-consumers to creating your own event-producers is a tougher challenge.

Events are meant to represent notifications in your code. But ultimately the code being notified is represented as a method, and the code raising the notification is calling that method. So how then do events differ from a typical method-call? Understanding this is key to understanding when to define your own events.

MethodB is a non-virtual method (more on virtuals in a bit) being called by MethodA:
MethodA --> MethodB – call direction and dependency direction are the same.

In the typical non-virtual method-call relationship, the dependency relationship is in the direction of the call. Said another way, at compile time, MethodA’s code depends on MethodB’s code, and must know important information about MethodB, such as what its signature is, what class or struct defines the method, whether the method is instance or static, and what assembly the code is packaged in.

With events, the dependency relationship is reversed:
Event-Raiser --> Event-Receiver – call direction
Event-Raiser <-- Event-Receiver – dependency direction

This reversal of dependency has the important impact of allowing calling code to be written without prior knowledge of (or a dependency on) the code being called. This is very useful for library code, which must pre-exist the application code that uses the library. Thus the substantial number of events defined in the .NET Framework class library.

But what of events raised from your application code? Well, this reversing of the dependency relationship can be useful for apps as well. An example that I saw today (which inspired this blog entry in the first place), was a user control in an ASP.Net application. Without going into gory details, the user control had taken dependencies on the pages which contained the control (not an easy thing to accomplish, since ASP.Net disallows cyclic relationships between auto-generated portions of the application). In essence, the control was saying "if I am embedded in page A, do this, if I am embedded in page B do that," and so on.

In defense of the code's author, the user control didn't start out this way, but over time it began to be used in more places, and yet at a certain point in the logic, it needed to pass control on to page-specific processing.

This is an example where the reversed dependency of an event is a more natural fit to the already established dependency between various pages and a user control. And so, by introducing an event in the user control, now each page was able to perform its own page-specific processing, in response to an event raised by the user-control. The pages registered for the event in each case, and now the control was responsible only for the notifying part of the code. The encapsulation improvements in this minor change, in this case, were far-reaching, because now the user control no longer needed to grovel around in the pages' controls collection to gather necessary state.

In both ASP.Net and Windows Forms user-controls are an area where applications can benefit from implementing their own events (properties are useful here too, incidentally).

Alright, so reversal of the dependency relationship in a method call is one reason for events. Events, though, are not the only object oriented-idiom with this attribute. Interface methods as well as class-defined virtual methods exhibit this reverse dependency. And so, the next question is how do events and virtual methods differ. Two noteworthy differences are somewhat related, which are differences in discovery and impact on your derivation lineage. Let's start with discovery.

Events have a built-in registration and un-registration mechanism. In fact, given that the actual call is implemented by the lower-level delegate, you could make the argument that events offer nothing but a registration and un-registration mechanism. This allows for dynamic addition and removal of a delegate in the callback list of some notifying code. The add and remove mechanism is really just a method-pair, but the method pair is well defined, which has a number of useful effects. One is that the definer of the event-raising code can all but completely ignore the registration details here, and just let the compiler do the work, if they want to. Another is that designers and intellisense can consistently automate the wiring of handlers to arbitrarily defined events. (This automatability extends to the COM interop infrastructure as well.) In contrast, if you are writing code that calls a virtual method, it is your job to decide how overriders of the virtual let you know of their existence. There are many ways of accomplishing this.

The second major difference is the impact on your derivation lineage. If the calling code is calling a virtual or interface method, then that forces your called code to derive from the defining base type. This has several side-effects. One is that a single type-definition cannot define two different handling methods for the same notification, a limitation that events don't share (because events are delegate based, and therefore enjoy method-level granularity). Another is that the type, in the case of a virtual in a class, no longer can decide what class to derive from. And a third is that, in the case of an interface, the class has to implement all of the methods in the interface.

I am not arguing against the use of interfaces or virtual methods, by any stretch. I do want to point out, though, how much more heavyweight your dependency relationship is, when the callback mechanism is a virtual method. (That being said, both Java and C++ do, without the benefit of events, similar things to what .NET code does, by using virtuals and interfaces.)

The lines between event/delegate use and virtual/interface use are not always clear-cut; there can be art to this design decision. As evidence to this, notice that List in the Whidbey class library has a Sort overload which takes an IComparer interface reference, and a Sort overload which takes a Comparer delegate reference. Here they provided both delegate and virtual-binding versions, though I think it is safe to say that the newer delegate-based version is likely to be the more convenient to use in many cases.

Alright, so the summary here is that events are another OO mechanism which can reverse, loosen, lessen, or sometimes entirely remove binding dependencies between code. A feature that can be very useful in achieving reusability and extensibility when exploited properly.

I will part on some Whidbey-isms. Whidbey makes event-defining less tedious, by introducing the generic EventHandler delegate type. The introduction of the EventHandler delegate not only reduces the number of delegate types you need, but also enables the following generic event-raiser helper method, which you can package into your classes which raise events:
void RaiseEventHelper<TArgs>(
   EventHandler<TArgs> del,
   TArgs args)
   where TArgs : EventArgs {
      if (del != null)
         del(this, args);
}

Using a method like this accomplishes the two important tasks of checking the event for null before calling, and making a local-variable-copy  (in this case argument-copy) of the delegate before testing and calling.

Alright, I had better get back to work. Cheers!

I am teaching a .NET class this week, and the attendees are a technical and enthusiastic bunch which makes things fun for me (thanks SIG!!) Today we got into a discussion about the anonymous methods feature of C# 2.0. Due to their interest, and mine, I got an opportunity to write more involved demo code on the topic then I usually do. Following is a cleaned-up/commented version of the code.

Summary:

  • Uses anonymous methods to implement the command pattern, a-la GoF.
  • Implements an Undo/Redo stack class.
  • Uses anonymous methods to keep undo and redo commands together in a single method declaration.
  • Uses anonymous methods to generate the state objects necessary to maintain specific undo and redo command information.
  • Don't forget, you need a Whidbey build of the runtime or VS.Net 2005 to try this code.

 

using System;

using System.Collections.Generic;

using System.Drawing;

using System.Windows.Forms;

 

class App {

   public static void Main() {

      Application.Run(new MyForm());

   }

}

 

class MyForm : Form {

 

   // Fields for my controls

   ListBox list = new ListBox();

   TextBox textbox = new TextBox();

   Button buttonUndo;

   Button buttonRedo;

 

   UndoRedoStack urs;

 

   public MyForm() {

      Text = "Anon Sample";

      urs =  new UndoRedoStack(UndoRedoEnabled);

 

      // Create my list and textbox controls

      list.Location = new Point(150, 10);

      list.Parent = this;

      list.Sorted = true;

 

      textbox.Location = new Point(10, 10);

      textbox.Parent = this;     

 

      // Create my buttons which perform the

      // initial commands operation

      Button b = new Button();

      b.Text = "Add Item";

      b.Location = new Point(10, 40);

      b.Click += delegate { AddItem(); };

      b.Parent = this;

 

      b = new Button();

      b.Text = "Rename Item";

      b.Location = new Point(10, 70);

      b.Click += delegate { RenameItem(); };

      b.Parent = this;

 

      // Create my button which performs an undo

      buttonUndo = new Button();

      buttonUndo.Location = new Point(10, 110);

      buttonUndo.Text = "Undo";

      buttonUndo.Click +=

         delegate { urs.Undo(); };

      buttonUndo.Parent = this;

 

      // Create my button which performs a redo

      buttonRedo = new Button();

      buttonRedo.Location = new Point(10, 140);

      buttonRedo.Text = "Redo";

      buttonRedo.Click +=

         delegate { urs.Redo(); };

      buttonRedo.Parent = this;

 

      UndoRedoEnabled();

   }

 

   // Add an item to a sorted list box

   // (one of two commands)

   void AddItem() {

     

      Int32 item = 0;    

      String text = textbox.Text;

      textbox.Text = String.Empty;

 

      CommandCallback cbUndo, cbRedo;

     

      // Setup the cmd object to

      // contain our operations

      cbRedo = delegate {

         item = list.Items.Add(text);

      };

 

      cbUndo = delegate {

            list.Items.RemoveAt(item);

         };

 

      urs.PerformOperation(cbRedo, cbUndo);

   }

 

   // Rename an item in a sorted list box

   // (two of two commands)

   void RenameItem() {

      Int32 item = list.SelectedIndex;

 

      if (item > -1) {

         String oldText =

            list.SelectedItem.ToString();        

         String newText = textbox.Text;

         textbox.Text = String.Empty;

 

         CommandCallback cbUndo, cbRedo;

     

         Int32 newItem = 0;

         // Setup the cmd object to

         // contain our operations

         cbRedo = delegate {

               list.Items.RemoveAt(item);

               newItem =

                  list.Items.Add(newText);              

            }; 

 

         cbUndo = delegate {

               list.Items.RemoveAt(newItem);

               list.Items.Add(oldText);

            };

 

         // perform the initial operation   

         urs.PerformOperation(cbRedo, cbUndo);

         list.SelectedIndex = newItem;

      }

   }

 

   void UndoRedoEnabled() {

      buttonUndo.Enabled = urs.CanUndo;

      buttonRedo.Enabled = urs.CanRedo;

   }

}

 

 

// Supporting delegate for the UndoRedoStack

public delegate void CommandCallback();

 

 

public class UndoRedoStack {

 

   // Command object which holds a matching

   // do and undo operation

   class Command {

      internal CommandCallback redo;

      internal CommandCallback undo;

   }

 

   // undo and redo stacks of Command objects

   Stack<Command> undoStack =

      new Stack<Command>();

   Stack<Command> redoStack =

      new Stack<Command>();

 

   CommandCallback undoStatus;

 

   public UndoRedoStack() : this(null) {}

   public UndoRedoStack( // optional callback

      CommandCallback statusUpdateCallback) {

      undoStatus = statusUpdateCallback;

   }

 

   public void PerformOperation(

      CommandCallback operation,

      CommandCallback undoOperation) {

      // Setup the cmd object to

      // contain our operations

      Command cmd = new Command();

      cmd.redo = operation;

      cmd.undo = undoOperation;

 

      // do the operation the first time

      cmd.redo();

 

      // push the undo on the stack

      undoStack.Push(cmd);

 

      // clear our redo "history"

      redoStack.Clear();

 

      if (undoStatus != null) undoStatus();

   }

 

   // Perform an undo operation

   public void Undo() {

      Command cmd = undoStack.Pop();

      cmd.undo();

      redoStack.Push(cmd);

      if (undoStatus != null) undoStatus();

   }

 

   // Perform a redo operation

   public void Redo() {

      Command cmd = redoStack.Pop();

      cmd.redo();

      undoStack.Push(cmd);

      if (undoStatus != null) undoStatus();

   }

 

   public Boolean CanUndo {

      get { return (undoStack.Count > 0); }

   }

 

   public Boolean CanRedo {

      get { return (redoStack.Count > 0); }

   }

}

Executable entry point methods in managed code (e.g. Main in C# or VB.Net) should be very simple. As an example, this Main is too complex and should be simplified.

class MyApp {

   public static void Main() {

      Application.Run(new MyForm()); // MyForm is a form-

                                     // derived type

   }

}

Furthermore in managed code an entry-point method should never diverge (very far) from the following code.

public static Int32 Main(String[] args) {

   try {

      return MainImpl(String[] args); // defined in same

                                      // type as Main

   } catch (Exception e) {

      HandleTheUnhandled(Object e);   // ditto

   } catch {

      HandleTheUnhandled(null);

   }

}

I will get to the anatomy of a stable entry method in a moment.

Until then let’s look closer at the problem. Here are the precepts which lead me to conclude that that first Main is too complicated:

  1. Applications should not be designed to crash.
  2. By design, if the CLR cannot Just-In-Time (JIT) compile Main, the results are an application crash (or at least that is what it will look like to the end-user).
  3. Methods that cause a type to load are less likely to JIT then methods that don’t.

Starting with number one, in an ideal world, applications should not crash. Taking this principle a step further, even if your application does encounter some failure that will prevent it from executing normally, it should still present the user with a notification of the problem, rather then “just crashing”.

So why the CLR’s designed crash in number two? In a JIT compiled environment, if a method doesn’t JIT it can’t be executed at all. There is no concept of partial execution here. So the CLR has no choice but to fail the execution of an application entirely if, for some reason, Main fails JIT compilation.

Alright, so that brings us to number three, which is really the crux of the problem. When managed code starts up it is inherently unstable. Methods get JIT compiled which causes types to be loaded. Types are loaded which cause assemblies to load. Assemblies are loaded, which involves file system operations, at minimum, and network operations in some deployments. You might imagine your application JIT compiling entirely, before Main is ever called; but that is not how it works. Instead, your methods are JIT compiled as they are called, and types and assemblies that your code references are loaded as your code executes.

Eventually the chaos settles down, and your application executes in a steady state. The trick is avoiding chaos in Main.

Let me reprint the too-complicated Main.

class MyApp {

   public static void Main() {

      Application.Run(new MyForm()); // MyForm is a form-

                                     // derived type

   }

}

This code is going to cause the System.Windows.Forms.Application type to load, as well as the application defined type MyForm. In the process of JITting a method, the types referenced by the method are loaded (if they have not already been, that is). Since Main is the first method to execute, we are fairly certain that any types that it references must be loaded.

If either type fails to load, then Main will most likely fail to JIT compile. Here are some situations that can cause a method to fail JIT compilation:

  1. The method fails verification or contains invalid Intermediate Language.
  2. Any type that the method references fails to load.
  3. The type containing the method itself fails to load or fails to initialize.
  4. The method cannot bind to a referenced type or method for security reasons.
  5. The CLR itself has failed or there is not sufficient memory for the native instructions.

Let’s immediately write-off reasons 1 and 5 as edge-cases. If you manage to get your compiler to produce an invalid Main method, you will notice before you ship your product. And number five represents genuine system instability that is beyond the scope of an application to manage.

Reasons 2 and 3 are almost the same problem. In both cases a type-load did not result in a usable type. In one case the type was referenced explicitly by the method being JIT compiled. In the other case the type in question is the type that contains the method being JIT compiled. Failed type-loads can be caused by both unusual and usual situations. Again, don’t burden your application logic with handling bona-fide edge cases. These are things like missing system assemblies, bizarre binding and security policy configurations, CLR errors and such ignorables.

However, an application that late-binds to assemblies or is installed in a network deployment, should remain stable even if an application assembly goes missing or fails to load for some reason. Similarly, default security policy enforces a number of scenarios where a type may fail to load for security reasons. Finally, any type with a static constructor (type initializer) is surprisingly susceptible to initialization failure which for the type containing Main is just as bad as type-load failure.

Here is a fun example:

using System;

using System.Windows.Forms;

 

class MainForm : Form {

 

   static Int32 num =

      Math.Abs(Int32.MinValue); // evil code!

 

   protected override void WndProc(ref Message msg) {

      base.WndProc(ref msg);

   }

 

   public static void Main() {

      try {

         Application.Run(new MainForm());

      }

      catch { // catch *any* exception

         Console.WriteLine(

            "Alert user of unexpected failure");

      }

   }

}

If you compile this code as a console application, and run it, here is what you see on the console:

Unhandled Exception: System.TypeInitializationException: The type initializer for "MainForm" threw an exception. ---> System.OverflowException: Negating the minimum value of a twos complement number is invalid.

   at System.Math.AbsHelper(Int32 value)

   at System.Math.Abs(Int32 value)

   at MainForm..cctor()

   --- End of inner exception stack trace ---

   at MainForm.Main()

The important detail, though, is that the phrase “Alert user of unexpected failure” is not part of the console output. The reason is that the exception occurred before Main could be JIT compiled, and Main’s exception handler is useless here.

A more subtle (and bothersome) case appears if you comment out the line of code commented as “evil code”, and then rebuild as a console application. Now if you run it, everything seems fine. Unless, that is, you copy the .exe to a share on your network, and run it from there. Then you get this on the command line:

Unhandled Exception: System.Security.SecurityException: Request for the permission of type System.Security.Permissions.SecurityPermission, mscorlib, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 failed.

The state of the failed permission was:

<IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"

             version="1"

             Flags="UnmanagedCode"/>

Again, an exception has occurred in the process of loading the type that contains Main, and so the exception handler in Main is useless. Incidentally the reason for the security exception in the first place is that our type overrode the WndProc virtual method. Yes, sometimes just overriding a method represents a security breach (if your app is run partially trusted from a network share), that can cause a type to fail load. In this case we would like to present UI to the user letting them know that their deployment is causing the app to fail for security reasons. But we never get the chance to alert the user, because Main is too complex to even JIT.

A Stable Entry Method

Fortunately it doesn’t take too much effort to make your entry method stable. Here are some guidelines:

  1. Avoid type-loads of any kind in Main. Main should only call methods implemented in the same type definition.
  2. Do not implement a static constructor in the type that contains Main. (Avoiding static fields entirely is the safest way to go).
  3. Derive the type that contains Main from Object. This means that you need to hoist Main out of the type definition for your main form if you use Visual Studio .Net wizards to create your project.
  4. Keep the type that contains Main focused on getting your application started. Don’t think of it as the “Application” type that holds your application-level state.

The following code is a template for an entry point that follows these rules. Forty-two lines of code may seem like quite a few, just to get things up and running. Think of it as boilerplate logic that increases the stability and determinism of the first moments of application execution.

using System;

using System.Security;

 

public class AppEntry {

   public static Int32 Main(String[] args) {

 

      // Do we need to roll our own unhandled behavior

      // or was a handler successfully installed

      Boolean unhandledInstalled = false;

 

      try {

 

         // Run Main's usual logic and

         // install unhandled handler

         return MainImpl(args, out unhandledInstalled);

 

      } catch (SecurityException) {

         // Let user know that application

         // is shutting down due to

         // security restrictions

      } catch (Exception e) {

         if (unhandledInstalled)

            throw;

         HandleUnhandled(null,

            new UnhandledExceptionEventArgs(e, true));

      } catch {

         if (unhandledInstalled)

            throw;

         HandleUnhandled(null,

            new UnhandledExceptionEventArgs(null, true));

      }

      return -1;

   }

 

   static Int32 MainImpl(

      String[] args, out Boolean handlerInstalled) {

 

      // Try to install an unhandled exception handler

      // In v1.0/v1.1 failure to do this probably should

      // be reason to terminate the application

      // In v2.0 default unhandled behavior

      // substantially improved

      AppDomain.CurrentDomain.UnhandledException +=

         new UnhandledExceptionEventHandler(

         HandleUnhandled);

      handlerInstalled = true;

 

      // Perform main's "usual" 

      // application start-up logic

 

      return 0;

   }

 

   static void HandleUnhandled(Object sender,

      UnhandledExceptionEventArgs args) {

      // log exception object

      // let user know of unexpected failure

      Environment.Exit(-1);

   }

}

I wish that this blog entry was about “Monad”.

 

“Monad” is a new command shell that Microsoft is working on. The shell is built with managed code and is more featured, by far, then CMD.exe. One feature of Monad that I look forward to is the ability to extend the shell with my own managed code extensions called cmdlets.

 

But as I said, this blog entry isn’t about Monad. Nope, here I am going to show you a .bat file that you might find useful. I wrote this .bat file (with more then a little help from my friend Geary “I’m batman” Eppley), during a project where I needed a fair amount of cmd scripts, and I was becoming frustrated by the limitations of the batch language. (Batch, amazingly, hasn’t improved much since DOS.) I wanted to use C# as my script language.

 

On a system with the .NET Framework installed, with a few syntax shenanigans, you can embed arbitrary C# code into a batch file. Then you can write the logic of your script as C#. At the end of this entry is a batch file that creates such C# bat files (using the same technique as its implementation).

 

What the batch file is doing is creating a temporary file from the subset of the file that contains C# syntax. Then it is searching for the latest version of the .NET Framework on the system, and it is compiling the C# into an executable using the compiler. After that it is running the executable, passing on the bat arguments to the newly created exe. Then the exe returns, as does the .bat. Finally the .bat cleans-up after itself. This is no Monad, but it is a way to use C# for scripting.

 

Alight, here is a template .bat file for creating C# based .bat scripts.

 

@echo off & goto :beginScript

#endif

#line 4

 

/******** Put compilable C# code after this line ********/

 

using System;

using System.IO;

 

class App {

   public static void Main(String[] args) {

      Console.WriteLine("Put whatever logic here you want!");

   }

}

 

/*******************************************************/

#if NO

:beginScript

setlocal

set versions=

:: Uncomment the following line (remove REM) to limit the fx versions. Uses newest by default.

rem SET versions=v1.0.3705 v1.1.4322

set tempCs=%~s0

set tempCs=%tempCs:\=.%

set tempCs=%tempCs::=.%

set tempCs=%TEMP%\%tempCs%

if not exist %tempCs%.exe goto :build

::check for up-to-date .exe

copy %~s0 %tempCs%.tst 1>nul 2>&1

for /F %%i in ('dir /od /b %tempCs%.*') do set latestCs=%%~xi

del %tempCs%.tst 1>nul 2>&1

if "%latestCs%"==".exe" goto :run

:build

if defined versions FOR %%c IN (%versions%) DO IF EXIST %SystemRoot%\Microsoft.Net\Framework\%%c\csc.exe (SET netpath=%SystemRoot%\Microsoft.Net\Framework\%%c)

if not defined versions for /F %%c in ('dir /b /on %SystemRoot%\Microsoft.Net\Framework\v?.*') do if exist %SystemRoot%\Microsoft.Net\Framework\%%c\csc.exe (SET netpath=%SystemRoot%\Microsoft.Net\Framework\%%c)

if not exist %netpath%\csc.exe GOTO noFramework

echo #line 1 "%0" >%tempCs%.cs

echo #if NO >>%tempCs%.cs

TYPE %~s0 >>%tempCs%.cs

%netpath%\csc.exe /out:"%tempCs%.exe" %tempCs%.cs >nul

if ERRORLEVEL 1 goto badCompile

if exist %tempCs%.cs DEL /q %tempCs%.cs

:run

%tempCs%.exe %*

goto :EOF

:badCompile

%netpath%\csc.exe /out:"%tempCs%.exe" %tempCs%.cs

IF EXIST %tempCs%.cs DEL /q %tempCs%.cs

goto :EOF

:noFramework

ECHO ERROR: This batch file requires the .Net framework.

goto :EOF

#endif

I started this blog entry planning to explain exactly what happens when an exception is thrown from, or otherwise escapes a finally block in your code. I planned to explain in painful detail exactly what the runtime does in all of the various cases, with the goal of concluding (with substantial proof, I might add) that a finally block that throws is pure evil.

 

I couldn't do it in the half-hour that I had budgeted for this blog entry. It wasn't possible. So I have decided to refactor this blog entry into a little bit of philosophy, a statement of an unfortunate fact, and an example or two that should prove the case just fine without every convoluted detail. Oh yes, and I will wrap up with some guidance.

 

Promised Philosophy -

I believe that exception handling is an excellent way of reporting method failure in Object Oriented code. For this reason, I agree with the overall design of the .NET Framework in standardizing on exceptions as its primary means of expressing method failure. However, to wholeheartedly embrace exceptions for logical failure handling, it must be safe to throw from within any part of your application. Likewise, the behavior when you throw must be well defined and easy to understand in all circumstances.

 

An Unfortunate Fact -

The CLR's behavior when an exception is thrown from within a finally clause is neither safe nor easy to understand in all circumstances. Technically it is well-defined.

 

So what's all the hullabaloo about? The problem is that throwing from a finally block means that more than one exception can become active at the same time. No, this doesn't crash the CLR, but it is exceedingly difficult to button-down-the-hatches and avoid chaos in your application when this happens. Allow me to share some examples with you.

 

Some examples -

using System;

 

class App {

public static void Main() {

   AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(OnExcept);

 

   try {

      FinallyMadness(5);

   } catch (InvalidOperationException) { // One catch fits all!

      Console.WriteLine("catch");

   }

}

 

static void FinallyMadness(Int32 end) {

   try {

      Console.WriteLine("throw");

      throw new InvalidOperationException(); 

   } finally {        

      if (--end != 0) {

         FinallyMadness(end);

      }

   }

}  

 

static void OnExcept(Object sender, UnhandledExceptionEventArgs args) {

   Console.Write("unhandled");

}

}

 

No, I won't make you compile and run the application. I will tell you what the output of this application is (on versions 1.0, 1.1, and 2.0 of the CLR). Here goes:

throw

throw

throw

throw

throw

catch

 

That's right, five exceptions are thrown, and only one catch handler is required to catch them all. Is that catch handler called five times? No. Is the unhandled exception handler activated? No. Why is this? The reason is that each time a throw occurs, the one catch is sufficient to avoid triggering the unhandled exception handler, and then when the finally executes, the next throw replaces the previously active exception. That's it. One active exception replaces another, and in the end we catch the lucky exception that made it to the top. Never mind the other four exceptions. We didn't really mean to throw them anyway, right?

 

OK, but these exceptions are of the same type, what happens with exceptions of different types? If they had been different types surely one of them would trip our unhandled exception handler right? Right, unless you are unlucky and there are other catch handlers in the callstack that just happen to match each thrown exception type. Catch this:

 

using System;

 

class App {

public static void Main() {

   AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(OnExcept);

   try {

      ThreeThrow();

   } catch (NullReferenceException) {

      Console.WriteLine("catch");

   } catch (ArgumentException) {

      Console.WriteLine("catch");

   } catch (InvalidOperationException) {

      Console.WriteLine("catch");

   }

}

 

static void ThreeThrow() {

   try {

      Console.WriteLine("throw");

      throw new NullReferenceException();

   } finally {

      try {

         Console.WriteLine("throw");

         throw new ArgumentException();

      } finally {

         Console.WriteLine("throw");

         throw new InvalidOperationException();

      }

   }

}

 

static void OnExcept(Object sender, UnhandledExceptionEventArgs args) {

   Console.Write("unhandled");

}

}

 

OK, what's the output of this application? You guessed it:

throw

throw

throw

catch

 

That's right, one catch handles three exceptions of different types. Yes, the other catch clauses are necessary to make this possible, and yet their code never executes. "Jason, did you say that this behavior is well-defined?" Yes I did, and believe it or not, it is. It is just unrealistic to remember and design around in any realistic fashion.

 

Guidance -

#1. Consider a finally block that throws on purpose to be a bug in your code, and change it.

#2. Do whatever you can to stick to the basics in your finally blocks and perform whatever state-testing you can to avoid exceptions being raised by the methods you call in finally blocks.

#2. Don't catch and swallow exceptions in your finally blocks to solve this problem! This is no better (read worse!) than the default behavior of the runtime.

#3. If you are up for high-maintenance coding, consider wrapping the logic in all of your finallys in a catch-all exception block, that exits your application on the spot in the case of an exception (after logging the facts, of course).

#4. Always register for an unhandled exception handler in your applications that logs the facts, and when you are in your development phase, test with your debugger set to break on throw rather then breaking on unhanded exceptions. Take advantage of the selective exception settings of your debugger to make this practical.