Wednesday, May 20, 2009

Speaking at CodeStock 2009

This year CodeStock is shaping up to be a conference like no other. Most regional conferences have around 25 sessions with some attempt to do Open Spaces on the side. CodeStock 2009 will certainly blow the doors off the norm with a community driven event with something to offer for everyone. To start with, it is the first conference that I know of that allowed the early registering attendees to choose the direction for the more than 50 hour-long sessions as well as 6 extended hands-on sessions. Then, to kick it up one more notch, Alan Stevens will be facilitating the Open Spaces. Make no mistake: Alan knows how to do Open Spaces right. Last year’s CodeStock was the moment the community took notice of the way that Alan’s particular talent set meshes with coordinating an exceptionally effective Open Space event. This is truly an event that has something to offer everyone.

Given the community selection process, it is even more of an honor to be selected to speak at this event. I will be giving the PatternsInTesting presentation that has already been well received in the Midwest area.

Indy Code Camp 2009

I was privileged to be able to give the PatternsInTesting presentation at Indy Code Camp this year. There were many really good testing related conversations before and after the presentation. I am encouraged by the amount of interest the community is taking towards improving the adoption of test driven design. I also got to see a few top notch presentations:

  • Tim Wingfield - Care About Your Craft: A very motivating presentation on doing the right thing
  • Philip Japikse - CRUD Sucks! NHibernate to the rescue: Phil has an impressive in depth knowledge of NHibernate. I was most fascinated by all of the extensions that he has written to really make NHibernate hum.
  • Jon Fuller - Dealing with Dependencies: This was my favorite presentation of the day. Jon had only enough slides for an overview and went directly in to writing code. It was an in depth, working look at using DI tools.
  • Michael Eaton - Developing Solid WPF Applications: A very informative view into a real world WPF application and its development evolution

Greater Lansing .net User Group

A big thank you to GLUGnet for letting me do the PatternsInTesting presentation for the group. This is a group that I frequently attend, it is nice to be able to present on a topic that I talk about so much with the members of that group.

Wednesday, May 20, 2009 9:38:30 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0]  |  Trackback
Tuesday, May 19, 2009

Your mission, should you choose to accept it, is to observe the interaction with an object and verify that this interaction is in your best interest.

The Scenario

Some objects that you have to consume are just poorly written. The ones that are most egregious always seem to be the ones you have no control over. That lack of control may be because you have no access to the source, it may be because it would be a political minefield to change the source, or a lack of tests makes the team afraid to change the source. It seems like every time I go to a new client, these objects exist (as well as the political minefields). The developers have a mysterious set of incantations that they have memorized for interaction with these objects in order to avoid bugs. Often, no one knows where these "rules" came from and they are usually not written down.

The Vocabulary

The name of this pattern is the Spy. What the spy will do is capture information about interaction with an object, and only take action if the need arises. A spy object looks just like the object that you need to interact with (i.e. implements the same public interface) such that your code should not even notice it is even there, but, behind the scenes it will perform validation and give the useful feedback you wish the original object would have implemented in the first place. This spy or validation wrapper is commonly implemented by holding on to a reference to original object. This allows for the spy to call the actual implementation in order to preserve the original behavior.

The ideal world

In an ideal world, the kinds of interactions that you are trying to validate with a spy should be captured be captured by the actual object you are interacting with, rather than the spy. Having a wrapper object whose function is validation is a massive code smell. If you have the ability to fix the original code by adding the relevant validation, that is by far a better solution than creating a spy object.

The real world

In reality, you do not have access to change the source of third party libraries, even if sometimes that third party is a couple of buildings or even cubes away. The first thing you should do when you run in to these bizarre incantations “required” for successful object interaction, is to ask “why?” and be persistent, dig deep. You may be (not so) surprised that most of the reasons have long since gone away. If you do find that some of the hidden rules are indeed valid, you need a way to validate that your code is following the rules.

Example

Consider the following example where MethodToObserve will throw an uninformitive exception if the PropertyToObserve has not yet been set.

    1 public interface IInterfaceToUse

    2 {

    3     void MethodToObserve();

    4     List<string> PropertyToObserve { get; set; }

    5 }

    6 

    7 public class ClassToUse : IInterfaceToUse

    8 {

    9     public void MethodToObserve()

   10     {

   11         PropertyToObserve.ForEach(str =>

   12                  Console.WriteLine("Calling the MethodToObserve:" + str) );

   13     }

   14 

   15     private List<string> propertyToObserve;

   16     public List<string> PropertyToObserve

   17     {

   18         get

   19         {

   20             Console.WriteLine( "Calling the PropertyToObserve setter");

   21             return propertyToObserve;

   22         }

   23         set

   24         {

   25             Console.WriteLine("Calling the PropertyToObserve getter");

   26             propertyToObserve = value;

   27         }

   28     }

   29 }

As mentioned previously, the ideal solution is to fix the implementation. If your only access to this code is Reflector or you are just not authorized to change it, the next best thing is to protect yourself (flaming email to the author of the code is,of course, optional). Our protection, or at least better information will come from a class implementing IInterfaceToUse just like the original, only this time the implementation will provide the consumer with information that they can act on.

    1 public class ValidatingObserver : IInterfaceToUse

    2 {

    3     private IInterfaceToUse _observedClass;

    4 

    5     public ValidatingObserver(IInterfaceToUse observedClass)

    6     { _observedClass = observedClass; }

    7 

    8     public void MethodToObserve()

    9     {

   10         if (PropertyToObserve == null)

   11             throw new ArgumentNullException("PropertyToObserve",

   12                                             "Property must be set prior to calling Method");

   13         // perform observations

   14         Console.WriteLine("The spy is watching: MethodToObserve");

   15 

   16         // pass through to implementing object

   17         _observedClass.MethodToObserve();

   18     }

   19 

   20     public List<string> PropertyToObserve

   21     {

   22         get

   23         {

   24             Console.WriteLine("The spy is watching: PropertyToObserve getter");

   25             return _observedClass.PropertyToObserve;

   26         }

   27         set

   28         {

   29             Console.WriteLine("The spy is watching: PropertyToObserve setter");

   30             _observedClass.PropertyToObserve = value;

   31         }

   32     }

   33 }

Note that this time, instead of the “oops, I forgot something exception” known in .net as the “Object reference not set to instance of an object” exception, we get meaningful information about what is missing and even some hint as to how to fix it. The error now clearly states that the PropertyToObserve should be set prior to calling the MethodToObserve.

Using the spy

There are many ways to create a spy object, I chose containment for this post; You may also use derivation to create your wrapper. Derivation will get you up and running faster, and you will not have maintenance work to do if you add a method to the interface, but this will come at a cost. Containment will allow you to swap out the actual implementation of the object with a mock implementation at some time in the future. As always consider you needs before choosing a spy implementation.

The test below shows how to use the spy created in this post

    1 [TestFixture]

    2 class ManualObserverTests

    3 {

    4     [Test]

    5     public void MethodCallSpy()

    6     {

    7         var observedClass = new ClassToUse();

    8         var validatingObserver = new ValidatingObserver(observedClass);

    9 

   10         Assert.Throws<ArgumentNullException>( validatingObserver.MethodToObserve);

   11     }

   12 }

Tool Support

All of the previous posts in this series have mentioned leveraging tools to assist in creating these test objects. They spy object however is a strange beast; the demands it places on the tools turn out to create as much code as the manually coded version. If you are so inclined, you can use Rhino for a spy object. What is required is taking advantage of the Do extension method. Do takes a delegate as a parameter that matches the signature of the method being called. So what you will end up establishing is an Expectation that a method will be called and when it is Do the operation specified by the delegate.

Summary

The spy object reminds me of the Broken Windows section of the Pragmatic Programmer. It clearly states not to live with broken windows, but if you cannot fix the window, at least put a board over the window. In the case of third party code where you cannot change the source code, a validation wrapper is the board you need to keep further damage from occurring and show other developers in the area that you still care about the quality of code.

The Series

PatternsInTesting[2] - Stub Pattern PatternsInTesting[4] - Mock Pattern
Tuesday, May 19, 2009 9:49:32 AM (Eastern Standard Time, UTC-05:00)  #    Comments [1]  |  Trackback
Thursday, March 19, 2009

revolution_3I love my MX Revolution mouse. It is the most comfortable mouse I have used to date. For me, this is the first mouse that the wireless works without glitches, the scroll wheel has virtually no resistance, and there are a pile of programmable features on well placed buttons. As a desktop mouse, I would suggest anyone give it a try.

As a presentation mouse, however, it did not work so well. The scroll wheel with no resistance would scroll under its own weight causing my slides to advance and back up in a very rapid fashion. This is a great example of a highly desired feature in one context being a complete hindrance in another. Now off I go to  find a device well suited for presentations.

Thursday, March 19, 2009 6:20:16 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0]  |  Trackback
Monday, March 16, 2009
I will be presenting items from the PatternsInTesting series as well as some additional content in the Test Driven is Driving me Insane talk at the Great Lakes .net User Group on 3/18/2009 and at the Northwest Ohio .net User Group on 4/21/2009. This has been a really fun talk so far and I have enjoyed the conversation it generates. Stop by if you can make it.

Monday, March 16, 2009 12:48:40 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0]  |  Trackback
Thursday, March 12, 2009

I will be presenting items from the PatternsInTesting series at the Greater Lansing .net User Group Flint meeting. I was compelled to put this blog series and presentation together to address the pain many organization experience when trying to include automated testing into their development process. The content is based on the insight and lessons learned that I have picked up by experiencing the same transition in multiple organizations. Participants in this presentation will walk away with tools for writing more effective tests and how to better identify issues in tests.

Thursday, March 12, 2009 8:15:15 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0]  |  Trackback
Wednesday, December 10, 2008

The Scenario

On our continuing quest to create unit tests that exercise only the class under test, we look at another common scenario that occurs while writing tests. As with the Dummy, our class under test has a dependency on another class, only this time the dependent class has an active role in our test. Our testing needs are about the logic of the class under test and not the interaction with the dependent object. In order to create a good test, the class under test must be isolated from the dependent object.

An example of this scenario might look like this:

   11     public interface ICalculator

   12     {

   13         int Add(int left, int right);

   14     }

   15     public class Fib

   16     {

   17         private ICalculator _calculator;

   18         public ICalculator Calculator

   19         {

   20             get { return _calculator; }

   21             set { _calculator = value;    }

   22         }

   23 

   24         public int Next(int i, int j)

   25         { return Calculator.Add(i,j); }

   26     }

The class under test in this scenario is Fib, which has a dependency on an ICalculator. The test's objective is to validate that the Next method returns the correct result for some well-known examples.

The Vocabulary

The name of this pattern is the Stub. A stub stands in the place of the actual object in use and provides known answers and predictable behavior. If you are doing any sort of evolutionary development, chances are that the initial versions of your classes more resemble stubs then real code. Why? The goal is the same: you wrote stub functionality to allow you to focus your development efforts on different parts of the system. This is exactly what we are doing with Stub tests: isolate one part of the system from another by providing known results.

The solution without tools

Unlike with a Dummy, providing a class that throws a NotImplementedExcpetion in the Add method does not meet our needs. Since the functionality of ICalculator is outside the scope of this test, we assume that it is working correctly (and hopefully under test). A simplistic implementation of ICalculator will work nicely. Since we are not testing the calculator, provide a simplistic calculator that returns fixed results.

   38     [Test]

   39     public void NextResultIsCorrect()

   40     {

   41         Fib fib = new Fib();

   42         fib.Calculator = new StubCalculator();

   43 

   44         Assert.That(fib.Next(2, 3), Is.EqualTo(5));

   45     }

 

   29     public class StubCalculator : ICalculator

   30     {

   31         public int Add(int left, int right)

   32         { return 5; }

   33     }

The test will check that the Next method returns the correct result given the StubCalculator. What we end up doing here is fully exercising the Fib class with known values from its dependent classes. The stub gives us the proper level of isolation for this test.

The solution with Rhino Mocks

For this version, leverage Rhino Mocks to keep us from having to code physical versions of the Stub class. Using Rhino's Fluent Interface, this reads as Expect a call on Calculator with the parameters 2 and 3, and when making this call return 5 as a result.

   47     [Test]

   48     public void NextNumberIsCorrect()

   49     {

   50         Fib fib = new Fib();

   51         fib.Calculator = MockRepository.GenerateStub<ICalculator>();

   52         fib.Calculator.Expect(calc => calc.Add(2, 3)).Return(5);

   53 

   54         Assert.That(fib.Next(2, 3), Is.EqualTo(5));

   55     }

The tools advantage

Just as discussed with IComplicated in the Dummy sample, adding methods to ICalculator does not require any additional maintenance of this test. However, unlike the Dummy sample, calls into the stub return the expected value. Additional benefits can easily pile up. Consider adding multiple calls to Add with different parameters. The hand-coded version would need some sort of conditional logic to determine what to return based on the calling parameters. Complexity adds up fast, even in the simple example listed here. Using Rhino, one concise and readable line of code can use new parameters for an additional expectation, including the expected result, and Rhino deals with matching up the parameters with the correct result. This is just a glimpse into the functionality offered by Rhino; the upcoming patterns will cover even more capability.

Isolation effects

Should a test that checks the result of the Next method fail if there is something wrong with the ICalculator implementation? The answer, as always, is "it depends." This test should fail if we were writing an integration test—a test that ensures all the pieces of a system are working together. This test should not fail based on ICalculator if it is a unit test, focused only on the result of Next. Isolating ICalculator from Fib helps build a set of unit tests that can quickly identify the location of errors introduced into a system. The stub is a common pattern of isolation, and using it will make a marked and immediate improvement in your tests.

The Series

PatternsInTesting[4] - Mock Pattern
Wednesday, December 10, 2008 5:49:06 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0]  |  Trackback
Thursday, December 04, 2008

The Scenario

One of the characteristics of a good unit test is that the object under test is the only object being exercised. The problem in this scenario is that the object under test requires a dependent object, even though the functionality of the dependent object is not used in the test. To make a good test, the dependent object needs to be isolated from the class under test.

An example of this scenario might look like this:

    8     public interface IAmComplicated

    9     { void DoStuff(); }

   10 

   11     public class ClassUnderTest

   12     {

   13         private IAmComplicated complicated;

   14         public double circumference;

   15         public double radius;

   16         public ClassUnderTest(IAmComplicated externalComplicated)

   17         {

   18             if( externalComplicated == null )

   19                 throw new ArgumentNullException("complicated is required");

   20             complicated = externalComplicated;

   21         }

   22         public double DoInternalStuff()

   23         {

   24             return circumference/(2*radius);

   25         }

   26     }

The dependency in ClassUnderTest is that its constructor requires an instance of an object that implements IAmComplicated. The rather simple objective of this test is to validate that DoInternalStuff returns Pi within a reasonable amount of rounding error.

The Vocabulary

The name of this pattern is the Dummy. It is unclear to me whether this is a reference to the object that enables isolation for the test or a reference to the original author of the code. It seems to be a code smell for this scenario to even occur. However, sometimes you need to use an external library and do not have liberty of changing the code.

The solution without tools

Using only Visual Studio, add a class that implements IAmComplicated, right-click on it, and choose implement interface. Every method in the class will throw a NotImplementedException. This class meets the needs of the test because none of the methods are ever called; its only purpose is existence.This is your Dummy.

    1     public class ComplicatedDummy : IAmComplicated

    2     {

    3         public void DoStuff()

    4         {

    5             throw new NotImplementedException();

    6         }

    7     }

This Dummy class allows us to create the following test:

   39     [Test]

   40     public void DoStuffValidates()

   41     {

   42         ClassUnderTest cut = new ClassUnderTest(new ComplicatedDummy());

   43         cut.circumference = 314;

   44         cut.radius = 50;

   45         Assert.AreEqual(Math.PI, cut.DoInternalStuff(), 0.01d);

   46     }

The solution with Rhino Mocks

Rhino Mocks has the capability to create an object at runtime by reflecting the IAmComplicated interface. This gives us the capability we need without having to maintain another class in the test project. Since Rhino is reflecting the interface at runtime, adding a method to the interface at a later date does not require changes to the test code. There are several different ways Rhino could give us a placeholder for IAmComplicated. Here we will use a simple one line call to GenerateStub.

   55     MockRepository.GenerateStub<IAmComplicated>();

This one line saves us an entire file of maintenance, and our test only requires minor modification to use this technique. Place the call to Rhino as the parameter to the ClassUnderTest constructor instead of creating a new ComplicatedDummy.

   52         [Test]

   53         public void DoStuffValidates()       {

   55             ClassUnderTest cut = new ClassUnderTest(MockRepository.GenerateStub<IAmComplicated>());

   56             cut.circumference = 314;

   57             cut.radius = 50;

   58             Assert.AreEqual(Math.PI, cut.DoInternalStuff(), 0.01d);

   59         }      

Isolation of Failure

One of the primary goals of good unit tests is to identify exactly which unit caused the error. By applying this pattern, tests that cover ClassUnderTest no longer require an implementation of IAmComplicated to instantiate without failure. This helps shorten your bug hunting cycle by reducing the areas that indicate error to where the real error occurred. As you attain higher levels of isolation and better definition of units, you will find you spend much less time in the debugger. This means spending less time finding problems more time fixing them.

The Series

PatternsInTesting[2] - Stub Pattern PatternsInTesting[4] - Mock Pattern
Thursday, December 04, 2008 5:01:09 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0]  |  Trackback
Wednesday, December 03, 2008

It does not matter if your test philosophy is Test Driven Development, Test Eventually Development, or I write tests occasionally. Very early in your testing experience, you will want to start isolating portions of your application or libraries. Without this isolation, you will start seeing a fragile set of tests that make it challenging to track down the point of failure. In order to reach the level of isolation that your tests need, you will need to introduce Mocks (or Test Doubles) to your testing toolbox.

The Testing Story

Someone on your team (extra geek cred if it was you) brings the concept of adding tests to the development process. No doubt there is some confusion at first. What are tests? How do we write them? This phase quickly passes as the team finds things that they understand how to test. This initial period of enlightenment yields great results. Everyone is happy that code is doing what it should be doing. Occasionally, the team celebrates when a broken test flags an unintended change. Clearly development will never be the same again.

As time goes on and the test library gets larger, you start to notice that a breaking change often causes quite a few tests to fail. The team finds this annoying, but decides having tests is better than developer life before tests. At some point though, the tests start to feel burdensome. Adding simple changes start to propagate through the whole system of tests. Discouragement and discontentment set in, and some of your team members want to abandon developing with tests.

Enter Mocks

At this point, the prominent options are to ignore the tests (the blue pill) or find a way to make the tests better (the red pill). This series will cover some of the test development patterns used to isolate areas of your code in the hopes that you will choose the red pill. The goal for the initial four or five posts will be to cover the types of scenarios that occur in test code and what common solutions look like. After that, I hope to cover some of the patterns for dealing with legacy code as I am currently reading through Working Effectively with Legacy Code and it seems relevant to the client I am working with.

The Mock Controversy

There has been considerable conversation in the community about the usage of the term mock. Some prominent members of the development community have been pushing for changing the vocabulary to test doubles, where mock, stub, fake and spy are a particular type of test doubles. My take on this is that these test double types are each describing the scenario where it is useful and the technique for solving the problem; this is describing a pattern. Good names are the key to effective patterns, and we have a good set of names for pattern description. It really does not matter what you call the concept (mocking | doubling | faking | test doubles) if the pattern names describe the scenario effectively.

What's next?

This Series of posts will explore these test double patterns and decompose a few alternate implementations.

The Series

PatternsInTesting[4] - Mock Pattern
Wednesday, December 03, 2008 10:05:47 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0]  |  Trackback
Sunday, November 16, 2008

In my last post, I mentioned the new ValuesAttribute that can be used as a test factory to generate a series of tests with many permutations of parameters. Looking into that feature led me to look at the feature set in NUnit 2.5 which is currently in Alpha 4. Some of these features address scenarios that I have run into in my test code. I wanted to mention them here so others could start benefiting as well.

The source of the new feature set that I am pulling from is the current release notes.

Movin' on up

One of the items that I think is most important is not a new feature, just a change in location. The change in mind set is what stands out as important to me. The Is, Has, Text, and List constraints have been moved into the NUnit.Framework namespace. They were formerly off in the more obscure NUnit.Framework.SyntaxHelpers namespace. The assertions that are created using these constraints line up much better with BDD and have a more readable feel to them. I am happy to see them becoming part of the mainstream namespace. If you are not familiar with the constraint model, check out code below.

// Classic model
Assert.AreEqual(expected, actual);
// Constraint model
Assert.That(actual, Is.EqualTo(expected));

I think the second reads much more like the English phrase that the constraint would represent. Check out the docs; you will find that almost everything you can do with the "classic" model can also be done in the constraint model.

Chained Setup and TearDown

Test code should be crafted with the same level of care as production intent code. This means that it should be DRY and carefully designed. Many times you will be testing a related set of classes, leading to base classes in your test code. Don't be afraid to capture common test code functionality in base classes. Prior to this release, the Setup and TearDown attributes could be applied in your base class, but if you applied the Setup or Teardown attributes in your derived class, the calls were not chained. You had to remember to call the base class version from the derived class. In 2.5, the base Setup method will be call prior to the derived Setup method by the framework. One more win for automation versus developer discipline.

New constraints

Chris Marinos recently blogged about disliking the [ExpectedException] style of tests and wrote a helper class to support the syntax of Throws.Exception. As of the 2.5 release Throws.Exception is included. This allows for much more focused testing. Putting the ExpectedExceptionAttribute on a method simply says that somewhere in the method the exception will get thrown. The exception may well be thrown 2 lines prior to the call you were intending to test. This yields a false positive test result. Throws.Exception (and its set of related Throws) takes a delegate so that you can check a specific call for the presence of an exception.

[Test]
[ExpectedException]
public void PassesButShouldnt()
{
    int importantPreWork = int.Parse("abcd");
    DoStuff();
}

[Test]
public void FailsProperly()
{
    int importantPreWork = int.Parse("abcd"); 
    Assert.Throws<Exception>( DoStuff );
}
public void DoStuff()
{ throw new Exception("Something is terribly wrong"); }

In the example, the PassesButShouldnt test passes due to the expected exception being thrown on the Parse call. Unfortunately, the test was intended to ensure that DoBadStuff threw an exception. The FailsProperly test more accurately checks that only the DoBadStuff call throws an exception. In addition, it also reads better as it places the constraint on the same line as the call just like any other Assert method.

Attribute testing

With the Has.Attribute constraint, you can verify an object (yes, object not class) is decorated with an attribute. A common example of where this could be used is validating that a class has been marked with the SerializableAttribute.

[Serializable]
public class testclass {}

[Test]
public void Test()
{ Assert.That(new testclass(), Has.Attribute<SerializableAttribute>()); }

I have to admit, when I first saw the Has.Attribute constraint, I thought for sure one of my test base classes was going to get a bit lighter. One of the applications that I work on has a pluggable architecture and uses attributes to determine what should be exposed to the end user. I had to code up a method that used reflection to determine if the items that were supposed to be exposed did in fact contain the attribute that exposed them. I was somewhat disappointed to see that it only seemed to work with instances of objects and not Types or MemberInfos. This did get me thinking, however, that my approach of putting this in a base class may not have been as elegant as learning about extending NUnit. Perhaps that will be a post in the future. I should call out that this was in the NUnit blog as a feature added in Alpha 1, however, it is the only feature listed here that has not made it to the documentation yet. That could mean that it just has not been documented yet, or it could indicate that it is not yet ready for prime time.

Range Testing

Is.InRange allows you to use a more concise syntax for expressing assertions that required both a GreaterThan and LessThan for validating an item is within bounds.

[Test]
public void RangeTesting()
{
    // old way
    Assert.That(3, Is.GreaterThanOrEqualTo(1) & Is.LessThanOrEqualTo(5));
    // new way
    Assert.That(3, Is.InRange(1, 5));

    // NOTE: InRange is inclusive
    Assert.That(5, Is.InRange(1, 5));
    Assert.That(1, Is.InRange(1, 5));
}

New Assertions

In some tests you are able to determine early in the test that the expected behavior has been met. Rather than throwing in a return statement or creating triangular code, the new Assert.Pass method is available for early termination with passing results. There is also a new inconclusive result state that can be set by calling Assert.Inconclusive. I have no idea how this can be used; I cannot think of any test scenarios that I have had to implement where I really was looking for "Assert...oh...I don't know." It seems there is a failure in the system at this point, even if that failure point is not understanding the requirements. I would take this as an indicator to go clarify requirements with the client and write a better test.

Specialized Assertions

CollectionAssert has picked up a set of IsOrdered constraints. This constraint uses the IComparable interface to verify increasing or decreasing order of all of the items in a collection. This is another one of those features that I have implemented in a test utilities class. I am happy to remove those lines of code.

Previous versions of NUnit had a FileAssert class to verify that your application was generating an output file. DirectoryAssert has been added as a compliment to FileAssert. The DirectoryAssert.IsWithin method (or IsNotWithin) will crawl from the directory specified, including all of its subdirectories, to verify that the expected directory is present. You can also use IsEmpty to verify if a file was output. You are, of course, still responsible for determining that the correct output was written.

Generic Support

There are several type constraints in NUnit that take typeof(class) as a parameter. The following constraints have been updated to include a version that takes a generic parameter specifying the type.

Assert.IsInstanceOf<T>(object actual);
Assert.IsNotInstanceOf<T>(object actual);
Assert.IsAssignableFrom<T>(object actual);
Assert.IsNotAssignableFrom<T>(object actual);
Assert.Throws<T>(TypeSnippet code);

The TestFixtureAttribute also picked up a generic version. Use this to test a class that takes a generic type parameter. Specify this attribute multiple times on a class, each time specifying a different type for the generic parameter. For each type specification, a new test instance is created and executed. This is useful when you were trying to exercise a class under test with a couple of different types. It does seem like this is the wrong level of abstraction for a test, but I am sure it is a reaction to some level of demand.

Try it out

Every one has a different tolerance for using things that have not been marked as released, yet. Early releases of NUnit traditionally have been very solid. Much like GMail still being in beta, it seems the open source community drop releases much more often, but keeps them flagged with alpha and beta. I have already started using these features to produce cleaner, more readable test code.

tdd
Sunday, November 16, 2008 10:04:37 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0]  |  Trackback
Monday, November 03, 2008

RowTests are a great tool for consolidating tests that have the same logic, but differ by the parameters and the expected values. I did a post a while back on using RowTest in MbUnit, and Michael Eaton recently posted on using RowTest with NUnit. Reading Eaton's post reminded me that I had just run into a new feature in the NUnit 2.5 drop. One of my favorite features of competitive open source tools is that they usually add at least one feature more than the other guy with each release. For the 2.5 release of NUnit, one of those features is the ValuesAttribute. Granted, MbUnit had this feature in concept with CombinationalTestAttribute, but the usage of the ValuesAttribute in NUnit seems much cleaner to me.

Tests with no [Values]

Looking at the previous posts on RowTests, you can see that passing in many values for a specific test is not that difficult. So why would we need anything else? In certain scenarios, the number of permutations that you would have to write Row attributes for could be pretty cumbersome, and if it is truly a permutation scenario, difficult to maintain. The test case for this post will be that the test should be called with all possible combinations of 1,2,3 for one parameter and 10,20,30 for another parameter. With this simple example you can see that we have already blown up to 9 rows, adding on more variant onto either of the parameters and we would have 12 rows to maintain.

Giving your tests [Values]

What the values attribute does is allow you to express all 9 of these combinations in a very concise syntax. This lines up better with the expression of your requirements; instead of 9 Row attributes, you would now have the following:

[Test]
public void Use_Value_Attributes([Values(1,2,3)] int param1,[Values(10,20,30)] int param2)
{
    r.DoStuffWithParms(param1, param2);
}

This nicely wraps up in one line what would have been expressed with 9 [Row] attributes in the past. Bring this up in the NUnit gui to verify that the tests you were looking for were in fact generated.

ValueAttributes

What do you use it for

Now that you have such a powerful tool in you toolset, start to think about how this would be useful. The real world case where I use this feature ensures that interaction with an external library is correct both in number and order of calls when the actual parameters from the system are applied. This test is purely focused on the behavior of the system not the expectation of a mathematical result.

What wouldn't you use it for

It would be very difficult to tie an expected value to the generated permutations. So if you are going after a specific output from an algorithm, a RowTest will work much better for you. Keep in mind that the RowTest feature has been around a while, so it is likely that you will use it more often.

Monday, November 03, 2008 10:15:32 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0]  |  Trackback
Monday, October 20, 2008
The keynotes from PDC are always packed with information on the direction of tools from Redmond over the next couple years. If you are not going, you may be thinking, "I will download the videos when they are available." This year there is a better option. Join us at the SRT offices in Ann Arbor. After the keynotes, and realistically during, talk with developers in the local community for an even better understanding of the impact of these announcements. Microsoft will be sponsoring lunch for this event.

Remote Viewing & Discussion of the Ray Ozzie Keynotes
Monday, October 27, 11:30a-2:00p - Register
Tuesday, October 28, 11:30a-2:00p - Register
SRT Solutions
206 S. Fifth Avenue, Suite 200
Ann Arbor, Michigan 48104



Monday, October 20, 2008 12:16:07 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0]  |  Trackback
Monday, October 06, 2008
I thought a long time about whether or not to put this blog entry on my tech blog. This is by no means a technical post, but it relates to a very important issue for my family.

The Event
On October 12, 2008 American Diabetes Association will be having a fundraiser walk to raise money for "research, information and advocacy efforts and its mission: to prevent and cure diabetes". This year my family will be participating in the walk and could use your support.

I have set up a team named after my oldest son who was diagnosed with Type 1 diabetes on Nov 26, 2007. There are two ways to help. From this link click on Join Team to walk with us in Ann Arbor or click on a member of the team to sponsor that walker. Note that any donations are going directly to ADA. ADA will send out the necessary information for the tax deduction.

Our Story
On Nov 26, 2007 the lives of our family were changed significantly. On that date, our oldest son (4 years old at the time) was diagnosed with Type 1 diabetes. The result of this is that blood sugar levels are checked around 8 times a day. Every carbohydrate consumed is counted. There is a set of ever changing ratios to determine how much insulin is required to try to ensure that the carbs just eaten do not make the blood sugar levels too high and that the insulin levels do not make the blood sugar levels go to low. It is a very delicate balance given the ever changing metabolism, hormones, and activity levels of a boy that age. 

Prior to August, every day included 2 shots of long term insulin as well as 3 shots of short term insulin that went with meals and usually 1 shot for correcting things that did not go according to plan. So our brave little boy had 6 shots a day for nearly a year. In August we became eligible for insulin pump therapy. So rather than 6 shots a day, he now has an infusion set every 3 days that stays attached 24/7. Hard to believe that a 5 year old would be excited about having something stuck under his skin perpetually, but one injection vs 18 shots works out to be a good deal. As it turns out, the pump also has much finer grained dosages that enable much better control.

As of today, my son has started kindergarten and has an A1c of 6.9%. An A1c of below 7% reduces risk of complications by 40%, and they only hope to get to 8% in a child of that age. So in spite of all of the challenges facing this little guy, he is doing very well. I am very excited to see where life takes him. Through events like this, diabetes management technology has come a very long way in a short period of time. I hope that in my lifetime I can see a day where constant 24/7 management of this disease is a thing of the past.



Monday, October 06, 2008 8:35:13 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0]  |  Trackback
Saturday, October 04, 2008

In the previous post, I walk through creating a web site project where C# and Visual Basic code live happily in the same project file. The call to action from that post is to ask "What this could be used for?" If you recall from that post, some of the distinguishing features of VB9 over C#3 are XML Literals and expanded support for LINQ query expressions, but where would I use these features? I can't think of a good reason to use these features in the code-behind of a web site project (user interface layer); places where I would use LINQ expressions, for instance, would be in a business logic layer.

The Process
When creating business logic functionality, under TDD we would first create a test to ensure that this functionality does what it is supposed to. Using a web site project under this process, things start to fall apart. A website project does not create an explicit assembly that you can reference inside of a unit test library project. I created a test assembly in the same solution as the MultiLanguage project. When I tried to add a reference, the project was not available either. Because we can't reference the web project assembly, we can't test it, which means there is no test coverage of the components inside App_Code. This is a deal breaker for me; I sure hope that I have missed something along the way.

The Feature Request
What I really want is a class library project that acts like the website project when it comes to adding files in multiple languages. I want to be able to add a partial class implementation in the primary language of my choice. I also want to be able to add a partial class implementation that will allow me to implement methods on that class in a secondary language if that language is better suited for a particular task. The compiler that works with the website project is clearly able to handle this scenario. How about letting Visual Studio do this for me in class libraries?

Looking Forward
As of right now, the benefits of using both VB and C# do not seem to be worth the cost of the extra steps required to build a testable assembly. C# and VB are not that far apart; there are relatively few differences that make one more effective than the other, and that effectiveness is marginal. That said, there is a lot of language work going on top of the CLR. There are significantly different approaches to problems that are enabled by using a functional languages like F#. There is a totally different set of solutions in the dynamic language world enabled by the DLR in languages like IronRuby and IronPython. I want to be enabled to use the best fit language for a given problem and package up that solution in a way that makes sense. I don't want to have to create a new class library and package that into the deployment process every time I want to use a feature from a different language.

If you are only building web solutions and test coverage is not important to you, than the technique described would meet that need. There is still a hole for non-web solutions. There are still plenty of apps written in WinForms, Console apps, or even just a single library. It would be handy if Visual Studio would provide for the use of this technique in environments other than web site projects.

 

Saturday, October 04, 2008 11:29:49 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0]  |  Trackback
Friday, October 03, 2008
Using C# and VB in the same project file! That is bound to get under the skin of the C# zealots. I prefer to code in C#, but these days it feels much more like I am coding to the framework, other libraries, or CodeRush (if you are addicted like myself). There are times when VB provides some real advantages over C#. Like XML Literals and specific cases of query expressions (like Take and Distinct).

The goal of the sample site
This post will demonstrate how to leverage multiple languages within a website project. The website will contain pages written with both C# and VB as the code behind languages. These pages will contain user controls that have been written in both languages as well as reference classes that have been coded in both languages. All of the pages,user controls, and classes will be contained in a single project file.

Make a website project
From the file menu select New Website... then select ASP.NET Web Site
In the sample I have named the site MultiLanguage. There are several differences between a web site project and a web forms project. An advantage of web site projects that we will take advantage of is the language selection on the web site creation dialog. What I find interesting is that the only effect of this option is to select the code-behind for the default page that is created. In an web forms application, the project file is set up to be bound to the language compiler before the first page is created. Since the goal here is to include different languages in a project, the web site project is the choice for us.

Add web forms
Add two new web forms: one with C# code behind the other with VB code behind. For the sample I chose the names of csPage.aspx and vbPage.aspx, respectively. This is really easy at this point since the new web form dialog has a language drop down that allows the selection of your preferred language. For the sake of feedback, drop a label on the page. In the page load event handler, populate the label with the language used in the code-behind.

<asp:Label ID="languageTag" runat="server" />languageTag.Text="CSharp PageLoad Handler";

Try it out
At this point you should be able to bring up both pages. Already this is quite different than the usual web site. Two pages that are peers in the same project have been created with different languages.

Add user controls
Add two new web user controls: one with C# code-behind the other with VB code-behind. The sample uses the names csUserControl.ascx and vbUserControl.ascx. Just like with the forms, the language can be selected right on the add User Control dialog. Just like in the forms, add a label to the control. Just like in the forms populate the page load event handler for the control with code to update the label with the language used in the code-behind of the control.

<asp:Label ID="languageTag" runat="server" />languageTag.Text = "CSharp UserControl PageLoad Handler";

Include the controls
Drag both controls onto each of the language-specific pages. No additional work is required to wire up events on the controls, as they are self contained for this example.

<uc1:vbUserControl ID="vbUserControl1" runat="server" />
<uc2:csUserControl ID="csUserControl1" runat="server" />

Try it out
Bring up both pages again. Now for any given page multiple languages are being used to render it!

Add classes
So far, the steps involved in adding multiple languages to pages and user controls have been discoverable using Visual Studio directly. Adding classes is slightly different. The App_Code folder will enable us to pull off multipule-language classes. Add an App_Code folder if you do not have one already: right-click the project, select Add ASP.NET folder, there will be an App_Code selection. In the App_Code folder, add a new class for both VB and C#. Here again, the language selection still lets you choose a language. As a quick way to get some feedback from each class, provide an override of ToString that will say what language the class is written in.

public override string ToString()
{
  return "CSharp class text";
}
Public Overrides Function ToString() As String
  Return "VisualBasic class text"
End Function

Add the classes to the forms

Add labels to the language specific pages, one for each language specific class. In the page load event handler for the page, instantiate one instance of each class and populate the new labels on the page with the ToString call from each language specific class

csClass mycsClass = new csClass();
vbClass myvbClass = new vbClass();
csClassText.Text = mycsClass.ToString();
vbClassText.Text = myvbClass.ToString();

However, if you bring up one of the pages you will be greeted with a compiler error that the two classes use a different language.

Adding multiple language support to App_Code
In order to use multiple languages inside App_Code you will need to add sub folders to App_Code. I'll name these folders csharp and visualbasic in the sample. Now, notify the compiler that these subfolders should be compiled separately. This can be done by adding a codeSubDirectories section under the compilation area of the web.config.

<codeSubDirectories>
    <add directoryName="csharp"/>
    <add directoryName="visualbasic"/>
</codeSubDirectories>

Move the VB class from App_Code to this visualbasic folder, and the C# class to the csharp folder, then try to view one of the pages.

Try it out
That is it! Now we have forms, user controls, and classes all using both VB and C# included in the same project file.

 

Now what
The first thing to ask when seeing a new technique, is "What would I use this for?" Being a fan of TDD, I have issues with this approach, but I will leave that for the next post. If you don't care much about test coverage, this technique is useful for leveraging features specific to a language to get the job done as efficiently as possible.

Sample Project

MultiLanguage.zip (7.61 KB)
Friday, October 03, 2008 9:35:56 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0]  |  Trackback
Wednesday, July 09, 2008

I would like to thank Micheal Eaton for kicking off this meme. I have enjoyed many hours reading the responses. But, now I feel guilty for not having put up my response sooner.

How old were you when you started programming?
At 9 years old, my parents bought me the Intellivision computer. I spent many hours re-typing sample code and tweaking it.  This was the same timeframe as the VIC-20. I had a friend with one of these. We would trade the sample programs and have to modify them to work on a different system. This was probably more PEEKing and POKEing than a kid should have been doing.

How did you get started in programming?
The hook for me was a downhill skiing game on the commodore. Somehow, I managed to find the collision detection portion of the code. After a bit of modification, no one could touch my record time. hehe. Of course, I put the collisions back in once my time was set. Exposure to that level of ego gratification at that young age was just dangerous.

What was your first language?
BASIC

What was the first real program you wrote?
As an intern, I wrote a set of shell scripts that set up a clean AT&T System V Rel 3.2 System with all of the hardware that was attached. This included serial port extenders, terminals, and printers as well as other hardware. I was much like plug and play for Unix in '91. It shaved about 90% of the setup time on one of these systems. A few months later an AIX version was created. That was the first time I realized that even people I looked up to could be interested in my unusual approach to an existing problem.

What languages have you used since you started programming?
I'll only mention ones that have been used professionally. bsh,csh,CADOL (oh boy don't ask), C, 8086 asm, C++, VB, Java, C#, Ruby, and PowerShell.

What was your first professional gig?
I had an internship at Versyss. There I worked on the previously mentioned script, some minor enhancements and was general gopher. My first full-time gig was at EDS with GM as a client. I worked on Automotive Diagnostic software. This is still some of the coolest stuff I have done to date.

If you knew then what you know now, would you have started programming?
Absolutely. This in one of the few industries that you can really solve problems in just about any business space. If you are bored it is your own fault.

If there is one thing you learned along the way that you would tell new developers, what would it be?
Never, ever take the golden handcuffs. There is too much enjoyment in this industry to get stuck doing something you don't like because you can't leave. This really relates much more to how you handle your personal finances than what job you take. Do that right, and you have many more options available to do the things you want to do.

What's the most fun you've ever had ... programming?
There are really many to choose from. Almost all of them have been off project or black ops. There is something about solving a problem you are interested in using an approach that you enjoy. I find that things developed in this space end often end up having a lot of value.

Wednesday, July 09, 2008 12:37:25 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0]  |  Trackback
Friday, June 27, 2008

What do you do when the limitations of SQL Management Studio will not show all of your results?

Our application works with an XML file defined by an external industry specification. We found that a significant portion of this file is not required by our application. So, when loading this file into our system, we remove the portions that we do not care about and stuff the rest into a database. What is left can still be a pretty good sized XML string. Common usage shows the reduced size to still be around 300-500 KB.

Recently, we needed to investigate the contents of one of these modified files as well as the history of what was loaded. Using the standard developer playbook, the first response is to quickly fire up SQL Management Studio and craft a query to get the ntext column. At that point, the 65K limit on a column in Management Studio yields about a quarter of the file.

It would be pretty easy to pull up Visual Studio and put together a quick utility to extract the XML into a file. As a developer, I would likely keep this project around for an excessively long period of time. After all, it is now part of my code toolbox. So, rather than squirrel away a project file, source file, and all the related baggage of a VS project, I chose PowerShell as the hammer for this nail. The C# code that would have been created in Visual Studio, in this case, is simply a language that is accessing the functionality in the .net framework. Since PowerShell has access to the .net framework, it is very similar code simply using a different language. Additionally, the PowerShell script is a single file without the weight of a VS project. The only thing that I keep in my toolbox is the code required to complete the task.

What is required is the pretty common code of opening a connection, executing a query, and using the results. This is how this common C# task is represented in PowerShell. We are pulling back several rows that contain this large XML field and tagging the resuts by upload date.

param( $theId, $server,$db )


$connection = New-Object System.Data.SqlClient.SqlConnection("data source=$server;initial catalog=$db;Integrated Security=SSPI")
$command = New-Object System.Data.SqlClient.SqlCommand("select * from MyTable where theItemId=$theId", $connection)

$connection.Open()

$reader = $command.ExecuteReader()
while( $reader.Read()  ) {
    $fileName = "Item_{0}_DateLoaded_{1:yyyy_MM_dd_HH_mm_ss}.xml" -f $theId,$reader['dStart']
    Out-File  -FilePath $fileName -InputObject $reader['reallyBigXMLText']
}

$connection.Close()
$reader.Close()

Save that text into a .ps1 file and that is all that is necessary to extract the large text field. I am not one that has cut over from the classic command line to PowerShell. At the same time, it is important to know when this tool can be helpful.

Friday, June 27, 2008 1:11:03 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0]  |  Trackback
Monday, June 23, 2008

The next topic in this series was supposed to be invariants. While that topic will still be coming up, the topic of nulls was not complete enough. In the last post, coverage was mostly related to parameters and method signatures. Since parameters are not the only variables in a system that can be null, it makes sense to talk a little about class fields. Consider the following class member from the Sentence class discussed in Part 1.

List<string> words = new List<string>();

Several methods and properties in the sentence class perform operations on this variable by dereferencing it and calling its methods and properties. Spec# notices this and warns of a potential null dereference. At first this seemed like a bit of an inconvenience. But if you think about this a second, this warning is for every location where "object reference not set to instance of an object" can occur. Wow, removing that error from the development cycle would no doubt be a huge boost to productivity. So a simple change to the signature eliminates that warning.

List<string>! words = new List<string>();

So what if you are not instantiating objects the same way for each class creation. Try removing the new from the declaration, and a whole different error shows up. This time the constructors all get flagged. Spec# notices that the fields that have been marked as non-null have not been assigned in the constructor. New up a sentence object in the constructor on the validation engine is now happy.

There is an impressive depth to the null checks that can lead to a much more solid code base. In the strong typed world where compiler errors are preferred, Spec# strengthens the type checking pushing potential errors earlier in the development cycle to the point of some of them showing up in the editor pre-compile time!

Monday, June 23, 2008 3:26:17 PM (Eastern Standard Time, UTC-05:00)  #    Comments [1]  |  Trackback
Friday, June 20, 2008

One of the key characteristics that makes a professional-quality application is defensive coding. While necessary, this can hide the meaningful portions of logic. It can also lead to many tests that are more related to the chosen implementation than the business rules. Take this simple piece of code to add a word to a sentence.

public void AddWord(string word)
 {
     if (word == null) throw new ArgumentNullException("word");
     if (word.Length == 0) throw new ArgumentException("word");
     words.Add(word);
 }

The validation code dominates this simple function. Additionally it does not provide the consumer of the method with any hints to the parameters constraints. Sure, xml docs can provide some documentation, but that still does not help at design time. A set of tests that check the expected exception would also be common for this block of code. There is plenty to debate about the non-functional tests, but it is safe to assume that this kind of testing is common.

The Spec# team is doing some incredible work to make constraints like this either enforced by the language or more visible by placing them within the method signature.

The first parameter check relates to nullness. Spec# provides an operator for forcing non-null. The signature of AddWord would now look like:

public void AddWord(string! word)

This tells the compiler and Visual Studio that this parameter cannot be null. If you even try to pass a string that can be null to this method, a warning will appear at design time. A compiler error will also result. This really cranks up the visibility of the constraint. The user of this method can also see the constraint right in the signature.

The second parameter check relates to some data constraint on the string. In this case, it is required to be a non-empty string. What is really going on here is that this method has a pre-condition relating to the data it is going to work with. Preconditions in Spec# are specified with the requires keyword. So our method now looks like:

public void AddWord(string! word)
 requires word.Length > 0;
{
 words.Add(word);
} 

Now the requirements are part of the method signature that show up in intellisense. This alone is a big help to the development process. The precondition is validated at runtime kicking out an exception if the condition is not met. It is worth noting that you can map the stock RequiresException back to an argument exception via the otherwise keyword.

requires word.Length > 0 otherwise ArgumentException;

It is pretty evident to see the big gain here in the signature of the method containing all of the relevant constraints. Even more assistance can be provided at design and compile time when these constraints are provided in the signature. Even better than all of this is that the body of the method is left with only the required logic the method is responsible for.

There is plenty more to cover with the direction spec# is taking. Next up, validating the internal state of an object as part of the class definition.

Friday, June 20, 2008 10:39:57 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0]  |  Trackback
Thursday, March 27, 2008

At this months GLUGnet Flint meeting, I will be giving a presentation on PowerShell. What drove me to put this presentation together is all of the recent conversations I have had about PowerShell. It seems to be one of those topics that developers intend to look at but never really get to. This presentation starts from the ground up to several real world examples that have come up in my work environment. I sincerely hope that after this meeting those that have not used PowerShell yet will walk away with another tool in their arsenal.

Hope to see you there.

UPDATE: Adding files and ppt

glugnet.zip (89.02 KB)

Thursday, March 27, 2008 9:13:51 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0]  |  Trackback
Wednesday, February 13, 2008

One of the things I really enjoy about the local developer groups is the sharing of ideas and usage patterns of common tools. At tonight's Ann Arbor .net Developers Group, the topic of CodeRush templates came up. I commonly use a set of templates centered around the Rhino Mocks framework As I was describing these templates Jay Wren claimed they should be posted. The irony in that is the first time I saw someone using CodeRush was in a presentation Jay was giving on IoC. As a result of that presentation, we are using Castle Windsor in our application and CodeRush as a productivity tool. 

Creating a Mock Instance

To use Rhino Mock to create a mock instance, you write something like:

MyType myType = (MyType)mocks.DynamicMock(typeof(MyType));

This is an exceptionally redundant exercise that just screams for a Template. The core part of the template takes a string from the Get string provider (named Type) for the type of the instance to create. It will also name the variable with the same name as the type with a slightly different format. Even though this variable name is a linked field, you can break the link by pressing Ctrl-Enter while the cursor is on the variable name. This is commonly required in when creating multiple mock instances in the same scope.

#MockInstance#: Base template not intended to be called directly

«Caret»«Link(«?Get(Type)»)»«BlockAnchor»«Link(«?Get(Type)»,FormatLocalName,PropertyNameFromLocal)»= («Link(«?Get(Type)»)»)mocks.DynamicMock(typeof(«Link(«?Get(Type)»)»));

mk: the type name is initialized to MyType

«?Set(Type,MyType)»«:#MockInstance#»

mk\: the type name is initialized from the Clipboard

«?Set(Type,«?Paste»)»«:#MockInstance#»

Setting up the Tests

The mock instance templates are not much use without having the MockRepository set up and test methods to call. These templates come in handy as well.

mtf: the test fixture

[TestFixture]
public class «Caret»My«BlockAnchor»Test
{
 private MockRepository mocks;

 [SetUp]
 public void Setup()
 {
  mocks = new MockRepository();
 }
 
 «Marker»
}


mt: the test

[Test]
public void «Caret»Test«BlockAnchor»()
{
 «Marker»
 mocks.ReplayAll();
}

Hopefully these templates will be found useful and maybe even kick off some ideas for new ones.

UPDATE: Yea, it would be easier if I added the export file.

CSharp_Custom.xml (12.45 KB)
Wednesday, February 13, 2008 11:44:18 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0]  |  Trackback
Tuesday, February 12, 2008

PowerShell has been a topic of interest for me for the last couple of weeks. I have been squeezing in some reading on it here and there for about a little over a week. Out of the blue pops up one of those issues at work that does not involve making an elegant object model, but rather digging through log files. How cool is that? For more years than I care to mention, it seems like every time I start looking into a new topic, something comes up where that research saves a ton of time. So there I am whipping up this script, when SharpReader pops up toast that says Using an IDE to write PowerShell Scripts. If you are doing any PowerShell work at all, go ahead, stop reading this post and go get that tool. The post will be here when you get back. The PowerShell Suite has been discounted for 2 weeks associated with Hanselman's post and there is a free version for non-commercial use.

The issue was that users in Germany were getting access denied during a particular time frame. Since this time frame overlapped with with the nightly import of user information, there was some speculation that there was a collision with the import. We wanted to get a list of users that got the access denied and correlate that with the users that were imported. That leaves us with 500MB for 2 hours on each server. 8 web servers and a 4 hour period in question yields 16GB worth of log files to mine. Definitely an automation task.

The log file looks like:

... cut
[8364/18416][Tue Feb 07 04:30:27 2008][..\..\..\CSmHttpPlugin.cpp:402][INFO:1] PLUGIN: ProcessResource - Resolved Url '/security/accessdenied.aspx?ReturnUrl=index.aspx'.
[8364/18416][Tue Feb 07 04:30:27 2008][..\..\..\CSmHttpPlugin.cpp:515][INFO:1] PLUGIN: ProcessResource - Resolved Method 'GET'.
[8364/18416][Tue Feb 07 04:30:27 2008][..\..\..\CSmHttpPlugin.cpp:566][INFO:2] PLUGIN: ProcessResource - Resolved cookie domain '.SITENAMEWASHERE.com'.
[8364/18416][Tue Feb 07 04:30:27 2008][..\..\..\CSmHttpPlugin.cpp:3727][INFO:1] PLUGIN: EstablishSession - Decoded SMSESSION cookie -  - User = 'uid=USERIDHERE,dcxdealercode=DEALERCODEWASHERE,ou=dealerships,ou=dealers,o=DOMAINWASHERE.com', IP address = 'IPADDRESSWASHERE'.
... cut

What we needed was the occurrence of access denied where the source was the home page. A few lines later in the log, the SiteMinder user information was present. The script then needs two modes: looking for access denied and looking for the user info. Get-Content provides reader like functionality kicking out a line of text at a time from the provided file. Piping to a ForEach calls the associated script block for each line of text in the file. Use some Regex magic to find the correct string and extract information from the user information line. The result of the Regex is where I ran into the biggest hang up. PowerShell has an automatic variable $matches that is populated when a match is found (when a match is found not when a match is attempted). So I had to clear out the $matches variable after processing a match. The only output was the parsed user information that could be passed off to Brian, who deals with the imports. It is a pretty simple piece of script that looks like:

param ( $infile )

$lookingForSiteMinderCookie = $FALSE
$matches = $null
$Get-Content $infile | ForEach-Object {
  if( $lookingForSiteMinderCookie )
  {
    if ( $_ -match '^.*\[.*\](\[.*\])\[.*\]\[.*\].*uid=([a-zA-Z0-9]*).*dcxdealercode=([0-9]*).*$' )
    {
      "TimeStamp: {0}`tUser: {1}`tDealer: {2}" -f $matches[1],$matches[2],$matches[3]
      $matches = $null
      $lookingForSiteMinderCookie = $FALSE
    }
  }
  else
  {
    if ( $_ -match '^.*accessdenied\.aspx\?ReturnUrl=\%2fhome\%2fmain\.aspx.*$' )
    { 
      $matches = $null
      $lookingForSiteMinderCookie = $TRUE 
    }
  }
}

 

This was saved as LogParse.ps1.

From the PowerShell command line:

  • Use Get-ChildItem with a filter that matches the log file names to get a list of log files
  • Iterate through each file using ForEach calling LogParse.
  • Output to Out-File to save the results

Get-ChildItem logfilepattern | ForEach-Object { .\LogParse $_ } | Out-File deniedUsers.results

I have found PowerShell to be a very useful tool for doing some quick and dirty tasks. I can certainly see that with a bit more experience with it, a command line .net interpreter could be very handy. Check it out. You can rarely go wrong by having another tool in the toolbox. I do want to point out that this was primarily an exercise in using Powershell because I wanted to learn it better. The power of PowerShell is not going to come in text processing where there are many tools that have been around for a very long time that do that job very well. Many shells use strings when piping between commands. Passing a string object is not that much better. The real power comes when you start using objects and even more when you use objects in the pipeline. That is the feature unique to PowerShell.

Tuesday, February 12, 2008 8:29:01 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0]  |  Trackback
Thursday, January 17, 2008

Predicate: Logic. that which is affirmed or denied concerning the subject of a proposition.

In programming terms, a function that returns true or false taking a subject as a parameter. So, Predicate<T> is really just a specific signature applied to a delegate. A method compliant with this signature looks like:

bool method(T item)

The collection classes in System.Collections.Generic have several methods that will take a predicate as a parameter. I really like this separation of concerns. The responsibility of iterating through the collection is owned by the collection; the responsibility of making a decision based on data in an object is owned by the object. What seemed to be missing to me was the common operation of combining boolean results with logical operators. What I really wanted to do was to pass a set of predicate functions to the collection methods. Of course, the collection authors could not know how I would want the boolean results combined. This seemed to be the responsibility of something else that could contain a list of predicates, but at the same time return a predicate function that is the logical combination of the results.

The PredicateList class is a container of Predicate<T> delegates. The methods that can be used as a predicate are the logical AND and OR operations. These methods iterate through the contained predicates and short circuit when arriving at a value that determines the result of the operation.

using System;
using System.Collections.Generic;

namespace Utilities
{
  public class PredicateList<T> : List<Predicate<T>>
  {
    public PredicateList(params Predicate<T>[] predicates)
    {  AddRange(predicates);  }
    public bool And(T item)
    {
      foreach (Predicate<T> pred in this)
      {
        if (!pred(item)) return false;
      }
      return true;
    }
    public bool Or(T item)
    {
      foreach (Predicate<T> pred in this)
      {
        if (pred(item)) return true;
      }
      return false;
    }
  }
}

Using this class with one of the collection methods would look like:

PredicateList<T> filters = new PredicateList<T>(IsThis, IsThat, IsTheOtherThing);
return FindAll(filters.And);

Thursday, January 17, 2008 10:31:02 AM (Eastern Standard Time, UTC-05:00)  #    Comments [1]  |  Trackback
Wednesday, January 16, 2008

While working on the tests for the next post, I was reminded of how cool MbUnit can be. Most tests have the signature of public void TestMethod(). In some cases, this causes a propagation of tests in order to accomplish running pretty much the same test with different data. MbUnit adds the RowTest attribute to the mix. With the RowTest and Row attributes you can create one parameterized test "template" and the test will run for each data item provided. Running the following code will execute 3 different tests, one for each of the Row parameters provided.

[RowTest]
[Row(2,8)]
[Row(5,5)]
[Row(8,2)]
public void GreaterValueTest(int filterValue, int expectedCount)
{
  ClassicCollectionBase results = col.FilteredCollection(new GreaterValueFilter(filterValue));
  Assert.AreEqual(expectedCount, results.Count);
}

This cool feature can help reduce the maintenance time associated with test code.

What about NUnit?

With the new features of NUnit 2.4 Andreas Schlapsi has an NUnit extension that allows for RowTests. I would expect this exceptional feature to get rolled into the core in an upcoming release.

tdd
Wednesday, January 16, 2008 7:52:11 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0]  |  Trackback
Sunday, January 13, 2008

With the release of VS 2008 and SQL Server 2008, a set of certification updates are in the works. If you are one to keep your certifications up to date, you may be interested in the following webcasts:

MCP Live Meeting: Microsoft Certification for Developers

MCP Live Meeting: SQL Server 2008 and Your Microsoft Certifications

UPDATE: These were live wecasts on Jan 23 2008. They have not yet been archived for On-Demand use.

Sunday, January 13, 2008 2:11:18 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0]  |  Trackback
Saturday, January 12, 2008

Equality comparisons in .net behave differently by default for reference types and value types. Value types are considered equal when the state of the object is equal. Reference types are considered equal when the reference points to the same location in memory. Therefore two different instances of a reference type would not be considered equal even if the internal state is the same. A quick unit test can be used to show this.

The class we will be using for comparison:

using System;

namespace Equality
{
  class MyClass
  {
    public MyClass(int id)
    { _id = id; }

    private int _id;
    public int Id
    {
      get { return _id; }
      set { _id = value; }
    }
  }
}

The test fixture and the first test:

using System;
using MbUnit.Framework;

namespace Equality.Test
{
  [TestFixture]
  class EqualityTest
  {
    const int equalId = 10;
    const int notEqualId = 12;

    MyClass testClass = new MyClass(equalId);
    MyClass equalClass = new MyClass(equalId);
    MyClass notEqualClass = new MyClass(notEqualId);

    [Test]
    public void EqualsMethod_Test()
    {
      Assert.IsTrue(testClass.Equals(equalClass),"Equal by identity but not by reference");
      Assert.IsFalse(testClass.Equals(notEqualClass), "Not equal by either identity or reference");
    }
  }
}

Test Results:

------ Test started: Assembly: Equality.exe ------
Starting the MbUnit Test Execution
Exploring Equality, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
MbUnit 1.0.2700.29885 Addin
Found 1 tests
[failure] EqualityTest.EqualsMethod_Test
TestCase 'EqualityTest.EqualsMethod_Test' failed: Equal by identity but not by reference
MbUnit.Core.Exceptions.AssertionException
Message: Equal by identity but not by reference
...
0 passed, 1 failed, 0 skipped, took 1.63 seconds.

Since all reference types derive from System.Object, we can change this behavior by overriding the Equals method to do a comparison that means something to the object. In this case we will use the Id property. In this case we will first test to make sure that the object being compared is of the correct type and then we will compare the Id property. As an interesting excercise, take a look at the override of the Equals method in the System.ValueType class using Reflector. This implementation uses reflection to determine what items can hold state. It then does a comparison for each item (using .Equals in the end so that reference types work correctly).

  public override bool Equals(object obj)
  {
    MyClass testClass = obj as MyClass;
    return Id == testClass.Id;
  }

Results:

------ Test started: Assembly: Equality.exe ------
Starting the MbUnit Test Execution
Exploring Equality, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
MbUnit 1.0.2700.29885 Addin
Found 1 tests
[success] EqualityTest.EqualsMethod_Test
1 passed, 0 failed, 0 skipped, took 1.59 seconds.

Now we have the Equals method expressing a meaning for equality that matches our understanding of the object. This is a nice advantage when using framework classes such as collections. Collection methods like Contains will call the object's Equals method. Simply overriding the Equals method gives us many more tools to work with without much effort. One thing that should be mentioned here is the warning that occurs when you override Equals. You will be greeted with a compiler warning about overriding Equals without overriding GetHashCode. GetHashCode is defined as a method that should return a number unique for a given instance of the object. We are using the Id property for that purpose.

public override int GetHashCode()
{ return Id; }

Now it would be really nice to have some consitancy with other mechanims used to compare equality. Another common mechanism for equality testing is the == operator. Lets put together a test that will see if this complies with our objects definition of equality.

[Test]
public void EqualOperator_Test()
{
  Assert.IsTrue(testClass == equalClass, "Equal by identity but not by reference");
  Assert.IsFalse(testClass == notEqualClass, "Not equal by either identity or reference");
}

Results:

------ Test started: Assembly: Equality.exe ------
Starting the MbUnit Test Execution
Exploring Equality, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
MbUnit 1.0.2700.29885 Addin
Found 2 tests
[success] EqualityTest.EqualsMethod_Test
[failure] EqualityTest.EqualOperator_Test
TestCase 'EqualityTest.EqualOperator_Test' failed: Equal by identity but not by reference
Message: Equal by identity but not by reference
...
1 passed, 1 failed, 0 skipped, took 1.78 seconds.


 

Looks like we have a bit more work to do. What we need to do now is provide the operator == method. We will take advantage of the fact that we have already defined equality in the Equals method on our object. (Note that this is a static method that takes two objects as parameters. One side effect of this is that you do not get to make static members virtual and override them.)

public static bool operator==(MyClass lhs, MyClass rhs)
{
return lhs.Equals(rhs); }

Now we fire up the test to see where we stand and we are greeted with an error message. The compiler is telling us that when == is implemented that != is required as well. After you finish wondering why someone by default would not implement a != method as an inverse of the == method, implement the != method using our Equals method or the == operator. Of course we need to add some tests to ensure that != is doing what we expect.

[Test]
public void NotEqualOperator_EqualTest()
{
  Assert.IsTrue(testClass != notEqualClass, "Not equal by either identity or reference");
  Assert.IsFalse(testClass != equalClass, "Equal by identity but not reference");
}

public static bool operator !=(MyClass lhs, MyClass rhs)
{ return !lhs.Equals(rhs); }

It can be handy for users of your classes to be able to count on basic functionality such as equality. It also will help leverage the framework for collection operations as well. Another thing very similar in nature to this exercise that will help leverage the framework is implementing the IComparable or IComparable<T> interface.

Other Considerations

In Bill Wagner's book Effective C#, Item 10 mentions some issues with overriding GetHashCode. In short, the framework has a very efficient way to come up with the hash code, in many cases you will not come up with something better. If you do not have something as simple as an identity column that is assigned from the database, consider this advice carefully.

 

Saturday, January 12, 2008 4:19:33 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0]  |  Trackback

For it seems like forever, friends and colleges have tried to push me into the exercise of blogging. For it seems like forever, I have resisted because I am horribly slow at writing. Two things are finally driving me to get started. As organizational changes have taken place, the company website is much more focused on the credibility of the Business Development staff and not so much on the Technical Staff. So, I no longer have a professional profile on the company web site. That profile was close to 5 years out of date anyway. More importantly, I hope to improve myself by learning more deeply in order to write about it.

This is my entry point into creating an up to date professional profile as well as getting better at the writing process. The technical content will probably not be real deep for a little while as I work through the process of writing. Hopefully this will be a fun ride.

Saturday, January 12, 2008 2:00:14 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0]  |  Trackback

Theme design by Jelle Druyts