Monthly Archives: February 2007

SQL Server Open World

I’ll attend the Miracle SQL Server Open World conference from March 8-10, 2007 where I will speak about Windows Communication Foundation (WCF) and .Net Garbage Collection on the business intelligence & .Net development track.

Smart guys like Mark Souza, Lubor Kollar, Poul Randall from Microsoft and Kimberly Tripp will be there – will you?

Favor structured exception handling

I was surprised this last week, when a discussion about error handling, whether or not to use structured exceptions in .Net, surfaced at a customer where I am helping them to complete a project. I will not name the company, but it is a Danish division of a large American IT corporation with around 80.000 employees.

The discussion was between one of their architects, a couple of others and me. The company where accustomed to used return codes and the architect argued in favor of return codes. I didn’t think in this day and age that organizations still use return codes with languages that have build-in support for structured exception handling.

An exception is an event that occurs during the execution of a program, designed to handle the occurrence of some exceptional condition which changes the normal flow of execution. Exceptions travel out of band and propagate through the call stack until an exception handler catches the exception. Structured exceptions use the Try…Catch…Finally syntax.
Below is a make believe example of a simple system calling two methods:

static void Main(string[] args)
  Order myOrder = new Order();
  decimal yield;

    yield = CalculateYield(myOrder);
  catch (Exception ex)
  //** Exception handling **//

public static decimal CalculateYield(Order order)
  // calculate yield
  return decimal.MaxValue;
public static void UpdateStatus(Order order)
  // update status

If an exception is thrown in the method CalculateYield the flow is short-circuited and the method UpdateStatus is never called. With return codes the developer has to manually check if the method failed and manually propagate the return code up the stack.

Return codes imposes on method signature by requiring the return type to be a return code and potentially use a parameter as return type. This clutters the method signature and does not make the method functionality apparent. Notice the confusing method signature of CalculateYield in the following code:

static void Main(string[] args)
  Order myOrder = new Order();
  decimal yield = 0;
  int returnCode = 0;

  returnCode = CalculateYield(myOrder, yield);

  if (returnCode < = 0)
    returnCode = UpdateStatus(myOrder);
    //** Error handling **//

  if (returnCode > 0)
    //** Error handling **//

public static int CalculateYield(Order order, decimal yield)
  // calculate yield
  return -1; // return code

public static int UpdateStatus(Order order)
  // update status
  return 0; // return code

Return codes are inferior to exceptions. Exceptions are instances of a class and can therefore carry detailed information – not like integer return codes! It is non-reputable that return codes are no good.

The return code advocate might bring up an issue like performance due to the fact that throwing an exception results in a stack walk to create the stack trace.

When to throw exceptions?

Do not throw exceptions in the normal flow of execution. If it is expected that an action might fail like a login, use the Tester-Doer Pattern (e.g. Collection.Contains) or Try-Parse Pattern (e.g. Double.TryParse).

When to catch exceptions?

Catch only an exception if detailed information about the exception can be added, the exception is handled or some sort of compensation action is required. If the flow of execution can not continue, rethrow the exception so an exception can be handled further up the stack, e.g. inform the user.

catch (ArgumentException ex)
  // some clean up or logging
  throw ex;

When rethrowing exceptions, it is important to do it the right way. By using the above pattern regarding throwing and not throwing ex, the stack walk is not performed twice, making the rethrow virtually free.

If you want to know more read the book Framework Design Guidelines. It is recommended and easily read. You can also look at the blog entry Exception Throwing by Krzysztof Cwalina – one of the authors of the Framework Design Guidelines book. There is also a small summery at Design Guidelines for Exceptions on MSDN.

On a side note: the company mentioned was as one of the first I Denmark to adopt the .Net framework – in 2000 where beta 1 was released they build their first project on the .Net framework. Go figure!

Computer game ilities

When installing Ceasar IV from Sierra you are confronted with the following screen

A gamer has to tackle not only DirectX, but also the .Net framework and ODBC drivers for MySQL.
The games today are surely getting advanced to install. Do they really expect the average computer user to understand any of this?
It places the users in a dilemma – what is required and what is not. Hide the dependencies and the complex install from most users. Apparently the common; typical or custom install feature has not reached the gamming industry yet. Maybe it is time for the gamming industry to focus more on non-functional requirements… the ilities?

Visual Studio 2005 shortcuts features

I tent to forget the Visual Studio 2005 shortcuts really fast when I haven’t done any real coding and just Word “coding” for a while. The shortcuts are really important as they enhance my coding experience and boost my productivity (which makes my manager happy; which increase my bonus; which makes me even happier – it’s a full circle 🙂 ).
There are a bunch of standard Windows keyboard shortcuts which I will not discuss. But do take a look, as I doubt that you know all of them. More or less all can be used in Visual Studio.
These are essential Visual Studio 2005 keyboard shortcuts for C#

F5 Start debug.
Ctrl + F5 Start without debug.
Shift + F5 Stop debug.
F9 Toggle breakpoint.
F11 Step into method – Executes code one statement at a time, following execution into
method calls.
F10 Step over method – Executes the next line of code, but does not follow execution through
any method calls.
Shift + F11 Step out of method – Executes the remaining lines of a method in which the current
execution point is located.
Ctrl + Space List possible methods, classes etc.
Ctrl + Shift + Space Displays the name, number, and type of parameters required for the specified method.
Ctrl + J List members of a method.
Ctrl + K, I Displays the complete declaration for the specified identifier in your code in a Quick
Info tool tip. This includes exceptions!
Ctrl + R, R Rename dialog box, which allows renaming all references for an identifier.
Ctrl + R, O Displays the Reorder Parameters dialog box, which allows changes to the order of the
parameters for methods, indexers, and delegates.
Ctrl + R, V Displays the dialog box, which allows removal of parameters from methods, indexers,
or delegates by changing the declaration at any locations where the member is called.
Ctrl + M, O Collapses existing regions to provide a high-level view of the types and members in
the source file.
Ctrl + M, L Toggles all previously collapsed outlining regions between collapsed and expanded
Ctrl + M, M Toggles the currently selected collapsed region between the collapsed and expanded
Ctrl + K, C Inserts comments marking at the beginning of the current line or every line of the
current selection. This also works in HTML and XML files.
Ctrl + K, U Removes the comments marking at the beginning of the current line or every line of
the current selection. This also works in HTML and XML files.
Ctrl + K, D Formats the current document according to the indentation and code formatting settings
specified. This also works in HTML and XML files.
Ctrl + K, X Displays the Code Snippet Picker. The selected code snippet will be inserted at the
cursor position.
Ctrl + K, S Displays the Code Snippet Picker. The selected code snippet will be wrapped around
the selected text.
Ctrl + Shift + V Pastes text from the Clipboard ring to the cursor location in the file. Subsequent
use of the shortcut key iterates through the items in the Clipboard ring.

There are loads of other Visual Studio 2005 keyboard shortcuts for C# – you should check out this Microsoft poster or this complete list.
You can setup your own keyboard shortcuts under Tools | Options | Keyboard. The interface for setting up keyboard shortcuts sucks, but it is doable.

Keyboard shortcuts are not the only means of improving your productivity. Visual Studio snippets are a timesaver. They work by entering a snippet shortcut key and the pressing tab twice. Like “class + tab + tab”, then a class stub is created for you.

class Class stub
cw Console.WriteLne
enum Enum stub
exception Exception class stub
prop Property stub with getter and setter
propg Property stub with getter only
#region Code region stub
try Try/Catch block
tryf Try/Finally block

The snippet I love the most is exception – this snippet generates complete exception class in accordance with Microsoft guidelines. I used to hate implementing custom exceptions because it was so cumbersome.

You can see all the default snippets under Tools | Code Snippets Manager or keyboard shortcut Ctrl K, B ;-). You can also implement your own or do as I do; Google it.

You shouldn’t memorize all shortcuts, but adopt those which make your everyday life easier. You should however, every ones in a while think of expanding your arsenal of shortcut.

Have I missed any really important keyboard shortcuts or snippets? What are your favorite keyboard shortcuts and snippets? Let me know – I am expanding my arsenal 😀