Dot Net Thoughts

September 29, 2007

Xml Code Snippets

A couple of months ago, I was giving a presentation about Web Services at the Portland Area Code Camp. The presentation was going okay, but I had the dreaded right-after-lunch time slot. The room was a little bit sleepy, to say the least. As I assembled a class, I typed prop and pressed tab twice. Studio diligently dropped a new property skeleton into my code. Suddenly, the room woke up. Everybody wanted to know what the cool add-in was that I was using, and where they could get it from. When I told them it was built into studio, they were elated. I don’t know if any of them remembered anything I had to say about Web Services, but I do know several of them went home and learned about snippets.

Xml Code Snippets are simply keyboard shortcuts for repetitive tasks that you may need to do in the IDE. If you open up the Studio IDE and select Edit–>Intellisense–>Insert Snippet (or press <ctrl>k – <crtl>x), a list of snippets available on the machine appear. Selecting prop, for example, from the list of available C# snippets creates a skeleton property, complete with member variable, into the class.


The property snippet highlights three values when dropped on the screen. The type of the property, the name of the property, and the name of the member variable. In the image above, myVar is highlighted. When I modify this variable name and tab off of it, the myVar in the getter and the setter will be updated automatically.

One of the neat things about Snippets is that you can create your own, or update the existing snippets. The included snippets are defined by default in %Program Files%\Microsoft Visual Studio 8\VC#\Snippets\1033\Visual C#. Modifying a snippet in this location will change the snippet for all users using the machine. Snippets can be modified for individual users by placing them in %MyDocuments%\Visual Studio 2005\Code Snippets\Visual C#\My Code Snippets. You can also define your own locations for storing snippets in the Code Snippet Management Window (<ctrl>k – <ctrl>b).

I’ve updated the property code snippet on my machine to take care of a couple of annoyances that I run into when debugging.

First of all, if I’m debugging a method in which I’m passing several properties on an object as parameters, I always have to watch the IDE go down into the getter, and step through retrieving the member variable. Microsoft has given us the ability to automatically move over these steps by adding a DebuggerStepThrough attribute to our code.

Secondly, an object’s data is exposed via the property itself. I don’t need to see the internal variables displayed when I’m using the data tips window. Once again, Microsoft will let us do that with the DebuggerBrowsable attribute.

To update the code snippet on my machine, I simply do the following.

1. Copy the property snippet (prop.snippet) from the location under program files into the location under MyDocuments.
2. Open up the snippet. I’ll see that there are two major areas to the snippet itself. The <Header> element in the Xml provides information about the snippet, and how it will be accessed. The snippet element declares what values the snippet will collect, and how it will apply them.
3. Modify the CDATA section of the Code element to include my new debugger attributes. When I’m done updating, my new Code element appears as follows. (Note that I’m using the fully qualified names so that I don’t have to include System.Diagnostics in every scenario where I want to use my snippet.

<Code Language="csharp">
<![CDATA[[System.Diagnostics.DebuggerBrowsable(System.Diagnostics.DebuggerBrowsableState.Never)] private $type$ $field$;
 public $type$ $property$
  get { return $field$;}
  set { $field$ = value;}

If I shut down and restart my browser at this point in time, my new snippet appears on the snippet menu.

Microsoft has released a lot of snippet add-ons for visual studio which can be found at

Code safe!


September 22, 2007

Error Handling – Best Practices

Filed under: Best Practices — dotnetthoughts @ 6:54 am
Tags: , , , , ,

I had a question from a friend about exception handling best practices earlier this week. He’d mentioned that it’s pretty hard to find good information about the topic. I rattled back a list of fairly generic dos and don’ts that we’ve all seen with exception handling before. As I thought about it a little bit more, I came to realize that we accepted a lot of these on blind faith, so I thought I’d take a little bit closer list of some of the error handling recommendations made in the .Net Framkework Design Guidelines.


Exceptions are fairly costly operations and will generally be considerably slower than a programmatic solution.  How much slower? To find out, I wrote a quick-and-dirty test application. This application divides two values, but, instead of returning an error to the client, it returns a null when attempting to divide by zero. The project contains two implementations of the calculator object: the calculator using exceptions, and the calculator not using exceptions. The only difference between the two is the way the division by zero is handled.

In the exception version, we are defaulting the return value to null, and simply hiding the exception when it occurs.

  public decimal? Divide(decimal numerator, decimal denominator)
    decimal? returnValue = null;
        return numerator / denominator;
    catch (DivideByZeroException ex) {}
return returnValue;

In the non-exception version, we are checking the denominator, and simply returning null if the denominator is equal to 0.

public decimal? Divide(decimal numerator, decimal denominator)
  decimal? returnValue = null;
  if (denominator != 0)
     returnValue = numerator / denominator;
  return returnValue;

While I was expecting there to be a little bit of a difference between the results, I was amazed at how big the difference was. On my machine, the object which was using exceptions ran 5000 iterations in 35 seconds. The version which explicitly checks the denominator value instead of using exception conditions ran in two milliseconds. [Note: Jon Skeet notes in the comments that this calculation is skewed, because I was running the code in the IDE at the time. He is correct. When running in the IDE, I get the 35 seconds to 2 milliseconds results. When running the compiled versions (Release or Debug), I’m seeing something on the order of 500 milliseconds to 2 milliseconds. It’s still pretty bad, but nothing on the order presented above.]

Handling Generic Exceptions

Section 7.2.2 talks about avoiding handling non-specific exceptions. For example:

catch (Exception ex) {//Handling here}

In general, this guideline is quite sound. If you are catching the general base class exception, you have no idea what has gone wrong, and shouldn’t attempt to recover from it. If an exception is thrown while writing to a file, for example, you do not know if the exception was because of an illegal file operation or due to an out-of-memory exception. It does take more time to research the appropriate exceptions that can be thrown by an object, but it can prevent a lot of pain in the long run.

The one exception I’ll often make to this rule is at the boundary of an object. If an exception has been thrown and has bubbled all the way up to the top of the stack, something truly unexpected has occurred. I’ll catch the generic exception object, log the exception to a log file, and then kill the application.

Use an Empty Throw

Section 7.2.2 also talks about using just an empty throw command when rethrowing an exception. In other words, use:

catch (Exception ex)
  {throw; }

Note that I’m not using throw ex. The primary reason for this is to maintain the stack trace. If you look at the Rethrowing Exceptions application, you’ll note that the only difference between the GoodErrorHandling and the BadErrorHandling methods is that good uses throw, and bad uses throw ex. Both methods call MyFlawedMethod which returns an InvalidOperationException. The resulting stack traces are displayed in a message box.

Examining the stack trace messages closely, you’ll notice something. The line number in the top frame of the stack points to different locations, even though the same base exception was thrown. The GoodErrorHandling frame points to the actual location of the error. When BadErrorHandling threw a new exception, however, the stack was reset and now points at the error handling in BadErrorHandling. This makes chasing down the originator of the actual error much less fun.

Code safe!

September 15, 2007

Debugging – Data when you want it, how you want it.

Filed under: Debugging — dotnetthoughts @ 8:00 am
Tags: , , , , ,

One of the keys to debugging is being able to get fast access to the data you’re interested in. Anybody who has developed code for any length of time knows the pain of drilling down through objects in the watch window to find the one property that is buried seven layers deep. Fortunately, .Net gives us the ability to see summaries of object data when we are debugging. Two of the most useful features for creating and viewing these data summaries are theDebuggerDisplay attribute and Visualizers. Both of these add debugging capabilities to Visual Studio by allowing you to see subsets of data or reformatted data more easily.

To demonstrate how these work, I have created a quick-and-dirty application which you can download here. The solution contains three individual projects.

  • The Family project contains a simple data object which represents an individual family in a phone book application. The object contains a location to enter a last name and a phone number, as well as zero to many family members associated with it.
  • The FamilyVisualizer is an application we can use to visualize our code in a friendlier format than what .Net will be able to provide by default.
  • The FamilyApplication exists to load and process family data. In reality, we’ll just set a few breakpoints in this object and look at the results.

The first item we’ll take a look at is the DebuggerDisplay attribute. This is a very easy way to pull to the surface exactly what data you need to see in an object. If you look in the Family object, you will notice that the class is prefaced with this attribute:

[DebuggerDisplay("Last Name: {LastName}")]

When debugging code, this attribute will cause the last name of the user to be displayed when you hover over the variable. Note that you can still drill down into the object to see the child properties should you need.

The DebuggerDisplay attribute is quite flexible, and will allow you to drill down in the object model, as well. For example, the following code displays the first child, assuming he exists.

[DebuggerDisplay("Last Name: {LastName} First Member: {FamilyMembers[0]}")]

The DebuggerDisplay is helpful from the standpoint of getting at data, but it isn’t so helpful in letting us visualize all of our individual family members. Since the FamilyMember property is one-to-many, we need a better way to display the individuals. This is where a custom visualizer comes in.

A custom visualizer is simply an object that extends the DialogDebuggerVisualizer and overrides the Show method. This allows you to use pretty much anything you can dream of to display data. If you look at the FamilyVisualizerDebuggerSide object in the sample code, you’ll note a couple of different things.

  • The class is marked with a DebuggerVisualizer attribute. This attribute contains information about what class is going to be used to present the visualizer (the FamilyVisualizerDebuggerSide), the type of object the visualizer is intended to display (the Family object), and a description for the debugger (Family Visualizer)
  • The project contains a form which we will use to customize our debugging display. It simply accepts data, and loads it into the appropriate labels and list boxes.
  • The class overrides the Show method, which will be used to display the debugger when debugging. Note that you must use windowService.ShowDialog to display the debugging form. (Calling familyForm.Show doesn’t work.)

If I copy my FamilyVisualizer dll into /MyDocuments/Visual Studio 2005/Visualizers and restart studio, I’m now able to access my visualizer directly from code that I have set a breakpoint on.


Selecting the visualizer displays the windows form which we created to show our family data.


If you want help creating you own visualizer, Microsoft has a very good Visualizer Walkthrough you can use.

 There you have it. a couple of handy tricks in a nut shell. Good luck and code safe!


September 9, 2007

Source Control

Filed under: Misc Thoughts — dotnetthoughts @ 10:49 pm
Tags: , , , ,

If I’m going to be writing a blog that involves code, tools, binaries, images, research and who-knows-what else, it’s critical that an organized process for storing and retrieving data exists. Any professional developer, while sitting at their desk at work, has some version of source control open and running all the time. Why? Because it is critical that one is able to go back to any point in history to examine what the code or documentation looked like.

So why are so many of us at home running without source control? I suspect it’s simply because it is one more application to set up and used on an already overwhelmed desktop. That seems like a fairly weak excuse, however. I can’t count the number of times I’ve wanted to see what a document looked like last week or last month, but was unable to.

So, I started searching the web for different source control options. Functionality, ease of use and price (i.e. free), were my main requirements. A little research on the web led to a couple of open-source standards. I’ve heard of companies using both CVS and Subversion with quite a bit of success, but I ended up shying away from both of them. Executing CVS was via command line switches that I never quite got to work right. Subversion documentation seemed to imply the same type of command line interface.

Eventually, I settled on ionForge’s Evolution. ionForge offers a free personal evaluation license for their source control with no expiration date, which is just perfect for the needs of an individual developer. It also seems to have a fairly impressive set of features beyond source control, such as process work flow, strong support for different versioning of branches (development vs. production), and good security integration. The user interface also seems to be fairly intuitive for basic activities.


The one drawback that I’ve discovered so far in working with the product is a lack of documentation. Several links in the help menu don’t seem to do anything. Also, I can’t find information in the included admin or client guide about some key features (such as the MS SCC API) that I find on the web site. I suspect that I’ll be able to work through any issues that come up with time, though. The price is right.

Anyway, that’s the thoughts for today. Good luck and code safe!


Create a free website or blog at