Archive for the ‘C#’ Category

Creating a Custom Item Template in VS2008

Tuesday, December 22nd, 2009

I write a lot of C# code, so anything I can find to reduce the amount of time I spend “filling in the blanks” is great.  Visual Studio is perfect for helping out in these types of situations.  A case-in-point is the custom item template.

Whenever you select “Add New Item” on a project, you are shown a list of templates for the different items you can create.  These items range from new classes to database files to xml files.  I have found over time that I tend to always create the same basic structure for every class I write in C#:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

 

namespace ProjectName

{

    /// <summary>

    /// ClassName

    /// </summary>

    public class ClassName

    {

        #region Private Data Members

        #endregion

 

        #region Public Accessors

        #endregion

 

        #region Constructors

        /// <summary>

        /// Construct a default instance of ClassName

        /// </summary>

        public ClassName

        {

        }

        #endregion

    }

}

After filling out the same basic structure a number of times, I realized it was time to automate.  Fortunately, as I mentioned, VS08 makes this ridiculously easy.  First create a file to use as your template, then under the “File” menu, select the “Export Template…” option.

A dialog will appear asking if you are creating an item template or a project template.  In this case, we are creating an item, so select the item option, and choose the project containing the file you created to use as a template.  Next, you will select the actual file from the project.  Note that you can select multiple files if your template needs supporting files.  Select the references to include, and then provide a name and description for the file.  make sure you have it automatically import the template, and you are finished.

If you are curious about the template structure, you view the template files as a zipped file under “Documents\Visual Studio 2008\My Exported Templates”.  By editing the files in the zip file you can further refine and enhance your template, and you can fix any problems that might have occurred during export.

Casting Performance

Tuesday, May 12th, 2009

The system that I am currently working on depends a lot on casting an object to an interface to see if it implements that interface.  If it does, the system will take one action, if not, it will take a different action.  Because of this, casting performance is very important to the overall performance of the software.

As far as I am aware, there are 4 ways in C# to test if a given instance of an object implements an interface (without knowing the exact type of the instance).

1. “as” cast after an “is” check:

if (castingObject is StringBuilder)
{
  StringBuilder testBuilder = castingObject as StringBuilder;
  // do stuff
}
else
{
  // do other stuff
}

2. “as” cast with a null check:

StringBuilder testBuilder = castingObject as StringBuilder;
if (null != testBuilder)
{
  // Do stuff 
}
else
{
  // Do other stuff
}

3. Explicit cast after an “is” check:

if (castingObject is StringBuilder)
{
  StringBuilder testBuilder = (StringBuilder)castingObject;
  // Do Stuff
}
else
{
  // Do Other Stuff
}

4. Explicit cast with InvalidCastException:

try
{
  StringBuilder testBuilder = (StringBuilder)castingObject;
  // Do Stuff
}
catch(InvalidCastException)
{
  // Do other stuff.
}

Method #4 should clearly be the worst performing option if you expect any number of the casts to fail (since throwing an exception is very expensive in .NET).  So which of the three remaining methods would result in the best performance?  Well, the only way to know for sure is to measure it, so that’s what I did.

As Cast with Is check: 0.0082533 seconds.

As Cast with Null check: 0.0077226 seconds.

Explicit Cast with Is check: 0.008119 seconds.

Explicit Cast with No check: 448.7026034 seconds.

Judging from these results, doing an “as” cast followed by a null check is the fastest way to test if an object instance is of a certain type.  Of course, there is not enough of a difference between any of the first three methods to make me redo any existing code, and I certainly wouldn’t sacrifice readability/maintainability just to grab 5 milliseconds or so over 200,000 casts.

If you are curious I ran the casts inside a 100,000 iteration loop, with one “successful” cast and one “failed” cast, for a 50% success rate.  A more clever test would take into account the actual expected failure rate of the casts and use that to measure the performance, but this was just a question of curiosity for me – as I mentioned the possible improvements are too small for me to worry about as long as I avoid the explicit cast with no checks.

Code smells, and passing a generic instance as a strongly-typed parameter

Saturday, March 14th, 2009

Whenever I see repeated blocks of code, I become suspicious.? I start to wonder if I can’t refactor that common code into a common method and (hopefully) simplify the existing code.? Recently I ran across a pattern of code that occurred intermittently throughout the codebase.? The pattern had a form similar to this:

????? System.Diagnostics.Process svnLook = new System.Diagnostics.Process();
????? svnLook.StartInfo.FileName = "svnlook.exe";
????? svnLook.StartInfo.UseShellExecute = false;
????? svnLook.StartInfo.RedirectStandardOutput = true;
????? svnLook.Start();
????? string output = svnLook.StandardOutput.ReadToEnd();

?

That's all there is to it.? The local variable “output” holds the entire output of the svnlook program.? The ReadToEnd method is useful because it blocks until the stream is closed, allowing you to block until the execution is complete.

There are other ways to do this (such as using the System.Console.SetOut method), but this was by far the easiest method I found.? Note that you must set the UseShellExecute property to false if you redirect the standard output, otherwise you will get an invalid operation exception (according to the documentation).

All things told, it was a refreshing change of pace for me, and a fun way to spend an hour or so at work.? I may even write and post a full-featured hook one of these days (of course, I'd probably use a different language to make it as portable as possible). In the meantime, I guess I should get back to my own mini-project…

Undo/Redo – A Manager

Wednesday, January 7th, 2009

Now you know better than to use confirmation dialogs, and you know the basics behind creating an unlimited undo/redo system.? All that is left is the implementation.? Fortunately there is very little to implementing an undo/redo manager.

In reality, it only requires two classes.? The first class is the interface that defines how you will execute and reverse an action:

this.NamedArgumentPublished.Invoke(this,new NamedEventArgs(name));

Finally adding and removing handlers should also be remarkably familiar:

publisher.NamedArgumentPublished.AddHandler(this.HandleNamedArgumentPublished);
publisher.NamedArgumentPublished.RemoveHandler(this.HandleNamedArgumentPublished);

?

As you can see, the usage of the WeakEvent class is remarkably familiar, and as a bonus eliminates the need to test and avoid the race condition I discussed earlier.? So now that we have discussed how the class is used, we can peek under the hood to see how it works.

The heart and soul of the class is the WeakDelegate class I discussed earlier.? It works its magic by splitting an event handler into 2 parts:

  • The target object (the reference to the instance subscribing to the event)
  • The method information (the actual handler method)

Once it has split the event handler into those 2 parts, it stores the reference to the target object inside a WeakReference, preventing the event from keeping the target object alive.? The code to do this is handled by the constructor:

??? this.EmptyArgumentPublished(this, EventArgs.Empty);

Of course, there is a specific pattern that you should use to avoid a NullReferenceException being thrown (and to avoid a race-condition), but I will get to that a little later.? For now, it is useful to think of events as methods.

Subscribing

Subscribing to an event is even easier than publishing one.? All you need to do is define a method with an appropriate signature and then add it to the publisher's event:

????? publisher.EmptyArgumentPublished += this.HandleEmptyArgumentPublished;
????? // Alternatively you can use the fully qualified way (required in older versions of .NET)
????? publisher.EmptyArgumentPublished += new EventHandler(this.HandleEmptyArgumentPublished);

That's all there is to it.? You are now subscribed to the event.? This assumes of course that the method “HandleEmptyArgumentPublished” has the correct signature.? When you no longer wish to subscribe to this event, you can unsubscribe just as easily:

????? publisher.EmptyArgumentPublished -= this.HandleEmptyArgumentPublished;
????? // Alternatively you can use the fully qualified way (required in older versions of .NET)
????? publisher.EmptyArgumentPublished -= new EventHandler(this.HandleEmptyArgumentPublished);

In this case, the event will do a value-based comparison (as opposed to a reference-based) to determine which handler to remove, so you do not have to keep the original instance of the EventHandler that you created.

Best Practices

I glossed over quite a bit in my quick little introduction to events, so lets go back to the beginning and implement a slightly more complicated event.? The first thing to realize is that since events are simply a collection of method pointers, you can technically use any method signature you desire to define an event.? However, in .NET it is expected that all event delegates will have a signature with 2 parameters, where the first is an object and represents the instance that fired the event, and the second parameter is the actual event arguments and derives form the “EventArgs” class.? This still gives you incredible flexibility in the events you can create, but it does mean that creating a custom event requires a little bit more work.? Fortunately, with .NET 2.0 generics, they have made it a little bit easier.? The first thing that is required when creating a custom event is to create a new argument class.? By convention, this class should derive from the base “EventArgs” class and the name of the class should end in “EventArgs”.

Code In Review is proudly powered by WordPress
Entries (RSS) and Comments (RSS).