# Thursday, June 17, 2010

If it walks like a giraffe and talks like a duck then what is it?  Maybe a duhk?  Who knows, but it certainly is not a duck.  So if that is the case, then you can probably guess what the Duhking library is all about…or maybe you can’t.  In terms of programming, Duck Typing refers to the ability of some languages to allow you to treat an object of one type as an object of a different type, provided the methods/properties needed exist on both objects.  Statically typed languages are usually not very good at this sort of loosey-goosey type inference, which is why this behavior is typically restricted to languages with less stringent rules on typing.

The Duhking library is an attempt to provide a very limited view of Duck Typing to .Net 3.5 applications.  It allows you to graft an interface type onto an object that has matching properties and/or methods but does not actually implement that type.  Why would you do that?  Well, there were a couple of use-cases that drove the development of this library.  One is a case where you want to wrap an API that you have no control over in an interface so that you can test your consuming code.  This is common for things like HttpContext or SmtpClient where you want to utilize the functionality of those libraries in your code which you work so hard to make testable.  A standard approach to doing this is to create an interface which defines the methods you need, and then create a “wrapper” class that implements the interface, but then calls through to the real, un-testable class to do the work.  So my thought was this:  “Since we’re just calling through to matching method signatures in a class that already exists, why not abstract the whole thing so I don’t need all of these crazy Wrapper classes everywhere?”.

The other use-case came up when dealing with anonymous types.  We all know that you can create basic data objects as an anonymous type, and then use them within the scope they are created.  But what happens if you want to pass an anonymous type to another method?  Well, you have two choices.  You can either move the data in your anonymous type to another class/struct and pass that, or you can resort to some reflection trickery to get the values out of a plain old object.  It seemed like you should be able to create a new anonymous object as a particular interface type, and then pass it around as that interface type.

So the Duhking library allows you to do both fairly easily by use of some simple extension methods on object, and the magic of the Castle project DynamicProxy2 library.  Now that I’ve told you the secret, surely you can see how things work.  The library simply creates a proxy of the specified interface, and then intercepts calls to the interface methods, and in-turn calls the matching methods on the object we are “Duhking”.  There is some checking going on to ensure that your object is compatible with the interface you are wanting to Duhk, which involves checking method signatures (this is surprisingly complicated, considering it is the basis for compiler based interface implementation verification….but then I may be doing it the hard way), but beyond that its just passing calls off to the proxy.  But enough idle chit-chat, lets see a sample.

Okay, so lets take the first use-case where we are wanting a wrapper class for a sealed framework class so we can test our consumers.  Let’s go with the SmtpClient as an example because it is fairly common to want to send emails for various reasons.

First off we need out wrapper interface:

public interface ISmtpClient
{
    string Host { get; set; }
int Port { get; set; }

void Send(string from, string recipients, string subject, string body); }

You could add in additional properties or methods, but this is enough to get you going.  So now you can use this interface in place of the standard SmtpClient in the framework, and write your tests against it without major pain.  So the next step is to Duhk the real SmtpClient so it implements your interface when your ready to do the “real” work.

// Some code here getting ready to call your class that needs the client
var myClass = new ClassNeedingSmtpClient(new SmtpClient().AsType<ISmtpClient>());
// and now you do something with it

Pretty cool huh?  You can also check to see if the given concrete type can be Duhked by using the CanBe extension method

// Some code here getting ready to call your class that needs the client
var realClient = new SmtpClient();
if(realClient.CanBe<ISmtpClient>())
    var myClass = new ClassNeedingSmtpClient(realClient.AsType<ISmtpClient>());
// and do something else if it doesn't work

So now lets look at the other usage scenario, wrapping anonymous types in an iterface so you can pass them around.  The first thing we need is an interface to hold the data

public interface INamedSomething
{
    string Name { get; }
    int Id { get; }
    string SomethingElse { get; }
}

Note here that we are only specifying getters. That is because the properties of anonymous types are read-only, and right now the duhking code doesn't differentiate anonymous types from other types (more on that later). Ok, so with this we can now create an anonymous type and return it as an INamedSomething

public INamedSomething MethodThatReturnsSomething()
{
    // Some work goes here
    return new { Name = "Sam", Id = 1234, SomethingElse = "Hah!", SomethingElseNotInTheInterface = "Foo" }.AsType<INamedSomething>();
}

And this works fine. Notice I threw an extra property in there to show you that when we are checking for matching signatures we're only checking the methods/properties in the interface we're trying to Duhk. You can have as many additional properties or methods as you want in your concrete type, doesn't matter.

Now, as for that whole read-only thing.  Right now the code that checks compatability between your class and the target interface is ensuring that each method in the target interface has a matching method in the class.  This includes the compiler-generated methods for getting and setting properties.  That means that if your using an anonymous type as your class, you will never be able to Duhk it to an interface that has setters on it’s properties.  While technically correct there is something about this behavior that bugs me…it just doesn’t seem flexible enough.  So most likely what I am going to do is add some special handling for anonymous types that will allow the target interface to have both getters an setters.  This will in effect provide a way to stub out an interface implementation, and use the anonymous type to set the initial values of the interface.  This does change a bit the purpose of what I’m trying to do with this library, and gives it the added ability to stub out interfaces, so I’ve held off on doing this.  I think, though, that adding this functionality will actually increase the utility of the library, so it’s probably worth doing.

Right, so now that you have all of the grueling details, go get it, and let me know what you think.

posted on Thursday, June 17, 2010 5:46:05 PM (Eastern Daylight Time, UTC-04:00)  #    Comments [0] Trackback
# Tuesday, December 15, 2009

On November 27th, a beta release of the 9.3 version of the Developer Express components, including CodeRush and Refactor Pro! was made available to subscribers.  This release is pretty significant to me because it contains a major feature that I have been waiting for for a long time: A Unit Test Runner.  There were some teasers released by Mark Miller a while back, which only made me want to get my hands on the tool that much more.  My initial impressions are that it is very nice.  It is similar to TestDriven.Net in that it provides context menu options to run tests at various levels of granularity (single test, file, project, and solution level) and includes a debug option.  At this point it does not contain some of the additional coolness that TestDriven gives you like NCover/Team Coverage and TypeMock integration, but it does have the advantage of being extensible.  I know it was extensible because Mr. Miller told me it was extensible (the title “The Extensible Unit Test Runner You’ve Been Waiting For” was a clue).  I did not realize how extensible, however, until after I submitted a bug report to DevExpress.  The bug I was reporting (the NUnit TestCase attributes were not recognized), it turns out, was already brought to the attention of the DX team by way of a forum post, and they had already planned on correcting it with the next 9.3 release, but I could have saved myself (and Vito on DevExpress team) some time by taking a peek at the source samples bundled with the 9.3 release.  Yep, you guessed it, there with a shared source license were all of the test framework implementation projects.  So this meant I could whip together my own temporary fix while I was waiting for the next release.  It seemed like something that other folks might want to know about, so I thought I would share it here.

The biggest piece of the puzzle is a new TestExecuteTask class for handling the TestCaseAttribute.  Due to my complete lack of creativity, I called mine TestCaseExecuteTask, and it looks like this:

using System;
using System.Collections.Generic;
using System.Text;
using DevExpress.CodeRush.Core.Testing;
using System.Reflection;
using DevExpress.CodeRush.Core;

namespace CR_NUnitTesting
{
    public class TestCaseExecuteTask : TestExecuteTask
    {
        public override TaskExecuteResult CollectTestParameters()
        {
            TaskExecuteResult result = TaskExecuteResult.SkippedTaskResult;
            Attribute testCase = GetMethodAttribute("NUnit.Framework.TestCaseAttribute");
            if (testCase == null)
                return result;
            
            foreach(Attribute testCaseItem in TestMethod.GetCustomAttributes(true))
            {
                if(testCaseItem == null)
                    continue;
                var testCaseType = testCaseItem.GetType();
                if(testCaseType == null || testCaseType.FullName != "NUnit.Framework.TestCaseAttribute")
                    continue;
                PropertyInfo prop = testCaseType.GetProperty("Arguments");
                if(prop == null)
                    continue;
                foreach(MethodInfo getter in prop.GetAccessors())
                {
                    object[] parameters = getter.Invoke(testCaseItem, Type.EmptyTypes) as object[];
                    result.AddParameters(parameters);
                }
            }
        }
    }
}

This could be cleaned up some, and some of the magic strings extracted to constants, but overall it is pretty simple. Basically what is going on here is that we are looking for the TestCase attribute, and extracting the arguments for any attributes we find.  It just so happens that the TestExecuteTask base class has a CollectTestParameters() method we can override which allows for this sort of Row testing.  The parameters we extract get stashed in the execution result, which causes the test runner to execute the test once for each group of parameters (the result has a list of parameters, which gets populated with an array of objects for each TestCase attribute), and will correctly display which cases failed if there is a failure.

There are a couple other small changes that need to happen to get this to work.  There is an NUnitExtension.cs  class, which is the Plug-In class for the NUnit support, and it handles wiring everything up for us.  First off we need to initialize our new TestExecuteTask, and add it to the list of tasks that run for NUnit tests.  We do that in the InitializePlugin method of the NUnitExtension class:

public override void InitializePlugin()
{
    base.InitializePlugin();
    nUnitProvider.AvailableTasks.Add(new NUnitIgnoreTask());
    nUnitProvider.AvailableTasks.Add(new NUnitSetupTearDownTask());
    nUnitProvider.AvailableTasks.Add(new NUnitExpectedExceptionTask());
    nUnitProvider.AvailableTasks.Add(new NUnitValuesTask());
    nUnitProvider.AvailableTasks.Add(new NUnitRowTestTask());
    nUnitProvider.AvailableTasks.Add(new NUnitTimeoutTask());
    nUnitProvider.AvailableTasks.Add(new NUnitExplicitTask());
    nUnitProvider.AvailableTasks.Add(new NUnitTestCaseTask());
}
Ours gets added to the end of the list, so it will be executed. The next step is to get the plug-in to realize that a method with a TestCase attribute is an executable test method. That trick happens in the handler for the CheckTestMethod event on the UnitTestProvider. All we're going to do is add another condition to an if statement like so:
void nUnitProvider_CheckTestMethod(object sender, CheckTestMethodEventArgs ea)
{
    IMethodElement method = ea.Method;
    if(//method.Name != null && method.Name.StartsWith("Test")
       ea.GetAttribute("NUnit.Framework", "Test", method) != null
    || ea.GetAttribute("NUnit.Framework.Extensions", "RowTest", method) != null
    || ea.GetAttribute("NUnit.Framework", "TestCase", method) != null)
    {
        ea.IsTestMethod = true;
        ea.Description = ea.GetAttributeText("NUnit.Framework", "Description", method);
        ea.Category = ea.GetAttributeText("NUnit.Framework", "Category", method);
    }
}

The only change to the original code was the additional GetAttribute call at the end of the if statement (the comments were there when I got there, I swear).  Now the only thing left to do is to compile it and drop it in the plug-ins directory.  Now when you are looking at a test class, you should be able to run TestCase decorated test methods without problem.  Well, almost.  There is one thing I was not able to find a clean way to implement, and that is the Result property of the TestCase attribute.  This allows you to streamline tests which are doing equals assertions by having the test method return the actual result, and you specify the expected result by using the result property.  Unfortunately I could not find a way to hook into the actual execution of the test in such a way that I could have access to the specific test properties being used, and the result of the test method execution.  But considering the DevExpress folks will be fixing this issue, I’m sure when they release it there will be support for this feature.  After all, this is simply a stop-gap solution until the next CodeRush release is available, so I’m willing to live with this slight inconvenience.

Happy Testing!  

posted on Tuesday, December 15, 2009 10:08:44 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0] Trackback
# Monday, December 07, 2009

As of right about now, you should be able to mosey on over to the DxCore Community Plug-ins page, and grab a copy of CR_MoveFile.  This is a plug-in I created primarily as a tool to aid in working in a TDD environment, but which certainly has uses for non-TDD applications.  It does basically what CR_MoveFile_ScreenShotthe name suggests, it allows you to move a file from one directory in your solution/project structure to another, even one in a different project.  I implemented this as a code provider (since it could change the functionality if you move the file from one project to another), so it will appear in the Code menu when you have the cursor somewhere within the beginning blocks of a file (“using” sections, namespace declaration, or class/interface/struct declarations).  Once selected you are presented with a popup window which has a tree that represents your current solution structure, with your current directory highlighted.  You can use the arrow keys to navigate the directories and choose a new home for your file.

If you move files between projects, the plug-in will create project references for you, so you don’t need to worry about that.  When the file is moved the file contents remain unchanged, so all namespaces will be the same as they were originally.  I did this mostly to keep the plug-in simple, but also because I could see situations where this would be good, and situations where this would be bad, and it seemed like this was a bad choice to make for people.  I’ve been using this plug-in on a day-to-day basis for a while now, and things seem pretty clean, I did run into a small issue, however, using it within a solution that was under source control.  At this point you need to make sure the project files effected by the move are checked out, otherwise the plug-in goes through the motions, but doesn’t actually do anything, which is quite annoying.  There is also no checking going on to make sure the language is the same between the source and target project, so if you work on a solution that contains C# and VB.Net projects, you have to be careful not to move files around to projects that can’t understand what they are (oh, and the project icons used on the tree view are all the same, so there is no visual indication of what project contains what type of files).

That’s pretty much it.  Clean, simple, basic.  Used with other existing CodeRush/Refactor tools like “Move Type To File” and “Move to Namespace”, this provides for some pretty powerful code re-organization.  Just make sure you run all of your tests :).

posted on Monday, December 07, 2009 2:17:46 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0] Trackback
# Wednesday, October 07, 2009

Anyone who has been around me for more than a few hours while coding, or who pays any attention to me on Twitter will know that I am a huge fan of CodeRush and Refactor Pro! from DevExpress.  I consider these sorts of tools essential to getting the most out of your development environment, and I think CodeRush is one of the best tools available for a number of reasons, not the least of which is it’s extensibility.  CodeRush is built on top of DxCore, which is a freely available library for building Visual Studio plug-ins (incidentally, DevExpress also have a free version of CodeRush called CodeRush XPress, which is built on the same platform).  DxCore provides any developer who wants it access to the same tools that the folks at DevExpress have for building plug-ins and extensions on top of VisualStudio, and several developers (including yours truly) have done just that.

One of the more recent additions to the CodeRush arsenal are the CodeIssues.  As of the v9 release, CodeRush included an extensive collection of these mini code analyzers which will look at your code in real time and do everything from let you know when you have undisposed resources, to suggesting alternate language features you may not even be aware of.  A lot of these are also tied in to the refactoring and code generation tools that already exist within CodeRush and Refactor Pro! so that not only do you see that there is an issue or suggestion, but in a lot of cases you can tell the tool to correct it for you.  Pretty impressive stuff.

So what I would like to do is dig in to how the CodeIssue functionality works within CodeRush by creating a custom CodeIssue Provider.  Because I’m a TDD guy, one of the things I’ve been trying to do is build in some tooling around the TDD process to make it that much easier to write code TDD.  So based on that I’m going to show you how to implement a CodeRush CodeIssueProvider which will generate a warning whenever you have created a Unit Test method with no assertions (which would indicate that you are either dealing with an Integration Test, or your test is not correctly factored).  Note: Since the CodeIssue UI elements are part of the full CodeRush product, and not CodeRush XPress, this plug-in will note do anything unless you are running the full version of CodeRush.

Okay, so the first thing to do is to create a new Plug-In project.  This can either be done from the Visual Studio File –> New Project menu, or by selecting the New Plug-in option from the DevExpress menu in visual studio (if you are using CodeRush XPress and you don’t have the DevExpress menu, my man Rory Becker has a solution for you).  Regardless of which way you go, you will get a “New DxCore Plug-in Project” window, which will ask you what Language you want to write your plug-in in (C# or Visual Basic .Net), and what kind of plug-in you want, along with the standard stuff about what to name the solution and where to store the files.  For our purposes we’re going to go with C# as the Language, a Standard Plug-in, and we’ll call it CR_TestShouldAssert (the CR_ is a naming convention used by the CodeRush team to indicate it’s a CodeRush plug-in, as opposed to a Refactoring or DxCore plug-in).

image

Net up is the “DxCore Plug-in Project Settings” dialog.  This allows you to give your plug-in a title, and set some more advanced options which deal with how the plug-in gets loaded by the DxCore framework.  We’ll just leave everything as-is and move on to the good stuff.

image

Once your project loads you will be presented with a design surface, this is because a large number of the components that are available via DXCore can actually be found in the Visual Studio toolbox, and you can just drag them out onto your plug-in designer to get started.  The CodeIssueProvider is an exception, though, so we will have to crack open the designer file to add it to our plug-in.  So open up the PlugIn1.designer.cs file, and add the following line of code under the “Windows Form Designer Generated Code” section:

CodeIssueProvider cipTestsShouldAssert;
You'll need to add a using statement for the DevExpress.CodeRush.Core namespace as well.  Next we need to instantiate it, so we need to do this in the the InitializeComponents method.  When you are finished your InitializeComponents method should look like this:
this.components = new System.ComponentModel.Container();
cipTestsShouldAssert = new CodeIssueProvider(this.components);
((System.ComponentModel.ISupportInitialize)(this)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this)).EndInit();

Now if we switch back over to the designer, we will see our new provider on the design surface.  At this point we can use the Properties window to configure the provider.  The things we need to worry about filling out are the Description, DisplayName, and ProviderName properties.  The Description is the text that will be displayed in the Code Issue catalog, so it needs to clearly explain what the CodeIssueProvider is intended to do.  Let’s go with something like: “A Unit Test should have at least one explicit or implicit assertion.”  As for DisplayName, lets say something like “Unit Test Method Should Assert”, and make the ProviderName the same.

Ok, so now it’s time to actually do the work of finding a TestMethod that violates this condition.  So we need to switch over to the Events list for our provider, and Double-Click in the CheckCodeIssues drop-down so it generates an event handler for us.  You will now be taken to the code editor and presented with a empty handler that looks something like:

private void cipTestsShouldAssert_CheckCodeIssues(object sender, CheckCodeIssuesEventArgs ea)
{

}

This looks pretty much like your normal event handler, we’ve got the sender object (which would be our provider instance, and then we have a custom EventArgs object. Looking at this event args object, you can see quite a few methods, and a couple of properties.  The first few methods you see deal with actually adding your code issue, if it exists, to the list of issues reported by the UI.  You’ve got one method for each type of CodeIssue (AddDeadCode, AddError, AddHint, AddSmell,AddWarning), and then one method (AddIssue), which allows you to specify the CodeIssue Type.  Now this is where things start to get interesting because basically we’re at the point where the good folks who wrote DxCore have said “All right, go off and find your problem and report your finding back to me when your done”.  So from here we have to figure out whether or not there are any test methods without asserts floating around anywhere.  The good news is that there are a few tools in the CodeRush bag of tricks that can help us.

Perhaps the best tool for figuring out this sort of thing is the “Expression Lab” plug-in.  You can open this up by going to the DevExpress menu, opening the Tool Windows->Diagnostics->Expressions Lab.  This shows you in real time what the AST that CodeRush produces for your code looks like as you move about in a file.  You can also see all of the properties associated with the various syntax elements, and view how things are related.  This is a very handy tool to have.  Before we dig too deep into the Expressions Lab, lets get a start on finding our CodeIssue.  We know that we are going to be looking at methods here, since we are ultimately searching for test methods, so the first thing to do is to limit the scope of our search to just methods.  The CheckCodeIssues event is fired at a file level, so you are basically handed an entire file to search by the DxCore framework.  We need to filter that down a bit and only pay attention to the methods contained in the current file.  To do that we’re going to use the ResolveScope() method of the CheckCodeIssuesEventArgs object.  Calling the ResolveScope() method gives us a ScopreResolveResult object, which doesn’t sound very interesting, but this object has a wonderful little method on it called GetElementEnumerator().  This method will allow you to pass in a filter expression, and return all of the elements that match that filter expression as an enumerable collection. So to get to this, lets add the following to the body of our event handler:

var resolveScope = ea.ResolveScope();
foreach(IMethodElement method in resolveScope.GetElementEnumerator(ea.Scope,new ElementTypeFilter(LanguageElementType.Method)))
{
}

This looks pretty straightforward, but there are a couple of things I want to point out. First is the ea.Scope property that we are passing in to the GetElementEnumerable() method. This is the AST object that represents the top of the parse-tree that we are going to be searching for code issues in. Typically this is a file-level object, but I don't know that you can count on that always being the case (changing the parse settings could potentially effect how much of the code is considered invalid at a time, and so you could get larger or smaller segments of code).  The other interesting bit is the ElementTypeFilter().  This allows us to filter the list of AST elements given to us in our enumerable based on their LangueElementType (LanguageElement is the base class for syntax elements within the DxCore AST structure.  All nodes have an ElementType property which exposes a LanguageElementType enum value). In our case we’re only interested in methods, so we’re using LanguageElementType.Method.  The result is a collection of all of the methods within our Scope.

Now that we have all of our methods, we need to figure out if they are Test methods.  To do this we’ll have to look for the existence of an Attribute on the method.  Taking a look at Expressions Lab, we can see that a Method object has an Attributes collection associated with it. So we should be able to search the list of attributes for one with a Name property of “Test”.  Using Linq, we can do this pretty easily like this:

method.Attributes.OfType<IAttributeElement>().Count(a => a.Name == "Test")
This will give a a count of the "Test" attributes on our method. We can put this into an if statement like so:
if(method.Attributes.OfType<IAttributeElement>().Count(a => a.Name == "Test") > 0)
{
}
A quick note; I'm using the OfType<T>() method to convert the collection returned by the Attributes Property into an enumerable of IAttributeElements just as an easy way of enabling Linq expressions against the collection. Since DxCore is written to work with all versions of VisualStudio, there really isn't any official Linq support. As a matter of fact, using the expression we did limits the plug-in to only those people with .Net Framework 3.5 installed on their development machines. I think that in this day and age, this is a fairly safe assumption, so I'm not that worried about it. I would like to point out also, that having this expression in place does not prevent the plug-in from working with Visual Studio 2005, as long as the 3.5 framework is installed.

Ok, so now we have a list of methods, and we’re filtering them based on whether or not they are Test methods (defined by the existence of a Test attribute).  The next thing to do is look for an Assert statement within the text of our method.  This is another place where the Expressions Lab proves invaluable.  Looking at Expressions Lab we discover that our Assert statement is in fact an ElementReferenceExpression and is a child node of our Method object.  With this knowledge in hand we can use the FindElementByName method on our Method object to look for an Assert reference:

var assert = method.FindChildByName("Assert") as IElementReferenceExpression
Now all we have to do is test whether or not our assert variable is null, and we know whether or not this method violates our rule. Once we do that test we can add the appropriate Code Issue Type to the CodeIssues list using our event args. The last piece of the puzzle then will look something like this:
if(assert == null)
{
    ea.AddIssue(CodeIssueType.CodeSmell,(SourceRange)method.NameRanges[0],"A Test Method should have at least one Assert");
}

With this in place we should now be able to run our project and try it out. Using F5 to debug a DxCore plug-in will launch a new instance of Visual Studio. From there if you create a new project, or open an existing project, and write a test method which does not have an Assert, you should see a red squiggle underneath the name of the method. Hovering over that with your mouse you'll see our Code Issue test presented. Adding an Assert will make the Code Issue disappear.

image

Well, things are looking good here, we’ve got code that is searching for an issue, and displaying the appropriate warning if our condition is met.  There is one other condition we should probably consider, however.  The one case I can think of when our rule does not apply is when we are expecting the code under test to throw an exception.  In that case there would be an ExpectedException attribute on the test class.  To make our users happy we should probably implement this functionality.

The good news is we already know how to accomplish this, since we are using the same technique to determine if the method we’re looking at is a test method.  All we need to do is change the test condition in our Count() method so it looks for “ExpectedException” instead of “Test”.  While we’re at it it seems like a reasonable thing to get an instance of the attribute and then check it for null, similar to how we’re handling the assert.  With all of this done the code should look like this:

var assert = method.FindChildByName("Assert") as IElementReferenceExpression;
var expectedException = method.Attributes.OfType<IAttributeElement>().FirstOrDefault(a => a.Name == "ExpectedException");
if (assert == null && expectedException == null)
{
    ea.AddIssue(CodeIssueType.CodeSmell, (SourceRange)method.NameRanges[0], "A Test Method should have at least one implicit or explicit Assertion");
}
So now we should be able to run this, and see that the code issue disappears if we have a test method with either an assert statement, or an expected exception attribute. Pretty cool. You’ll notice that I also updated our issue message so it reflects the fact that we are able to handle implicit assertions (in the form of our ExpectedException) attribute.  For the sake of completeness, here is what our finished CheckCodeIssues method looks like:
private void cipTestShouldAssert_CheckCodeIssues(object sender, CheckCodeIssuesEventArgs ea)
{
    var resolveScope = ea.ResolveScope();
    foreach (IMethodElement method in resolveScope.GetElementEnumerator(ea.Scope, new ElementTypeFilter(LanguageElementType.Method)))
    {
        if (method.Attributes.OfType<IAttributeElement>().Count(a => a.Name == "Test") > 0)
        {
            var assert = method.FindChildByName("Assert") as IElementReferenceExpression;
            var expectedException = method.Attributes.OfType<IAttributeElement>().FirstOrDefault(a => a.Name == "ExpectedException");
            if (assert == null && expectedException == null)
            {
                ea.AddIssue(CodeIssueType.CodeSmell, (SourceRange)method.NameRanges[0], "A Test Method should have at least one implicit or explicit Assertion");
            }
        }
    }
}

And that's it. Granted there are some things here I would like to change before releasing this into the wild. We are specifically looking for NUnit/MbUnit style test method declarations for one, and we are also looking only for the short version of the attribute names, but this should give you a good idea of how things work.

If you are interested in seeing a more polished final version, you can either download the finished source for this post, or have a look at my CR_CreateTestMethod (admittedly poorly named) plug-in on the DxCore Community Plug-In's site.

posted on Wednesday, October 07, 2009 1:22:35 PM (Eastern Daylight Time, UTC-04:00)  #    Comments [0] Trackback
# Friday, September 18, 2009

I ran into this odd problem recently working with some Linq2SQL based persistence code.  There is some code someone put together to commit a list of changed entities to the database as part of a single transaction, which simply iterates through the list and performs the appropriate action.  The problem I was having was that I had an object referenced by another object that needed to be persisted first, otherwise there was a foreign key violation.  To add to the strangeness there seemed to be some magic going on (most likely utilizing the INotifyPropertyChanged goodness), so that even if I tried to persist just my dependent object first, both were still showing up in the list, and always in exactly the wrong order.  Now, I’m okay with magic.  Magic makes a lot of things a lot easier.  The problem arises whenever the magic is incomplete, and doesn’t follow through to take care of all of the operation.  Its like someone comming up to you and saying “Pick A Card”, at which point you do, and put the card back, and they say “I know what your card was” and walking away.  Not real convincing.  This is what was going on here.  There was the smarts to know that changes were being made to more than one entity, and there were even attributes to define what properties contained dependent objects, but no smarts to actually deal with a case when you would want to save more than one object in an object graph at a time.

So it occued to me I should be able to do some linqy magic and create some sort of iterator that would return dependent objects in the appropriate order, so the lest dependent of the objects get move to the beginning of the list.  My first step, since I wasn’t really sure how to do this, was to write a test.  And I made it more or less mirror the issue I was facing, a list of two items, one of which is a dependency of the other.  I don’t know if there is a lot of value in posting all of the test cases here, but the end result was rather nice.  Sure it took several iterations, and there was plenty of infinite looping and stack overflows (which does some fun things to studio when your running your tests with TestDriven.Net), but I think this is a reasonable solution to the problem:

public static IEnumerable<T> EnsureDependenciesFirst<T>(this IEnumerable<T> items, Func<T ,IEnumerable> selector)
{
    if(items.Count() < 2)
        return;
    var firstPass = items.SkipWhile(t => items.Intersect(selector(t)).Count() > 0);
    var remainingItems = items.Except(firstPass);
    if(items.Count() == remainingItems.Count())
        return remainingItems;
    return firstPass.Concat(remainingItems.EnsureDependenciesFirst(selector));
}

Ok, so what do we have here?  Well to start out I’m checking the item list to see if there are at least two items in it, if not I just return the list.  This provides a means to avoid an infinate loop due to the recursive call, and provides a shortcut for a scenario with only one item.  Next off I use the SkipWhile() method, combined with the user-supplied selector function to iterate through each item, retrieve it’s list of dependencies (which is what the selector function does), and checks to see if the current list contains any of the dependencies for the object.  The results of this first pass are the objects which have no dependencies at all, so therefore they need to be first in the list.  The next logical step is to run the operation again for a list that does not contains the items filtered out by the first pass.  This is done via a recursive call back to the EnsureDependenciesFirst extension.  You will notice we’re checking the count of the remaining items against the current list, and returning the list if they are the same.  This is another safety precaution for dealing with infinite loops.  If we have a circular dependency, this bit will just return the items that are interdependent.

You will note that this is a generic function that has really noting at all to do with the entities that I am dealing with.  This was largely due to the fact that this was built TDD, so I just used a simple class which had a property that could take another instance of itself.  To use this to overcome my entity committing problem, I would have to write a not too small function to retrieve the list of dependent objects from the entity (since there would need to be some reflection magic to look at attributes on the properties to determine which properties contain dependencies), but it pretty much will drop in to the foreach statement that is currently being used to persist the entities.

Incidently, I learned from my dev team what the “official” way of dealing with this is a “ReorderChanges” method, which takes two entities, in the order in which they should be persisted.  I think I like my solution better, mostly because it should mean I don’t have to worry about it again.

posted on Friday, September 18, 2009 4:08:47 PM (Eastern Daylight Time, UTC-04:00)  #    Comments [0] Trackback
# Wednesday, September 02, 2009

I was pleased to find recently that Roy Osherove’s Art of Unit Testing was available on Safari.  I have been following Roy’s blog for a while now, and was quite excited at the prospect of him writing a book on Unit Testing.  It was only my personal cheapness that kept me from shelling out the $25 to get the E-Book version from Manning ahead of time.  I have to say, now that I have read it, that it would have been well worth the money.  Before I get too deep I want to provide some context for what I am about to say.

I consider myself an experienced TDD practitioner and Unit Test Writer
So that means that I was reading this book hoping to gain some insight.  I wanted to find out how to write better, more readable, more maintainable tests.  I was also hoping for a little bit of “atta-boy” affirmation that the way I do things is the “right” way.  The astute reader may be able to tell that in order for my first hope to be true, the second may have to get some points taken away.  This was in fact the case, and to be honest, coming out of it I feel like I’ve gotten more value from the things I’ve learned than I received from whatever ego stroking may have occurred with what I am currently doing right.

So lets get started….
I was expecting the book to start out essentially as it did, some brief history about the author and an introduction to Unit Testing for those who may not be familiar with it.  I have to say I was expecting the book to be a little more TDD-centric than it was, but I think most of that was my own bias for TDD as “The Only Way To Write Software”.  Roy actually explained what TDD was, and also why he wasn’t going to harp too much on it throughout the book.  I have to say, I can see why he made the decision that he did.  I can also say that it seemed perfectly clear to me that TDD is a technique that he feels has a lot a value, which made me happy.  Since this is supposed to be a review from the perspective of an experienced practitioner of TDD and Unit Testing, I’m not going to go into anything that was touched on in the early chapters, apart from noting that they contained a general introduction to the tools, technique and philosophy of unit testing.  I can also say that, though I was already familiar with the material, I didn’t mind reading through it at all.  Overall, Roy’s writing style was light and quite pleasant, even for a technical book.

And now into the meat of the book…
For me, things started getting interesting in Part 3 of the book.  This is where issues of test design and organization are addressed.  This is one of those areas that I feel like I need some guidance on, mostly because I developed my testing idioms mostly through habit, and trial and error.  I look back on tests I have written in the past (which could be as little as two days ago) and I wonder how I could have come up with such a brittle, unmaintainable nightmare.  I feel like I need guidance from the experts on what I can do better when writing my tests.  Roy delivered on these items in chapter 7 “The pillars of good tests”.  One of the lessons I took away from this was the value in testing one concept per test.  I had heard this as “one assert per test” in the past, and scoffed at the idea.  But Roy presents a very compelling argument for why this is a good idea, if you are testing multiple concepts, you don’t know the extent of the problem when your test fails.  And lets face it, the failing test is the reason we’re doing this whole thing.  I’ve seen personally the failing test that just keeps failing.  You tackle the issue from one failed assert only to rebuild, and find one right after it which fails as well.  One of the issues I’ve had with this is the redundant setup and configuration that could be required for exercising this concept, but this issue is also addressed by the straight forward recommendation of creating clear and understandable configuration methods.  In the past I have generally not been really good about applying DRY to my test setup, which, I know, is another case of treating tests differently from regular code.  Having someone in a position of authority (like Roy) say, “put your setup in separate methods so you can re-use them and make your tests more readable” made it okay to do the thing that I knew I should be doing anyway.  The key concepts covered are making tests readable, maintainable, and an accurate portrayal of the authors intent.

Even more in depth….
Section 4 goes even further and talks about how to integrate unit testing into an organization which is not already doing it.  This is an interesting subject to me as I have recently moved to a company which has not been doing unit testing and TDD as part of their regular development process.  Roy draws on his experiences as a consultant to provide some really good advice for how to go about enacting this sort of change in an organization.  I particularly pleased with his candor when he describes his failed attempts at integrating unit testing.  It would have been quite easy to simply say “Based on my considerable expertise, these are the things you need to do”, but he chooses instead to share some real-world experience in a straight forward way that only adds to my respect for him as a professional.  In addition to this, he touches on techniques for integrating testing into “legacy” code (i.e. code which is not tested).  He does a good job at introducing some techniques for testing what is essentially untestable code, which a very large nod at Michael Feathers’ “Working Effectively with Legacy Code”.

The book ends with three appendices, one discussing the importance of testability in the design process, one listing vairous testing tools (both Java and .Net), and the last listing guidelines for conducting test reviews.  This last one is nice, because it presents a concise view of all of the guidelines presented throughout the book, and provides page references where you can get the “why” behind each. 

All in all…
This is a really good book, which should be part of any agile development library.  It doesn’t matter if you are writing your first unit tests, or you’re a seasoned pro, there is going to be something here for you.  I think it is great that Roy has chosen to share his experience with the developer community in this way.  I came into this book with some rather high expectations and I think they were met.

A note on TypeMock….
I remember seeing some criticism floating around on twitter suggesting the book was rather pro TypeMock.  There was also the comment that Roy’s affiliation with TypeMock was not made clear early on.  I can’t say I saw either of these things when I was reading it.  For starters, I already knew Roy worked for TypeMock, so perhaps that skewed my ability to objectively judge if the disclosure was done in a timely manner or not.  I can say that the places in the book which there seemed to be a preference for TypeMock were places where he stated things like “I feel TypeMock has a better syntax in this case”, or “TypeMock is the only tool with provides these capabilities”.  For starters, the first is a statement of preference.  Sure Roy helped design the API for TypeMock, so it seems only natural that he would prefer it to other frameworks, but having used it I would have to agree with the statement.  It is a great API, and example if a fluent interface done well.  The second comment is also plain fact.  Of the mocking libraries available in the .Net space, TypeMock is the only one that allows you to swap instances of objects in place, without making changes to the classes using them.  You can argue over whether or not this is a good or a bad thing, but the fact remains that it is a feature specific to TypeMock.  Maybe I was expecting something more blatant and obvious, but I just didn’t see it.

posted on Wednesday, September 02, 2009 1:36:02 PM (Eastern Daylight Time, UTC-04:00)  #    Comments [0] Trackback
# Friday, June 19, 2009

The folks at TypeMock have released a new UnitTesting tool aimed specifically at catching deadlocks in multithreaded code called TypeMock Racer, and what's more they are offering free licenses to folks willing to review it during the 21 day free trial period.  As anyone who knows me can testify to, I am a whore for free-bees, so I decided to take them up on this.

For the impatient, here is the executive summary:
This is a good tool.  Period.  It is, however, also a very specific tool that is intended to help find very specific problems.  If you are not doing any multithreaded code, there is no need to have it in your toolbox.  The cost ($890 US) is high enough that it doesn't really seem worth it to get it "just in case" (unless, of course, you right a nice review on your blog and get a free license).  If you do work with multithreaded code, and you are concerned about deadlocks, this tool will save you lots of time, which ultimately means money.

Now, for the details

First of all, this is a tool from TypeMock, so I expected some pretty incredible things, even at the 1.0 release.  After all, their flagship product TypeMock Isolator is phenomenally powerful, so much so that the free license I was given for posting an advertisement for the release of their ASP.Net product has gone largely unused.  I'm just scared of it.  It's like having access to a 50 horse-power tablesaw with no blade guard.  I may be careful enough to use it correctly most of the time, but the fact that it can take off my forearm without pausing to ask my permission makes me reluctant to get too close.  I do know that there are some very real problems that the tool can solve that just can't be done with any other tool, so I have every intent of getting up my courage, grabbing a first aid kit, and jumping in to see what I can do...eventually.

But Racer is different.  It is a very powerful tool with a very specific purpose.  It makes it easier to run tests in multiple threads, and detect deadlocks.  As far as I can tell, it just detects deadlocks, not race conditions, as it's name seems to suggest.  Not that this is bad, just that it only covers half of the rather shaky ground that is traveled while working with multithreaded code.  It is arguable, however, that dealing with deadlocks is the more difficult of the two problems, so getting this one tacked first is not a bad thing.

So how does it work?

Fairly straight forward really.  Start with a regular unit test, that is exercising some code that is utilizing locks in an attempt to be thread safe.  It looks like Racer supports just about every form of Synchronization supported by .Net, so you can feel free to use whichever mechanism you are more comfortable with to get the work done.  Now that you have a test, the simplest way to make use of Racer, is to add the Typemock.Racer library reference to your test project, and then add a ParrellelInspection attribute to the test.  This causes Racer to do it's thing, which by default means running the test once with a single thread, and then run it again using multiple threads (2 by default).  If there are no problems, nothing much new happens.  You see some additional information about the test being run first with one thread, and then multiple, and something about scenarios executed...nothing that exciting.  The coolness happens when you actually get a deadlock.  For starters you test output includes a bunch of new information, the most noticeable of which is a big "DEADLOCK discovered when running the following" message.  Also is a description of the scenario that caused the deadlock.  Something like "Thread 1 acquired lock A, Thread 1 released lock A, Thread 2 attempted to acquire lock B, etc".  Cooler yet is a message that says "To reproduce or debug this, copy the following attribute, paste it on top of your test and rerun the test:", followed by something that looks like

[SpecificScenario("2", 1, 2, 1, 1, 1, 1, 1, 2, 1, 1, 1, 2)]


Which, while being completely incomprehensible to humans, causes your test to run in the specific configuration which caused the deadlock to occur.  This means that you can accurately recreate the exact situation that lead to the problem.  If you have ever had to try to track down a deadlock in a live system, you will realize that this information just saved you countless hours of trying to recreate the production environment, and lots of trial and error getting things into the state that caused the problem.  One word: Brilliant!

So what is the down side?

I have to say that I've not yet been able to figure out how Racer determines what scenarios to run, or what the bits in the "SpecificScenario" attribute mean(well, the first string parameter is the number of threads, and the other numbers refer to the specific threads, and match the summary of the scenario, but beyond that, not a clue).  It would be interesting to know these things, but not really critical, as long as you are confident all appropriate scenarios are being executed.

There is also an interesting feature that I can't quite get my head around.  When you run a test with a deadlock, an image is generated, which is supposed to be a visual representation of the scenario that created the deadlock.  Here is an example:


 

Now, I see the three objects I was locking against (sync1, sync2, and sync3), and I guess the odd rhombus shaped objects represent the threads, but I'm not really sure what the diagram is trying to tell me.  This is, no doubt, something which is still fairly raw in this early version.  I think it could be very useful if it were clearer what the shapes and arrows represent, but at this point it is simply a cleaver bit of kit that you can show somebody so that they can be confused too.

The last issue I can see with it currently is the price.  At $890 US for a single user license, it isn't an impulse buy.  Granted, I think it can pay for itself easily after finding a few deadlocks in some production code (the earlier they are found the more that find is worth), but I don't see it being a terribly easy sell for management, at least if you are not actively trying to correct a threading issue.  I feel pretty fortunate that I work for a company that understands the value of good tools, and is willing to provide them if there is a need, but I think it would take some convincing to get management to agree to purchase Racer simply because it is a good tool, and could really pay off "one day".  If we were facing a threading issue, and I could demonstrate that racer would allow us to find it, and accurately reproduce it, it would be a fairly easy sell. 

So overall

I think this is an excellent tool.  Based on the fact that this is an early release, I can only see it getting better over time.  It is a rather pricey tool, however, so you may have to do some convincing to get the boss-man to get you a license.  There is a 21-day trial, however, so if you find yourself in a situation where you either have, or you could conceivably have, a risk of deadlock, then grab the trial, and use the first detected deadlock as justification to get a full license. 

posted on Friday, June 19, 2009 12:31:17 PM (Eastern Daylight Time, UTC-04:00)  #    Comments [1] Trackback
# Sunday, February 22, 2009

So, to take a slightly different turn from my usual meta discussions of process, theory, and architecture, there have been several people who have offered up some examples of extension methods that they have found useful, now that .Net 3.5 is roaring along nicely.  There are some collections of such utilities, like the Umbrella project, and some folks like Bill Wagner who have written books on the subject (okay, there are other things in there too), so I thought I might as well throw my hat into the ring as well.  Specifically, there was this tweet from @elijahmanor a few days ago.  It points to a positing which includes some extensions on string to convert from strings to value types (int, long, short, etc).  I pointed out that in our current project we have distilled this down to a single extension method: To().

He suggested I blog about it, so here it is:

So we actually have two classes of conversions, one converts from a string to a value type, and they other converts from a string to a Nullable value type.  In the case of our project, the nullable version came first, and so it became very easy to create the version that returned a non-nullable value.  Here are the methods of interest:

public static T To(this string input) where T : struct
{
    return input.To(default(T));
}

public static T To(this string input, T defaultValue) where T: struct
{
    return input.ToNullable() ?? defaultValue;
}

public static T? ToNullable(this string input) where T : struct
{
    if (string.IsNullOrEmpty(input))
        return null;
    var tryParse = GetTryParse();
    return (T?)tryParse(input);
}

Okay, so this is pretty straight forward.  The non-nullable version calls through to the nullable version, and if it is null, it returns default(T).  But, as I'm sure you are an astute reader, you will see that there is some magic going on; namely the GetTryParse() method.  This little guy goes off and looks for a TryParse method on whatever T happens to be, and then returns a Func<> delegate that will run the string input through the try parse and return either a null (in case the TryParse fails), or a boxed version of the result.  So, lets see what it looks like before we discuss pros and cons

private static Func GetTryParse()
{
    var tryParseEx = GetTryParseExpression();
    return (s) => tryParseEx.Compile()(s,default(T));
}

private static Expression> GetTryParseExpression()
{   
    if (_tryParseCache.ContainsKey(typeof(T)))
	return _tryParseCache[typeof(T)] as Expression>;

    MethodInfo tryParse = typeof(T).GetMethod("TryParse", new Type[] { typeof(string), typeof(T).MakeByRefType() });
    Ensure.IsNotNull(tryParse, string.Format("Cannot convert from type string to type {0} because {0} does not have a TryParse method", typeof(T).FullName));

    var stringArg = Expression.Parameter(typeof(string), "input");
    var tempArg = Expression.Parameter(typeof(T), "tmp");

    var tryParseEx = Expression.Lambda>(
        Expression.Condition(
            Expression.Call(tryParse, stringArg, tempArg)
                , Expression.Convert(tempArg, typeof(object))
                , Expression.Constant(null))
        , stringArg, tempArg);
    _tryParseCache.Add(typeof(T), tryParseEx);
    return tryParseEx;
}

So here we have some code looking for a TryParse method, and building an expression (using Linq Expression Trees) to execute it.  Now, I'll be honest, this is not the code I'm using in the project where this originally came from...mostly because I didn't think of it then.  In that case I'm actually doing a big case statement, checking the type of T and running the appropriate method.  This is much shorter, but potentially much slower at runtime.  So that is where the _tryParseCache comes in.  This is a simple static dictionary which contains the expressions created for each of the types, which means you only get the runtime performance hit once when you first ask to parse a specific type.  The declaration for this object looks like this:

private static Dictionary _tryParseCache = new Dictionary();

There you have it, my first (and possibly last??) contribution into the world of extension methods. Please commence criticisms

posted on Sunday, February 22, 2009 12:19:09 PM (Eastern Standard Time, UTC-05:00)  #    Comments [1] Trackback
# Tuesday, October 02, 2007

I'm currently finding myself in the midst of an evolutionary change.  And I'm not talking about my super-human mutant powers, I'm talking about the way I'm thinking about solving a specific set of problems.

Let's start with a sample....Lets take something like processing credit-cards as a benign and IP free place to start.  As a subject that I really have no practical experience with, it seems like an appropriate choice.  I'm going to assume that there are different rules for doing checksum validation on credit card numbers, depending on what the card is (Mastercard/Visa/Discover/etc). Now, here is evolutionary step 1: Use a basic case statement to process the various cards.  Here is what something like that would look like:

switch(CardType)
{
    case CardType.MasterCard:
        CardValidators.MasterCardValidator(card.CardNumber);
        break;
    case CardType.Visa:
        CardValidators.VisaValidator(card.CardNumber);
        break;
    case CardType.Discover:
        CardValidators.DiscoverValidator(card.CardNumber);
        break;
}

 

This looks pretty straight-forward, and as it stands it isn't too bad from a maintainability stand point.  But what happens when there are many different types of cards?  An then what happens when you find a large amount of duplication between the validation functions?

Well, any student of GoF should be able to tell you that a Chain Of Responsibility pattern looks like a perfect fit for this sort of scenario.  So, evolutionary step 2: Create separate classes to handle the different types of validation, and configure them in a Chain of Responsibility pattern where each instance decides for itself whether it can process the input.

Here is a quick and dirty look at what something like that would look like:
ClassDiagram1

 

The two most interesting things here are the GetValidator() method in the AbstractCardValidator, and the individual CanValidate() methods in the concrete implementations.  What this does is it allows each class to decide for itself how it is going to determine whether or not it can be used as a validator for a specific card (thats the CanValidate() part), and also provides a single point which the consumer of the API can use to get the validator for the card instance they have.  You would probably want to build and Abstract Factory around this, which would instantiate all of the ICardValidator classes, and then run the GetValidator() method to get the correct one.

Now we are at a point where things are looking pretty good; we've got the ability to do some fairly complex logic to make the decision about which validator to use, and we have a way to simply ask for one, and the correct one appears.  Pretty cool.

This is actually the place where I have found myself in the not to distant past.  I have previously been perfectly content with this arrangement, and been fairly happy with the separation of concerns among the classes...I mean, after all, who better to decide whether or not a specific class should be used to validate a card than the class itself.  So what is the issue?  Well, recently I have become aware of two problems with this arrangement: Tight Coupling, and a violation of the Single Responsibility Principle.  Let's start with the first:

Tight Coupling
The credit card example may be a bit contrived when it comes to this issue, but bear with me.  Overall, the issue is that specific instances of ICardValidtor objects are being created and handed around.  The use of an interface and an Abstract Factory pattern would actually help the situation out some, but effectively all it does is move the coupling from the consuming class to the Factory (okay, it also consolidates coupling to a single class, which makes maintenance a lot easier).  As I said, contained, but still there.  It would be nice if the factory didn't need any knowledge of what concrete instances of ICardValidator were out there.  Before we tackle that, though, lets also look at the second issue:

Violation of the "Single Responsibility Principle"
The SRP states that a class should have one, and only one, thing it is responsible for.  Sounds pretty easy doesn't it?  The problem is that this can be difficult to obtain without a fair amount of discipline.  The violation of SRP which I'm seeing is that the ICardValidator is responsible for both validating a credit card and determining which validator is appropriate.  But wait!  Didn't I just say that moving this check into the ICardValidator instance was a "Good Thing"?  Well, lets go as far as saying it is better than the previous method, but still not perfect.  Applying the SRP would move the task of selecting a validator from the ICardValidator instance, and put it on it's own somewhere.  So, thusly we come to our:

Inversion Of Control Container.
That's right, we are now going to get crazy and move the responsibility of creating these instances to another component all together.  The nice thing about this is that it allows us to move all of the knowledge about dependencies off somewhere else.  How does this apply to this example?  Well, lets assume we have an object of type Card which requires as a dependency an instance of an ICardValidator.  We'll also assume that Card is subclassed based on the type of credit card.  It now becomes trivial to configure our IoC container to supply a specific implementation (read sub-type) of ICardValidator for each implementation (again, read sub-type) of Card.  Now, when you want a Card instance, you ask the IoC container for one, and depending on what type of card it is, you will get the appropriate ICardValidator as well.

What's the catch?  Well there is some additional complexity which will show up somewhere in the application due to the IoC, but typically IoC configuration can be delegated down to the configuration file level, so even then the ugliness is pushed away to it's own dark corner.

But wait!  Why should we have different instances of Card?  What if the Card class is just a container for the card data?  Well, our Ioc still gives us some advantages.  If we look back at our first example with the switch statement, we've got a nice CardType enum, which could be a property of our Card class.  Using an IoC container like the one provided by the Castle project, you have the ability to configure a key string for your instances.  This would make it trivial to map the enum choices to specific keys within the container, which the Card class would use to get an ICardValidator instance.  This would also make it possible to make the validators slightly more advanced by adding something like a Decorator pattern, in which specific aspects of the validation could be factored into separate classes, and then "stacked" to produce the final validation logic (This is the same concept used by the Stream classes in .Net and Java.  You can modify the behavior of a stream by passing it to the constructor of a stream with different behavior).

It is definatly worth mentioning that there is a sudden appearance of tight coupling to the IoC container itself from our consuming classes.  You probably want to try to abstract away the fact that the IoC container exists from the majority of the application.  Factory classes go a fair ways in making this happen, but another good idea is to introduce a single service to do type resolution.  The Factory classes can then ask this service for the object they want, and they never need to know the IoC container is there.  This approach also gives you the ability to create some objects using IoC and others in another (more traditional) way.

So is this it?  Have I finally found the answer I've been looking for?  It's hard to say right now.  For the time being this is a decent way to handle things, provided the complexity of the underlying system, and the need for loose-coupling are both high enough to justify the additional complexity of the IoC.  But who knows, in another couple months I may find something new, or even something old, which seems better, cleaner, simpler.  That, after all, is my final goal....And I need to remind myself of that regularly, lest I become complacent.

posted on Tuesday, October 02, 2007 4:53:13 PM (Eastern Daylight Time, UTC-04:00)  #    Comments [0] Trackback
# Friday, July 13, 2007

I recently decided to take the plunge and get CodeRush and Refactor! Pro (along with DxCore) loaded instead of Resharper.  Now, don't get me wrong, there is a lot I like about Resharper, but overall the performance was becoming an issue.  There were often problems with VS freezing for no particular reason, and then coming back as if nothing was wrong...I swear it was like my IDE had narcolepsy or something.

One of the things I noticed immediately about CodeRush was the fact that there was a single installer, and when I went to run it I was able to install it on all versions of Visual Studio, including the Orcas Beta.  This was nice when compared to Resharper's separate install for vs 2005 and vs 2003.  It also makes me feel good about improvements in the product being available for all versions of the IDE.  One thing that I noticed about R# was that there was some work being done in the VS 2005 version around performance, but that did not seem to trickle down to the VS 2003 version.  I think the big reason for this is the fact that CodeRush and Refactor! are implemented on top of DxCore, which provides a very clean abstraction from the scariness that is the Visual Studio integration layer.

Here are the things I really like about CodeRush/Refactor:

  • The visualizations are stunning!  No, seriously this is some amazing stuff.  Circles, arrows, animations, eye candy yes, but useful eye candy.
  • The Refactoring Live Preview is crazy brilliant.  Mark Miller mentioned this on a DNR episode, and I agree with his comment that the live preview allows you to discover new useful refactorings that may not be completely obvious from the name.
  • Performance is great.  'Nuf said.
  • It works with VB.Net.  Granted I don't use VB.Net, but some of my co-workers do, and occasionally I have to work on VB.Net projects.
  • Dynamic Templates rock.  The fact that I can create a new mnemonic for my type, and then use predefined prefixes and do vee<space> to create a new Employee Entity for example is pure bliss.
  • Template contexts are way cool.  By default they have NUnit templates defined, and with contexts, t<space> creates both a TestFixture class and a Test method
  • Markers and navigation are dreamy.
  • There are some crazy-cool template functions, like the ability to do a foreach within a template, so things like creating a switch/case statement for all items in an enum can be done easily.  This also powers a conditional to case refactoring that is pretty sweet.

Here are the things that I miss from Resharper:

  • Automatically adding a using statement in VS 2003 was sweet.  VS 2005 can do it with the buit-in intellisense features, but I got very used to it.
  • The VS 2003 test runner was very nice.  I use the Testdriven.Net plugin, which I cannot live without, but I like the graphical runner in the IDE.  The free test runner from JetBrains is for VS 2005 only, so it doesn't help those of us in VS 2003.  I do like the fact that they released it as a free tool, though.
  • The "Extract Field" refactoring doesn't exist in Refactor!...This shocked me a lot.
  • The Find Usages task.  This I think is part of the reason why R# was slow, but it did a brilliant job.  I think the rename in R# was more powerful as well.  I think there is a rename in Beta for Refactor! that is supposed to be able to work accross an entire project/solution, but I haven't had a chance to really test it yet.
  • The pre-build error checking is nice.

The good news is that the DxCore extensibility model means that most if not all of these items could be recreated.  The bad news is that there isn't a lot of documentation around the extensibility model, particularly when it comes to creating new refactorings.  The test runner is one of the most painful points for me right now, so I've started exploring the process of creating one using the DxCore APIs.  It opens up the possibility of refining things too, which would be nice.  What I would really like would be the ability to detect and integrate with TestDriven.Net.

The folks over at Eleutian are evidently running both, which they claim is possible with some tweaking, but the performance issues for VS 2003 are the biggest downer on the R# side, so I will probably not go down that path.  I may load up the test runner for VS 2005, unless I get some time to try and build one using DxCore, in which case I'll share it with the rest of the world.

posted on Friday, July 13, 2007 11:00:21 AM (Eastern Daylight Time, UTC-04:00)  #    Comments [0] Trackback
# Monday, June 18, 2007

So if you recall from some of my earlier posts, I've talked about the concept of the "Friend" class in C++ and how it could apply to TDD within .Net.  Well, today, with the help of Roy Osherove, I just stumbled upon the InternalsVisibleToAttribute within .Net 2.0.  This allows you to specify within one assembly, another assembly that should have access to the internal members of your assembly.  This is genius, and goes a long way towards allowing you to keep your code encapsulated, while still being testable.  If we could just get them to go one step farther, and allow for access to private and protected members as well, life would be good, and there would be no more of this OOD vs TOOD junk.

The other interesting thing about this is that it could allow you to give a separate utility...say the Castle Microkernel, access to internal class constructors, and thus enforce creation of your objects through the Kernel from outside assemblies.  This is actually a feature I am desperately wanting in my current project,  but sadly, I am limited to .Net 1.1, so I can't quite get there.

Here is a quick look at how this works.  Here is a very unrealistic class in an assembly that I want to test:

class TestClass
{
    internal TestClass()
    {}

    private bool PrivateMethod()
    {
        return false;
    }

    internal bool SomeMethod()
    {
        return true;
    }

    public string PublicMethod()
    {
        return "You can see me";
    }
}
Now, I add the following to the AssemblyInfo.cs file:
[assembly: InternalsVisibleTo("TestAssembly")]

And here is what Intellisense looks like in my test class

Not bad.  Overall I would say this is defiantly a good feature to have in your toolbox.  Internals are not perfect, but they are much more versatile than a lot of folks give them credit for.  Now if only I could get something like this in .Net 1.1
posted on Monday, June 18, 2007 11:33:09 AM (Eastern Daylight Time, UTC-04:00)  #    Comments [0] Trackback
# Monday, June 11, 2007

The project I'm working on now has a huge need for auto-update.  Strangely enough, there aren't a whole lot of documented solutions for an auto-update application for .Net 1.1.  In the 2.0 world you have ClickOnce, which handles those sorts of things for you (and in a way that isn't terribly difficult to manage as a developer...as long as you pay attention to what your doing), but the only real option you get from MS on this is the AutoUpdater Application Block from the Patterns and Practices guys.  I took a look at this when it was in it's 1.0 version a while back, and really didn't care for it much.  The big reason was that it required you set up an AppStart.exe file, which would take a look at your config file to determine which directory to start the app from.  When updates arrived, they were put in new directories based on versions.  This seemed like a lot of effort, and a lot of overhead.  The good news is that there is now a 2.0 version of the application block, and it looks like it is much more configurable, and has the ability to do inproc updates.

So here is my issue.  I want to change the default downloader (used to retrieve the updated files) from the BITSDownloader that ships with the block to one which will allow me to copy files from a UNC path.  Fortunately, a sample implementation of such a thing exists in the documentation, so there is a starting point.  It is pretty rough around the edges, and isn't testable, so I am working creating a nicer, testable version of the sample downloader.  Here is the problem, though; the dependencies are insane!  And it doesn't look like even mock objects will be able to help.  Initially I found this a little strange since I know that the Patterns and Practices group was headed up by some folks who were heavy into the Agile methodologies.  I also know for a fact that the Enterprise Library components have test included.  So I pulled up the AutoUpdater Application Block to see how they were testing things....and what do you think I found?  They were not testing anything!  I can only assume that the updater block came from another group, because there was no tests in sight.  So, since I had the source code, I'm reduced to making modifications to the block to support testing.  For the most part this involved marking public methods/properties as virtual so that Rhino.Mocks can mock them.  I also added some parameters to the constructor of the UpdateTask class so that I could supply mock versions of some of the dependencies.

I can't imagine trying to test this without the source code to modify...as it stands I don't feel real good about shipping around a non-standard version of the library.  Overall I'm quite disappointed in the P&P folks on this one.  I had high hopes whenever I saw the rest of the Enterprise Library that I would be able to test my extensions fairly easily.  I guess that goes to show that even in organizations (or specifically groups) where TDD is a best practice, it still is finding hurdles to acceptance.

posted on Monday, June 11, 2007 2:53:07 PM (Eastern Daylight Time, UTC-04:00)  #    Comments [0] Trackback
# Monday, June 04, 2007

Thinking about my earlier post discussing the OOP vs TOOP problem, I mentioned at the end that the best solution to this problem in my mind would be integrated language support for test classes.  Specifically, a way to let the Compiler/Runtime know that a specific class is a test class, and should therefore be able to access any and every property of a class.

It occurred to me that such blatant intrusion into the privacy of a class is not unknown in the programming world.  C++ has the notion of a "Friend" class.  This is a class that can access all members of another class regardless of their protection level.  To keep things civil, so that just any class can't declare itself to be a Friend of any class it wants, the class that the Friend class would be accessing would declare specifically that classes X, Y and Z are fiends, and so can have free reign.  Granted this is considered to be rather scary, and one of those features that makes C++ an ideal tool for shooting ones own foot off.

But, this concept has some merit within the context of Test classes.  In the .Net world we could potentially use attributes on a class to identify what the test class (or classes I suppose) for a class are.  The compiler and runtime could then use that information to provide unlimited access only to the classes listed in the test class list.  For more protection perhaps it would also validate that the classes in the list also have the appropriate attribute (TestFixture in NUnit, TestClass in TFS) before allowing access.  You would need some additional tooling in the development environment so that you would get Intellisense on all of the private/protected members, but that should be easy for the MS guys after building in the test support, right?

There is some additional danger in this approach since there is some potential to modify IL at runtime, but couldn't there be additional protections around such things?  As someone with no knowledge of the internal workings of the CLR, I can't say for sure, but its worth trying.

So, I know officially propose to Microsoft that this feature be added to the 4.0 version of the framework.

Do you think they heard me?

posted on Monday, June 04, 2007 10:21:47 AM (Eastern Daylight Time, UTC-04:00)  #    Comments [0] Trackback
# Tuesday, May 29, 2007

I have officially crossed over....I am now using Mock Objects in my tests and loving it.  After much humming and hawing, and trying to figure out how to write truly effective tests, I decided to give it a go, and so grabbed a copy of Rhino Mocks and started the grueling task of converting some data access code so that I no longer needed a database to run the tests.  It took a little bit to get my mind around the new way of thinking, but I have to say it worked great.  I'm now able to test my data access routines with complete success, and about a 95% code coverage rate.  This is all on top of the fact that I'm using Enterprise Library (for 1.1) for data access and exception handling.

Now, there is a very interesting article from Martin Fowler which is called simply "Mocks aren't Stubs".  In this article he is discussing two approaches for dealing with the sort of problem that I had with my data access code.  One is to create object stubs within your tests that you can use to feed known values back to your tests.  This is not at all a bad approach, and I am using it in some cases in conjunction with my mock objects.  The other approach is to use Mock Objects for all of the tricky stuff.  He observed an interesting dichotomy between the sort of TDD folks who follow each approach:  The folks that use stubs tend to be very results oriented in their testing...That is they are verifying the values of various object after performing an action using the test frameworks Assert calls.  This, I think, is most in line with the way TDD is supposed to work.  For the Mock Object folks, though, another thing starts to happen.  These test gain the ability to verify that specific methods are called in a specific order, and therefore the tests that come from this approach start becoming less results-oriented, and rely more on the method verification from the Mocking framework.  He points out these two styles of testing without really saying one is better than the other (he does indicate that he tends to be in the Stub camp, but I think that is a personal choice and level of comfort thing), beyond pointing out that relying on the results of the test tends to be more in line with the pure TDD way of doing things.

Now, I had read this article before I started using mocks within my project.  I thought about using stubs throughout, but since I was testing data access code, I would have a lot of methods to implement in my stub objects that wouldn't really be part of what I was testing, so it seemed a large waste of my time.  As I started implementing mocks in the tests, I paid attention to how I was testing to see if I was becoming a "Mockist" in the Fowler sense.  Overall I would say that I am not, currently, a "Mockist".  I'm still overwhelmingly validating the results of calls based on the methods I'm testing, and just using the mocks to feed appropriate values into the classes I'm trying to test.  As a matter of fact, I could probably remove the call to _mocks.VerifyAll() at the end of my tests, since I don't really care.  I can say, though, that the ability to verify what is being called with what arguments has been extremely useful in my data access testing space.  I've basically got objects which are making calls to stored procs on Oracle to do my data work. The DAL is a real simple deal that doesn't have much in the way of smarts, but works well enough for a small project.  Because of the fact that I'm making stored proc calls to the database, I can now use the mocks to make sure that when I call the Save() method on my User object (for example), It's calling ExecuteNonQuery() with the proc name of SAVE_USER.  I can also verify that all of the input an output parameters are being set correctly, which is a big consideration when adding a property to the data objects.  In that way I can know that my Save() method is doing what it is supposed to even though it returns no value.  This checking could probably be done by stubbing the EnterpriseLibrary Database and DBCommand objects, and then setting values within my stub object, which I could verify using an Assert call, but that seems like an awful lot of work when I have the option to simply set expectations, and then do a VerifyAll().

I think the Fowler article may be making much of a practice which is not that common among people using mocks in TDD.  Or maybe there is a slow creep that happens to the developer after months and years of using mocks in their tests that turn them into Mockists.  Personally I find that there is a very broad and comfortable middle ground which allows me more flexibility to express my intent quickly and concisely.  And after all, expressing intent is one of the major boons of TDD.

posted on Tuesday, May 29, 2007 11:45:50 AM (Eastern Daylight Time, UTC-04:00)  #    Comments [0] Trackback
# Tuesday, January 16, 2007
I've been reading the "Framework Design Guidelines: Conventions, Idioms, and Patterns for Reusable .NET Libraries" book recently, and I came across a section discussing interface design, which had direct bearing on one of my earlier posts regarding programmer intent.  They basically state flat out that you should never use marker interfaces in .Net.  Instead, you should favor custom attributes, and then test the type for that attribute.  This was interesting to me, since I have been trying to determine what, if any, value marker interfaces would have in .Net.  In the Java example I cited, one of the benefits was that the JavaDoc information associated with the interface would then be attached to the class, so you would have clear intent from the developer when the interfaces were used.  .Net documentation comments don't carry that same direct association...granted, when the documentation is generated, most of the time there will be a link to the interface definition..but it's not quite the same.  On the other hand, generally a custom attribute will not even provide that link, so from a doc standpoint there is less information available. 

I think, though, that it is a bit more important to have the information about developer intent available while reviewing the source code, which makes the custom attribute concept a really good option.  You could even conceivably create a utility which would grab the attribute information from the assembly meta-data and generate a report containing which classes were marked with which interfaces, and therefore, which classes were part of which patterns.  There would also be the ability to associate other information with the attribute, such as a description, so you could have an attribute which stated a class was part of a specific patter (say, Chain of Responsibility), and then give a description of the component.  With that you could see specific instances of Chain of Responsibility patterns within the code.  Attributes also follow inheritance hierarchy, so that could make things more confusing, depending on how the attribute was used on the more top-level classes.


powered by performancing firefox

posted on Tuesday, January 16, 2007 12:15:01 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0] Trackback
# Tuesday, January 02, 2007
I was listening to the ArCast recorded with Scott Hanselman earlier today, and he was talking about the idea that Non-Software artifacts should approach zero.  If you've seen some of his posts, or listened to some Hanselminutes podcasts, you have no doubt come across this idea before.  I like this particular phrasing mostly because it gets to the heart of what I think one of the most often overlooked aspect of the programming process is; Namely, the intent of the programmer.

I think this is one of the most important things to take into consideration when looking at someone else's code (or even your code, more that about a week after you wrote it).  There are a lot of subtleties about a design which go away after the code is written and starts to gather dust.  If the developer had a particular design pattern in mind when they built a class structure, this information exists only in the mind of the developer, and maybe some technical spec doc which is lost in source control, or share point somewhere.  Someone else comming along may look at that class structure, and not see the scaffolding the original developer put there to support that pattern, and will most likely simplify the design, removing the pattern in the process.

One proposed solution to this, which I saw in a posting from a java developer was to use marker interfaces to communicate this sort of intent.  That is, an interface which actually has no method declarations, but exists only to mark a specific class as being part of a pattern.  One additional advantage that the Java-Doc system allowed was the addition of the documentation around that interface into the docs generated for the implementing class.  This is not a bad idea, though it is terribly hard to enforce.

I think Windows Workflow will be a major contributor in this arena, allowing very explicit declarative syntax for creating code.  There may even be some potential to building WF activities around design patterns (hmmm...maybe I have a project).  This idea ties into all sorts of other areas of development, though. When designing web services the contract is what is used to communicate the developer intent, and therefore creating super methods that take DataSets or XML Blobs makes the contract basically useless.  .Net attribute-oriented programming also allows for this sort of thing, though I can't see it being flexible enough to serve as a declarative language extension (yet). 

Once again I think we have no choice but to look at Unit Tests as the single most effective way to communicate developer intent.  If the tests are named properly, and test coverage is high enough, we should be able to see all of the requirements, how the various components interact, and generally what the developer was thinking.  I've even written tests which assert a particular class implements an interface simply because I though that was a critical part of the design.

What is my point?  Well, I guess its really just the beginning of a though process around how to better capture programmer intent.  What tools should there be?  We all know documentation doesn't work.  Unless your doing Model Driven Development, UML is usually as out of whack with the software as the documentation (or worse).  And I think everyone agrees that putting this information in a word document is the best way to ensure it does not end up in the final product.


powered by performancing firefox

posted on Tuesday, January 02, 2007 11:48:24 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0] Trackback
# Wednesday, December 27, 2006
Okay, I admit it, this is a rant....But I promised myself I would post more, so you have to take what you can...

So here's the deal, I've been peripherally involved in a project at my current client, to the point that I know generally where things are going, but I haven't done any code review or anything like that.  The good news is that the developer working on it is fairly sharp, so I had no major worries....The fun comes when this developer (who is a contractor like myself), decides to take a offer for another gig (for way more $$, so who can really blame him).  Left in his wake is a new developer, who is trying to figure out the business as well as the code, which is not a fun thing to do, a stack of code, and deadlines which are not moving.  What is not left is any sort of design artifact on the code side.  There were some data changes, which have detailed ERDs, but nothing on the code side.  In looking at the code, it seems reasonably well put-together, though there is way more tight-coupling than I generally like to see, and a much deeper object hierarchy than I generally like to work with.

Now allow me to wonder into dream-land for a bit...This is a situation where TDD would pay off big-time.  For starters, it would be more likely that the code that was left would be leaner than it currently is had this project been a TDD project.  Also there would be the wealth of code artifacts that the tests provide.  At a glance I could see which components are supposed to do what, and (assuming the test writer thought this way) why certain components where there.  Then there is the safety net for the massive refactoring that every developer does when they inherit new code (you know, the guy who wrote it originally was an idiot...I never would have done it this way...that doesn't make any sense...).

This is making me start thinking about mandating a TDD approach, or at least if not mandating, fostering.  What is the best way to do that, though?  Everybody knows that developers don't take kindly to being forced to do anything, particularly when they see it as making their jobs more difficult.  And lets face it, the sorts of tests that you get from someone who doesn't "get" TDD are things like "Test1", "Test2"..."Test132".  What use is that?  So my challenge is to try to figure out how to introduce a concept like TDD into an organization which really has no other standards (there hasn't even been a decision regarding C# vs VB.Net), and where developers have not used TDD before.  The biggest problem with TDD initially, is that developers feel stifled.  Everyone is taught to think ahead, and try to create something that is resilient to change.  TDD throws that idea out the window, and it is damn hard to break that sort of thinking.  Particularly when your trying to baby-step your way through functionality like properties, that have to be put together in a particular way, and should have tests associated with them.  Why would any rational developer spend the extra 10 minutes to write CanSetCustomerName CanGetCustomerName tests when they can implement the properties and move on?  I think the only way to do it is to figure out some way of showing first-hand where the benefits lie.  Yes, I find writing tests for my accessors a bit redundant, but I take a great deal of satisfaction at the end in the information that I have managed to communicate about the code once it is done.  If I have a get test and a set test for a property, then it is pretty obvious I wanted both.  If I only have a get test, but a I defined a setter, then I know I can get rid of it.  There is also the knowledge that those small things are what the larger body of the tests are built on, and I think they provide a good way to ease into creating a new class in a TDD style.  While your writing those get and set tests you have time to think about the classes public API, and you can start to alter it a lot easier.

But back to the thoughts around introducing TDD....It is hard to show the added agility, unless you are actively changing an existing project.  The Code Artifacts are apparent, but a bit muddled and confusing.  The confidence that a full test suite provides is also a bit hard to communicate, particularly to a skeptical audience.  This is not an easy problem.  I think on one level it is easy to talk to developers and tell them why this is a good thing (Scott Hanselman did an excellent job on his TDD podcast), but experience shows that when the pressure to deliver starts cranking up, most developers return to their old habits to "deliver the project on time", regardless of the amount of time that may be lost down the road because it was not possible to do ruthless refactoring.  It is also dangerous to try to introduce TDD on a critical project....if for some reason it fails, or is delayed, there is likely to be some serious push-back from management to TDD adoption.

It's not an easy problem....but I think I need to figure it out.  I think there would be serious benefits to adopting TDD, especially in my current situation with developers coming and going.  I'll just need to figure out how to share the enthusiasm, and convince others that there really is no other way to develop software.


powered by performancing firefox

posted on Wednesday, December 27, 2006 11:25:37 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0] Trackback
# Thursday, June 15, 2006

   It looks like, to help avoid confusion, and questions from developers, Microsoft is renaming WinFx to the .Net Framework 3.0.  Evedently people were under the impression that WinFX was a seperate entity.

Here's the post:
http://blogs.msdn.com/somasegar/archive/2006/06/09/624300.aspx

posted on Thursday, June 15, 2006 1:11:21 PM (Eastern Daylight Time, UTC-04:00)  #    Comments [0] Trackback
# Wednesday, May 31, 2006
I just learned that Microsoft changed the way unhandled exceptions in Threads are propogated in .Net 2.0 vs the way they worked in 1.1.  With 2.0 any unhandled exceptions in a thread will not only cause that thread to exit, but will also be bubbled up to the thread that started the offending thread.  Overall, I think this is a good thing, since not only will it force people to handle exceptions within their thread code, but it will also eliminate the problem of processes mysteriously stopping if there is an unhandled exception on a thread.  It will, however, cause some serious grief for any developers not expecting that sort of behavior.  I'm sure I'm not the only one who has seen less than steller multi-threaded programming tactics in applications which should be better behaived (heck, I've done my share of shoddy thread handling in the past).

The one exception to this, of course, is the ThreadAbortException, which understandably, only effects the thread it is raised on.  Granted using Thread.Abort, or raising a ThreadAbortException is considered a brute-force approach, so it shouldn't be happening anyway....
posted on Wednesday, May 31, 2006 11:47:26 AM (Eastern Daylight Time, UTC-04:00)  #    Comments [0] Trackback
# Wednesday, May 24, 2006
It just goes to show that there are always little surprises waiting around the corner.  I've been looking at least casually at .Net 2.0 since Beta 2, and I even read through the "What's New" for C# 2.0 to see if I missed anything.  Somehow I managed not to notice Implicit Delegate Assignment (or at least that's what I'm calling it).

It is now possible to assign a delegate using just the Class and Method name...you no longer have to create a new instance of the delegate type.  Not a huge thing, I know, but for those of us who are easily impressed it's, well, impressive.

Here's the skinny in code language:

public class SomeClass
{
    public event EventHandler MyEvent;
}

public class SomeOtherClass
{
    SomeClass _class; 
    public SomeOtherClass()
    {
        _class = new SomeClass();   
        // Old Way
        _class.MyEvent += new EventHandler(this.MyHandler);
        
       // New Way
       _class.MyEvent += this.MyHandler;
    }

    public void EventHandler(object sender, EventArgs args)
    {
        // Handler Code
    }
}
posted on Wednesday, May 24, 2006 12:30:23 PM (Eastern Daylight Time, UTC-04:00)  #    Comments [0] Trackback