Tijmen 11:00, 16 September 2009

Nothing much to, just that it took me some time to figure it out today. The code below tests whether DivisionID is actually set in the presenter.

 

public class Presenter
{
    readonly IRepository repository;

    public Presenter(IRepository repository)
    {
        this.repository = repository;
    }

    public IView View { get; set; }



    public void GetDivision()
    {
        View.DivisionID = repository.GetDivisionID();
    }
}

public interface IView
{
    int DivisionID { get; set; }
}

[TestFixture]
public class PresenterTests
{
    Presenter sut;
    IView view;
    IRepository repository;

    [SetUp]
    public void SetUp()
    {
        view = MockRepository.GenerateMock<IView>();
        repository = MockRepository.GenerateMock<IRepository>();
        sut = new Presenter(repository){View = view};
    }

    [Test]
    public void when_on_the_sut_GetDivisionID_is_called_it_should_set_the_divisionID_on_the_view()
    {
        //AAA mocking style
        
        //Arrange
        const int divisionID = 1;
        repository.Stub(s => s.GetDivisionID()).Return(divisionID);
        
        //note: the expectation is set when DivisionID is set to divisionID
        view.Expect(s => s.DivisionID = divisionID);
        
        //Act
        sut.GetDivision();
        
        //Assert
        view.VerifyAllExpectations();    
    }
}
Tom 10:31, 15 September 2009

This is the third posting in the WEWLC-series.

 

Other posts are:

I Can't Get This Class into a Test Harness

I don't have much time and I have to change it

Assumptions on the reader

 

"Getting tests in place to make changes can be a bit of a problem. If you can instantiate your class separately in a test harness, consider yourself lucky."

Instantiating a class should not be hard, if you do have issues have a look at I Can't Get This Class into a Test Harness. That should take care of most of your problems.

But instantiating is often just the first part of all the hurdles to take. The second part is writing a test for the methods inside.

 

Fortunately, in most cases, the amount of work that we have to do to write tests for methods isn't as drastic. Here are some of the problems that we can run into.

  • The method may be private

  • The method may be hard to call because it has parameters that are hard to construct

  • The method might have bad side effects (modifying a database, writing to the file system etc)

The Case of the Hidden Method

If we need to write a test for a private method we need to make it public. There are some tricks in getting visibility on the method in your tests but I don't recommend it. First of all, if there is a need for private method odds are that what you need is a another collaborator.

This is of course a rather fundamental discussion. If you do care about keeping the method invisible to callers you can make it protected. Once it is protected you can derive a test class and add a public method that will simply call the protected method in the base class.

In most cases I would recommend moving the method to a separate class and inject it into the constructor of the class that interacts with it. Once there is a need to alter the behavior of a private method it is obviously doing something important, hence, it should be under test.

 

The Case of the "Helpful" Language Feature

Michael Feather is referring to sealed classes that don't have constructor. How do you test interaction code that takes such a class as a parameter in a method? Let's have a look at an example:

public class StreamHelper
{
    const int MIN_LEN = 4;

    public IList GetStreams(HttpFileCollection files)
    {
        var list = new List<Stream>();
        foreach (string name in files)
        {
            HttpPostedFile file = files[name];
            if ((file.FileName.EndsWith(".txt") && file.ContentLength > MIN_LEN))
            {
                list.Add(file.InputStream);
            }
        }
        return list;
    }
}

According to MSDN, the HttpFileCollection provides access to and organizes files uploaded by a client. Since this class is sealed and only has an internal constructor, how can you test this method?

Turns out that HttpFileCollection derives from NameObjectCollectionBase which has a parameterless constructor which is protected. If we thus derive from NameObjectCollectionBase, implement the indexer required and change the signature of the GetStreams method a bit to take our custom class instead of the HttpFileCollection we should be able to get going.

 

Please note, this is going to be a hefty refactoring. Right, lets get down to it. First let's create a fixture for our tests:

[TestFixture]
public class HttpCollectionTests
{
    [Test]
    public void can_instantiate_a_derived_class_from_NameObjectCollectionBase()
    {
        var customHttpFileCollection = new CustomHttpFileCollection();
        var collectionBase = customHttpFileCollection as NameObjectCollectionBase;
        collectionBase.ShouldNotBeNull();
    }
}

 

This means deriving from NameObjectCollectionBase

public class CustomHttpFileCollection : NameObjectCollectionBase
{
    
}

The next test is to be able to call GetStreams() in StreamHelper. Rather than changing the existing method we are going to create a new method with the same name, but different signature so that we can call it with our new CustomerHttpFileCollection:

[Test]
public void can_use_the_custom_class()
{
    var collection = new CustomHttpFileCollection();
    new StreamHelper().GetStreams(collection);
}
public IList<Stream> GetStreams(CustomHttpFileCollection files)
{
    var list = new List<Stream>();
    foreach (string name in files)
    {
        HttpPostedFile file = files[name];
        if ((file.FileName.EndsWith(".txt") && file.ContentLength > MIN_LEN))
        {
            list.Add(file.InputStream);
        }
    }
    return list;
}

This means implementing the indexer used in GetStreams() in our custom class. Luckily Resharper knows what to do and we can use ALT-ENTER to generate the code. Next to the indexer we will also need an IList to store the files and a method to add them to the internal collection:

public class CustomHttpFileCollection : NameObjectCollectionBase
{
    public HttpPostedFile this[string name]
    {
        get { return httpPostedFiles.Where(s => s.FileName == name).FirstOrDefault(); }
    }
}

This poses a bit of an issue; we can instantiate a HttpPostedFile so how are we going to populate an internal collection? Since this one is sealed, does not have a suitable base class and has no constructors we need to be creative. We need a custom implementation of the HttpPostedFile. First we create an interface, then define the same members on the interface as are in the HttpPostedFile class. Once that is done we can change the signature of the indexer to IHttpPostedFile and add some logic to store and add the files to the collection class, like so:

public class CustomHttpFileCollection : NameObjectCollectionBase
{
    readonly IList<IHttpPostedFile> httpPostedFiles = new List<IHttpPostedFile>();

    public IHttpPostedFile this[string name]
    {
        get { return httpPostedFiles.Where(s => s.FileName == name).FirstOrDefault(); }
    }

    public void AddHttpPostedFile(IHttpPostedFile file)
    {
        httpPostedFiles.Add(file);
    }
}
public interface IHttpPostedFile
{
    int ContentLength { get; }
    string ContentType { get; }
    string FileName { get; }
    Stream InputStream { get; }
}

Change the HttpPostedFile to the new IHttpPostedFile in GetStreams():

public IList<Stream> GetStreams(CustomHttpFileCollection files)
{
    var list = new List<Stream>();
    foreach (string name in files)
    {
        IHttpPostedFile file = files[name];
        if ((file.FileName.EndsWith(".txt") && file.ContentLength > MIN_LEN))
        {
            list.Add(file.InputStream);
        }
    }
    return list;
}
 

Now that we have set up the collection, let's write a test to see if it all works

Stream GetStream()
{
    const string s = "hello world";
    var memoryStream = new MemoryStream(System.Text.Encoding.Default.GetBytes(s));
    return memoryStream;
}
[Test]
public void can_use_the_customcollection_to_test_the_StreamHelper_class()
{
    var collection = new CustomHttpFileCollection();
    var httpPostedFile = MockRepository.GenerateMock<IHttpPostedFile>();
    httpPostedFile.Stub(s => s.InputStream).Return(GetStream());
    httpPostedFile.Stub(s => s.FileName).Return("somefilename.txt");
    httpPostedFile.Stub(s => s.ContentLength).Return(5);

    collection.AddHttpPostedFile(httpPostedFile);

    IList<Stream> streams = new StreamHelper().GetStreams(collection);
    streams.Count.ShouldEqual(1);
}

When we execute this test a lot is happening. First I create a mock of the IHttpPostedFile interface so that I can stub the properties. This allows me to test the method without having an actual implementation of the interface. Not that it would have complicated things tremendously, but it's a nice technique.

I also use a convenient helper method to get me a stream. This will come in handy later when I want to verify the outcome of the GetStreams() method.

Let's execute and:

 

------ Test started: Assembly: Koning.WEWLC.Tests.dll ------

TestCase 'Koning.WEWLC.Tests.HttpCollectionTests.can_use_the_customcollection_to_test_the_StreamHelper_class'
failed:
  Expected: 1
  But was:  0
    at Machine.Specifications.NUnitShouldExtensionMethods.ShouldEqual(Object actual, Object expected)
    C:\Dev\Personal\WEWLC\Koning.WEWLC\Koning.WEWLC.Tests\Tests\HttpCollectionTests.cs(59,0): at Koning.WEWLC.Tests.HttpCollectionTests.can_use_the_customcollection_to_test_the_StreamHelper_class()

0 passed, 1 failed, 0 skipped, took 1.37 seconds.

 

Why is this happening? My bad, I didn't implement GetEnumerator() on the custom collection class. This is easily fixed however:

public class CustomHttpFileCollection : NameObjectCollectionBase, IEnumerable
{
    readonly IList<IHttpPostedFile> httpPostedFiles = new List<IHttpPostedFile>();

    public IHttpPostedFile this[string name]
    {
        get { return httpPostedFiles.Where(s => s.FileName == name).FirstOrDefault(); }
    }

    public new IEnumerator<string> GetEnumerator()
    {
        return httpPostedFiles.Select(s => s.FileName).GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }

    public void AddHttpPostedFile(IHttpPostedFile file)
    {
        httpPostedFiles.Add(file);
    }
}

I'm using some Linq goodness to get to the filenames and iterate over that. Next up is refining our test and run it again:

[Test]
public void can_use_the_customcollection_to_test_the_StreamHelper_class()
{
    var collection = new CustomHttpFileCollection();
    var httpPostedFile = MockRepository.GenerateMock<IHttpPostedFile>();
    httpPostedFile.Stub(s => s.InputStream).Return(GetStream());
    httpPostedFile.Stub(s => s.FileName).Return("somefilename.txt");
    httpPostedFile.Stub(s => s.ContentLength).Return(5);

    collection.AddHttpPostedFile(httpPostedFile);

    IList<Stream> streams = new StreamHelper().GetStreams(collection);
    streams.Count.ShouldEqual(1);
    streams.First().Length.ShouldBeGreaterThan(0);
    new StreamReader(streams.First()).ReadLine().ShouldContain("hello world");
}

------ Test started: Assembly: Koning.WEWLC.Tests.dll ------

1 passed, 0 failed, 0 skipped, took 1.48 seconds.

 

Now note that when using the GetStreams() method one would have to transform the items in HttpPostedFileCollection to the IHttpPostedFile interface before using it.

 

 

The Case of the Undetectable Side Effect

Every so often you encounter code that just makes you mumble WTF way more than is healthy for any sane developer. In most cases things just happen everywhere. When the code is performing a query, it's also updating some other pieces, altering the file system a bit and lastly setting a whole bunch of other objects in an invalid state.

I wouldn't recommend getting the debugger up and running to see what's going on. Most of the time it consumes a lot of time and keeps the frustration really high.

What this kind of code is lacking is proper Command Query Separation (CQS). From the WEWLC book "It's a is a design principle first described by Bertrand Meyer. Simply put, it is this: A method should be a command or a query, but not both. A command is a method that can modify the state of the object but that doesn't return a value. A query is a method that returns a value but that does not modify the object."

 

You should always strive to adhere to this principle. It will make your code easier to read and more importantly, easier to skip when reading. When I encounter code that does not adhere to CQS I always split it up in several smaller methods, break out objects etc etc. Once that is done, testing immediately becomes easier on the class.

It's a matter of subclassing and overriding any behavior that is unwanted so that the method you like to test can be tested in isolation.

 

And with the Undetectable side effect covered we end the I can't get this class into a test harness chapter of WEWLC. Hope you enjoyed reading. Drop a line in the comments for feedback, or ideas.

Tom 10:14, 14 September 2009

This is the second posting in the WEWLC-series.

 

Other posts are:

I can't run this method in a test harness

I don't have much time and I have to change it

Assumptions on the reader

 

 

What to do if the system under test is a nasty legacy class that seems impossible to get under test? There are various techniques that can help you with this, let get started with "the case of the irritating parameter".

 

The case of the irritating parameter

When you have a SUT that takes complex objects into it's constructor you can easily circumvent the situation by applying Extract interface on the bothering classes.

After you have created the necessary interfaces you can utilize Rhino Mocks to generate replacement instances (mocks) of the required classes. Rhino Mocks will actually create an proxy instance for the class. Conveniently, you can then set expectations & outcomes on these mocks. So without an actual implementation you fake the system into believing it is dealing with actual classes.

Let have a look on how this works:

 

public class CreditValidator
{
    readonly IDbConnection connection;
    readonly ICreditMaster creditMaster;

    public CreditValidator(IDbConnection connection, ICreditMaster creditMaster)
    {
        this.connection = connection;
        this.creditMaster = creditMaster;
    }
}

public class CreditMaster: ICreditMaster
{
    public CreditInformation GetCreditInformation(Customer customer)
    {
        throw new NotImplementedException();
    }
}

public interface ICreditMaster
{
    CreditInformation GetCreditInformation(Customer customer);
}

First off we create an interface for the CreditMaster class. Once that is done we can start writing the test ask the Rhino MockRepository for an instance of both IDbConnection and ICreditMaster.

 

[TestFixture]
public class CreditValidatorTests
{
    [Test]
    public void can_construct_an_instance_of_the_SUT()
    {
        var connection = MockRepository.GenerateMock<IDbConnection>();
        var creditMaster = MockRepository.GenerateMock<ICreditMaster>();

        var creditValidator = new CreditValidator(connection, creditMaster);
        creditValidator.ShouldNotBeNull();
    }
}

 

This test should not throw an exception, I assert on null just to write a clear test. Run it, and surely enough the test passes.

------ Test started: Assembly: Koning.WEWLC.Tests.dll ------

1 passed, 0 failed, 0 skipped, took 1.35 seconds.

 

 

The Case of the Hidden Dependency

Once you get the class instantiated, we try to use it and bang! Some obscure other complex class is instantiated deep inside and causes the crash. Enter the "case of the hidden dependency". You need to remove newing the class and either move it to a public property or to the constructor. You can then either mock the constructor parameter or set it when you need through the property.

Once you start moving dependencies to the constructor of your classes it quickly starts to make sense to use a Dependency Injection Container. The one I use most frequently is Unity as it's included in EntLib and has several advantages over the other DI-containers available. For one that it's usage it's fairly simple, but even more so that is has Microsoft's backing, often a requirement at the projects I work.

 

Let's have a look at how such a configuration would look like for a hypothetical complex class Repository. First create an interface for the Repository and register it in the BootStrapper. Registration in the Unity container:

public static class BootStrapper
{
    
    public static IUnityContainer GetContainer()
    {
        var container = new UnityContainer();
        container.RegisterType<IRepository, Repository>();
        return container;
    }
}

public class Repository:IRepository
{
}

public interface IRepository
{
}

I prefer to use a static container to resolve dependencies in my applications, like so

public static class StaticContainer
{
    public static T Resolve<T>()
    {
        return BootStrapper.GetContainer().Resolve<T>();    
    }
}

Once the dependency is registered it is simply a matter of retrieving the SUT by requesting the container to construct it. In your tests you can then choose to have the container construct the dependencies or have Rhino Mocks generate the mocks after which you can set expectations on them.

 

The Case of the Construction Blob

If a constructor constructs a large number of objects internally or accesses a large number of globals, we could end up with a very large parameter list. One simple rule is to avoid the construction altogether and move the result of the creation logic into a dependency property. You could then have your DI container inject it at will or inject a mock when used in a test harness.

 

 

The case of the Irritating Global Dependency

In WEWLC, Michael Feathers writes: "Many different kinds of dependency can make it hard to create and use classes in a testing framework, but one of the hardest to deal with is global variable usage."

He's describing the hideous Singleton use in legacy code. Personally I haven't run into problems with a Singleton. Partly, because I didn't write tests at the time I was using them and on the other hand because nowadays I simply ask my DI container for a Singleton when I need it.

Still, Singletons can be a pain in the ass and you should try to avoid them. The whole idea of the singleton pattern is to make it impossible to create more than one instance of a singleton in an application. Because it is, it is particularly hard to fake. What do you do when you encounter one?

Basically you have three options, one is to replace all occurrences in the code; this can be a very tedious job, but with the aid of Resharper, one that I would recommend.

The other is to add a static method to the Singleton that will allow you to pass in a fake. First the lazy Singleton implementation (I have omitted any useful methods for  brevity):

public class PermitRepository
{
    protected PermitRepository() { }

    public static PermitRepository GetInstance()
    {
        return Nested.Instance;
    }

    public static void SetInstance(PermitRepository repository)
    {
        Nested.Instance = repository;
    }

    class Nested
    {
        // Explicit static constructor to tell C# compiler
        // not to mark type as beforefieldinit
        static Nested()
        {
        }

        public static PermitRepository Instance
        {
            get { return instance; }
            set { instance = value; }
        }

        static PermitRepository instance = new PermitRepository();
    }
}

 

 

And to prove that getting multiple calls of the GetInstance() method will return the same object whilst using the SetInstance method will change the instance field the following test:

public class FakePermitRepository : PermitRepository
{
}
[TestFixture]
public class PermitRepositoryTests
{
    [Test]
    public void can_replace_the_PermitRepositoryInstance()
    {
        var repository = PermitRepository.GetInstance();
        int hashCode = repository.GetHashCode();

        hashCode.ShouldEqual(PermitRepository.GetInstance().GetHashCode());

        PermitRepository.SetInstance(new FakePermitRepository());
        PermitRepository.GetInstance().GetHashCode().ShouldNotEqual(hashCode);
    }
}

------ Test started: Assembly: Koning.WEWLC.Tests.dll ------

1 passed, 0 failed, 0 skipped, took 1.35 seconds.

 

The third option is to reset the private instance field of the Singleton and set it to null. First we alter the nested class a bit so that it checks for IsNull() before returning the object:

public class PermitRepository
{
    protected PermitRepository() { }

    public static PermitRepository GetInstance()
    {
        return Nested.Instance;
    }

    public static void SetInstance(PermitRepository repository)
    {
        Nested.Instance = repository;
    }

    public static void Reset()
    {
        Nested.Instance = null;
    }

    public

    class Nested
    {
        // Explicit static constructor to tell C# compiler
        // not to mark type as beforefieldinit
        static Nested()
        {
        }

        public static PermitRepository Instance
        {
            get
            {
                if (instance.IsNull())
                {
                    instance = new PermitRepository();
                }
                return instance;
            }
            set { instance = value; }
        }

        static PermitRepository instance = new PermitRepository();
    }
}

With the test to prove that the newly created Reset() method works as expected:

[Test]
public void can_reset_the_PermitRepositoryInstance()
{
    var repository = PermitRepository.GetInstance();
    int hashCode = repository.GetHashCode();

    hashCode.ShouldEqual(PermitRepository.GetInstance().GetHashCode());

    PermitRepository.Reset();
    PermitRepository.GetInstance().GetHashCode().ShouldNotEqual(hashCode);
}

------ Test started: Assembly: Koning.WEWLC.Tests.dll ------

2 passed, 0 failed, 0 skipped, took 0.93 seconds.

 

The Case of the Onion Parameter

In in many cases, it can be hard to create objects. Especially if they take other object that take other objects in their constructor. Every object needs to be set up in a good state, a state that makes it ready for additional work. This quite closely resembles a fat onion.

Every time when I introduce a DI container to the team I start working with I get the fat onion argument against using a DI container. Due to the steep object graph it becomes impossible to instantiate a class manually without having to instantiate many many others.

I always reply with, why bother. The DI container will take care of it. If you do find it cumbersome, apply Extract interface and inject a mock or a stub and you'll be done with it.

Feathers makes a huge point for simplicity in his WEWLC but with today's ease of use with DI containers I don't consider the argument to be valid anymore.

 

The case the aliased Parameter

If only pieces of a class that is used as a parameter causes problems, we can take another approach. If we subclass the dependency we don't have to create (yet) another interface. I personally have no issues whatsoever with many interfaces in a system as I'm a heavy Resharper user which navigating between classes and interfaces trivial.

When we've subclassed the dependency we can write any behavior we'd like to have in our fake. Obviously my preference would be to fake the class using Rhino Mocks for easy of setup and speed of writing.

 

Right, that concludes my second post on WEWLC, I can't get this class in a test harness. Hope you enjoyed it, let me know what you think.

Tom 12:55, 12 September 2009

Who hasn't been into this position? I think we all know the drill: "we'd like you to do it know and you have until xxx to fix it". How do you approach such a situation? Do you open the source and start hammering code in an unbelievable pace or do you think the changes through, think where you will be invasive and what tests need to be written?

This (long overdue) first post is regarding making those changes. I will assume you have a working understanding about this.

 

Right, let's get started. If you don't have much time and you still need to make the change there are some techniques that let you safely insert / inject code while minimizing the risk of introducing errors.

 

Sprout Method

WEWLC: "When you need to add a feature to a system and it can be formulated completely as new code, write the code in a new method. Call it from the places where the new functionality needs to be"

This is a nice trick in that it will allow you to write the new code in a test harness provided you can instantiate the system under test (SUT).

 

Suppose we a class TransactionGate that is used to post entries. These entries need to have a certain timestamp that is applied before adding the entries to the transactionBundle. 

public class TransactionGate
{
    readonly IList<Entry> transactionBundle = new List<Entry>();

    public void PostEntries(List<Entry> entries)
    {
        entries.ForEach(entry =>
        {
            entry.PostDate();
            transactionBundle.Add(entry);
        });
    }
}

 

Now the requirement is that we check whether an entry is already listed in the transactionBundle before we add it. Fair enough, we change the code to look like this:

public class TransactionGate
{
    readonly IList<Entry> transactionBundle = new List<Entry>();

    public void PostEntries(List<Entry> entries)
    {
        entries.ForEach(entry =>
        {
            entry.PostDate();
            if (!transactionBundle.Contains(entry))
            {
                transactionBundle.Add(entry);    
            }
        });
    }
}

Contrived as it may look like we are actually making the code worse. What if the next day another requirement is to alter the conditional? It would be very tempting to simply add the next bit of code as well making the code start to rot.

A better solution is to use Sprout method. In this case, filter out the entries that are already in the transactionBundle and only add those.

public class TransactionGate
{
    public TransactionGate()
    {
        TransactionBundle = new List<Entry>();
    }

    public IList<Entry> TransactionBundle { get; set; }

    public void PostEntries(IList<Entry> entries)
    {
        var newEntries = FilterEntries(entries);
        newEntries.ForEach(entry =>
        {
            entry.PostDate();
            TransactionBundle.Add(entry);
        });
    }

    IList<Entry> FilterEntries(IEnumerable<Entry> entries)
    {
        return entries
            .Where(s => !TransactionBundle.Contains(s))
            .ToList();
    }
}

It would be trivial simple to unit test the newly created method:

public class TransactionGateTests: ContextSpecification<TransactionGate>
{
    [Test]
    public void when_an_entry_is_added_that_is_already_in_the_transactionBundle_it_should_not_Be_added()
    {
        var transactionGate = new TransactionGate();
        transactionGate.PostEntries(new[] {new Entry(1), new Entry(2)});

        transactionGate.PostEntries(new[]{new Entry(1), });
        transactionGate.TransactionBundle.Count().ShouldEqual(2);
    }
}

------ Test started: Assembly: Koning.WEWLC.Tests.dll ------

1 passed, 0 failed, 0 skipped, took 1.23 seconds.

 

However, if you then create this test:

[Test]
public void when_duplicate_entries_are_added_that_were_not_before_in_the_bundle_only_unique_entries_should_be_added()
{
    var transactionGate = new TransactionGate();
    transactionGate.PostEntries(new[] { new Entry(1), new Entry(1) });
    transactionGate.TransactionBundle.Count().ShouldEqual(1);
}

if fails miserably:

------ Test started: Assembly: Koning.WEWLC.Tests.dll ------

TestCase 'Koning.WEWLC.Tests.TransactionGateTests

.when_duplicate_entries_are_added_that_were_not_before_in_the_bundle_only_unique_entries_should_be_added' failed:
  Expected: 1
  But was:  2
    at Machine.Specifications.NUnitShouldExtensionMethods.ShouldEqual(Object actual, Object expected)
    C:\Dev\Personal\WEWLC\Koning.WEWLC\Koning.WEWLC.Tests\Tests\TransactionGateTests.cs(25,0): at Koning.WEWLC.Tests.TransactionGateTests.

when_duplicate_entries_are_added_that_were_not_before_in_the_bundle_only_unique_entries_should_be_added()

1 passed, 1 failed, 0 skipped, took 1.24 seconds.

 

If you take a look at the initial code we wrote then it becomes obviously clear that there is a huge benefit to writing the code in a new method: the code to PostEntries does not need to change, we only need to correct the code in the GetNewEntriesFrom method.

We now have a test that fails, good! Let's add a Distinct() clause to the filtering code so that the test passes:

public class TransactionGate
{
    public TransactionGate()
    {
        TransactionBundle = new List<Entry>();
    }

    public IList<Entry> TransactionBundle { get; set; }

    public void PostEntries(IList<Entry> entries)
    {
        var newEntries = FilterEntries(entries);
        newEntries.ForEach(entry =>
        {
            entry.PostDate();
            TransactionBundle.Add(entry);
        });
    }

    IList<Entry> FilterEntries(IEnumerable<Entry> entries)
    {
        return entries
            .Distinct()
            .Where(s => !TransactionBundle.Contains(s))
            .ToList();
    }
}

Only a subtle change but one that would not have been obvious if it were not for the tests written.

 

Sprout Class

The mechanics between Sprout Class and Sprout Method are not that different. You use Sprout class if the logic you want to add really belongs in its own separate class. You can also use Sprout Class if the class to alter is difficult to get into a test harness.

 

Wrap Method

When you encounter a method that consists a lot of procedural code it is often easiest to first wrap the existing method into another method. Say we have the Following PayDispatcher class:

public class PayDispatcher
{
    public void Pay(Employee employee)
    {
        //.... a lot of code follows
    }

}

public class Employee
{
}

Suppose we are required to add logging to the Pay method following. With Resharper this extraction is made extremely easy using the key combination CTRL-R, M (Extract method). We first move the code in Pay to DispatchPayment() and then add logging.

 

You will probably end up with something like this:

public class PayDispatcher
{
    public void Pay(Employee employee)
    {
        DispatchPayment(employee);
        LogPayment(employee);
    }

    void DispatchPayment(Employee employee)
    {
        //.... a lot of code follows
    }

    void LogPayment(Employee employee)
    {
        //.... some logging code follows
    }
}

Now, the point here is to see how wrapping the method calls would increase readability and isolation of the changes. Obviously the logging could be done in several other ways.

 

Wrap Class

One of the (many) alternatives would be to completely wrap the logging into a decorator. Let's have a look.

We first have to undo the logging in the original PayDispatcher class:

public class PayDispatcher
{
    public void Pay(Employee employee)
    {
        DispatchPayment(employee);
    }

    void DispatchPayment(Employee employee)
    {
        //.... a lot of code follows
    }
}

We can then write a decorator PayDispatcher that will wrap our existing PayDispatcher and apply the required logging, like so:

public class LoggingPayDispatcher
{
    readonly PayDispatcher payDispatcher;

    public LoggingPayDispatcher(PayDispatcher payDispatcher)
    {
        this.payDispatcher = payDispatcher;
    }

    public void Pay(Employee employee)
    {
        payDispatcher.Pay(employee);
        LogPayment(employee);
    }

    void LogPayment(Employee employee)
    {
        //.... some logging code follows
    }
}
This concludes the various approaches found in WEWLC for "I don't have much time and I have to change it". Hope you liked it, let me know where to improve.
Tijmen 11:16, 12 September 2009

As I will write the translations of the code snippets from the excellent Working Effectively With Legacy Code (WEWLC) book by Michael Feathers I will also assume the following:

  • There is some sort of understanding what mocks are
  • There is some understanding of how Rhino mocks work (if not, you will find out anyway by continue reading this blog)
  • There is some understanding of Dependency injection
  • One knows what TestDriven.net is.
  • One knows why AutoHotKey is used and what you can do with it
  • Some understanding of Reshaper
Tom 10:50, 6 September 2009

Time to start reading again. I've been picking up lot's of noise regarding Kanban lately. This let me to a post of Scott Bellware in which he describes what resources he used to study Lean.

 

This weekend I started with Lean Software Development, An Agile Toolkit by Mary & Tom Poppendieck.. The book is a very pleasant to read introduction into Lean. I will probably write follow-up post when I've completed some more of Scotts list.

 

In the meantime, I'd like to share a peek into my shelfari.

Tijmen 01:06, 4 September 2009

launch_or_activateOne feature of the new Windows 7 SuperBar that I particularly like is the ability to pin applications. This creates a single button that can be used to both launch the application (when it isn't already running) or to activate it if the app was already active. What I like about this concept, is that it expresses the user's wish much better in this way: a button to run Word can now be used to just "give me Word, I don't care if it's already running".

Since I usually work more keyboard- than mouse-centric, I came up with a way to mimic this behavior in AutoHotkey. I wrote a script that offers the following functionality:

  • either start or activate a particular application (based on a shortcut key obviously, this being an AutoHotkey post)
  • if the application is already running, cycle through the active windows (useful for Firefox or Explorer windows)
  • make it easy to "force-launch": force a new instance/window, regardless of whether it was already up and running.
  • give visual feedback on the launched-or-activated application

It took me a little time to work out the AutoHotkey script syntax, especially for dealing with arrays. In the script you set up an array of shortcut information, which serves as a settings registry. It contains the following parts:

  • display label: text that is shown in the visual feedback
  • a (unique) name: this is used to bind that particular command to a hotkey
  • a groupname: if a groupname is given, the script tries to loop through all the windows that match the window ID that is assigned to this entry
  • windowId: set this to the "ahk_class" of the window. You can use Window Spy (right click on any running AutoHotKey script tray icon) to find out this value for each command you want to add to the registry. It will probably work with Windows titles as well, but I never tried this since that method is a lot less reliable.
  • runcommand: the actual command you want the shortcut to point to if it needs to launch the application (for instance, "c:\windows\system32\calc.exe")

Adding a entry goes like this:

;--1. SETUP
;     enter label, name, groupname, windowId, runcommand
AddShortcut("Windows Explorer", "Explorer", "ExplorerGroup", "ahk_class CabinetWClass", "C:\windows\explorer.exe /select,d:" )

The next step involves hooking up the shortcut keys. This is standard AutoHotkey suff, so please refer to the AHK manual for doing this. An example for Explorer and Firefox:

#E::MyNewActivate("Explorer")
+#E::MyRun("Explorer")
F19::MyNewActivate("FF")
+F19::MyRun("FF")

So, Windows key + E does the launch-or-activate trick, whereas Shift + Win + E forces a new Explorer window.

The rest of the script adds some visual eye candy that is in no way functionally necessary, but it gives a nice, semi-transparent window that fades quickly. The three possible windows are shown at the top of this post.

The entire script is listed below; click expand source to view or copy.

#InstallKeybdHook

;--AUTOEXEC SECTION

GroupArrayCount := 0
SetTitleMatchMode 2

;--DISPLAY SETTINGS
;
INITIAL_TRANSPARENCY := 150
DELTA_TRANSPARENCY := 25
INITIAL_DELAY := 400
DELTA_DELAY := 50

;--1. SETUP
;     enter label, name, groupname, windowId, runcommand
;
AddShortcut("Windows Explorer", "Explorer",   "ExplorerGroup", "ahk_class CabinetWClass", "C:\windows\explorer.exe /select,d:" )
AddShortcut("Outlook", "Outlook", "OutlookGroup", "ahk_class rctrl_renwnd32", "C:\Program Files (x86)\Microsoft Office\Office12\outlook.exe")
AddShortcut("Firefox", "FF", "FireFoxGroup", "ahk_class MozillaUIWindowClass", "C:\Program Files (x86)\Mozilla Firefox\firefox.exe" )
AddShortcut("Calculator", "Calculator", "", "ahk_class CalcFrame", "c:\windows\system32\calc.exe")

;--2. ASSIGN KEYS
; win + E does a "run or activate", shift + win + E forces a new window
#E::MyNewActivate("Explorer")
+#E::MyRun("Explorer")

F14::MyNewActivate("Outlook")
F19::MyNewActivate("FF")
+F19::MyRun("FF")

;--Ctrl + Shift + Esc starts Process Explorer (task manager on steroids)
+^Escape::MyNewActivate("PE")
#C::MyNewActivate("Calculator")
;
;--/AUTOEXEC SECTION


; FUNCTION SECTION
GlobalTrans := INITIAL_TRANSPARENCY

;--CloseWin has to be an AHK subroutine, SetTimer doesn't work with functions
;  also note: subroutines do not require the "global" keyword
;             to manipulate global vars
CloseWin:
  If (GlobalTrans <= 0)
  {
    Gui, Destroy  
  }
  else
  {
    WinSet Transparent, %GlobalTrans%, ahk_class AutoHotkeyGUI
    GlobalTrans := GlobalTrans - DELTA_TRANSPARENCY
    ; negative time means run only once
    SetTimer, CloseWin, -%DELTA_DELAY%
  }
return


ShowText(text, textColor)
{
  global
  GlobalTrans := INITIAL_TRANSPARENCY

  Gui, Destroy
  SetTimer, CloseWin, Off
  Gui +LastFound +AlwaysOnTop -Caption +ToolWindow
  Gui, Color, 404040
  Gui, Font, s32
  Gui, Add, Text, c%textColor%, %text%
  SetTimer, CloseWin, -%INITIAL_DELAY%
  Gui, Show, Center NoActivate
  WinSet Transparent, %GlobalTrans%, ahk_class AutoHotkeyGUI
}

AddShortcut(label, key, groupName, windowId, runCommand)
{
  global
  GroupArrayCount += 1
  Labels%GroupArrayCount% := label
  Keys%GroupArrayCount% := key
  if (groupName != "")
  {
    Groups%GroupArrayCount% := groupName
  }
  Ids%GroupArrayCount% := windowId
  Commands%GroupArrayCount% := runCommand
  if (groupName != "")
  {
    GroupAdd %groupName%,%windowId%
  }
}

MyNewActivate(key)
{
  global
  Loop %GroupArrayCount%
  {
    if (key == Keys%A_Index%)
    {
      local thisId := Ids%A_Index%
      local label := Labels%A_Index%
      if WinExist(thisId)
      {
        ShowText("switching to " . label, "Lime")
        local thisGroup := Groups%A_Index%
        if (thisGroup == "")
        {
          WinActivate %thisId%
        }
        else
        {
          GroupActivate %thisGroup%,r
        }
      }
      else
      {
        ShowText("launching " . label, "FF8800")
        local thisCommand := Commands%A_Index%
        run, %thisCommand%
      }
      break ; terminate the lookup
    }
  }
}

MyRun(key)
{
  global
  Loop %GroupArrayCount%
  {
    if (key == Keys%A_Index%)
    {
      local label := Labels%A_Index%
      ShowText("force new " . label, "FF3300")
      local thisCommand := Commands%A_Index%
      run, %thisCommand%
      break ; terminate the lookup
    }
  }
}

Note that line 46 should read If (GlobalTrans <= 0), but the AHK brush for SyntaxHighlighter gets a bit confused here (since the semicolon ";" is also the AHK comment character). I found this brush here.

Tijmen 10:57, 2 September 2009

Every now and then I want to do a simple authentication scheme in an ASP.NET web application, without calling on various providers or other components that bring too much weight & functionality to the table. Implementing a custom IIdentity and IPrincipal is a straightforward way of achieving this.

The steps involved:

  • create a custom implementation of these two interfaces
  • set the custom principal as the user for HttpContext.Current
  • cache the principal in session state (not actually required, but a simple optimization)

Implementing the interfaces

A simple skeleton for the IIdentity implementation:

public class MyIdentity : IIdentity
{
    private string passedInName; 

    // IIdentity
    public string AuthenticationType { get { return "MyIdentityAuthenticationType"; } }
    public string Name { get { return passedInName; } }

    public bool IsAuthenticated
    {
        get
        {
            // TODO: add whatever logic we need here (for instance, AD group membership)
            throw new NotImplementedException();
        }
    }
    // /IIdentity

    // Hide constructor
    private MyIdentity() { }

    // Static factory method
    internal static IIdentity CreateIdentity(IUserNameProvider provider)
    {
        IIdentity identity = new MyIdentity { passedInName = provider.AccountName } ;
        return identity;
    }
}

And for the IPrincipal-implementing class:

public class MyPrincipal : IPrincipal
{
    private IIdentity identity;

    // IPrincipal
    public IIdentity Identity    { get { return identity; } }
    public bool IsInRole(string role)
    {
        // TODO add logic here
        throw new NotImplementedException();
    }

    // hide Ctor
    private MyPrincipal() { }

    // static factory method
    public static IPrincipal CreatePrincipal(IUserNameProvider provider)
    {
        IIdentity identity = MyIdentity.CreateIdentity(provider);
        IPrincipal principal = new MyPrincipal { identity = identity };
        return principal;
    }
}

A few things to note:

  • IUserNameProvider has only a single string property, name. The injected type is used to determine the current user's name.
  • I used simple static factory methods, that are by no means necessary in this context (regular constructors would work just as well).
  • you could factor out the two "business logic" methods IsAuthenticated and IsInRole to separate concerns using the template method pattern, but this is supposed to be a simple, lean implementation.

Hooking them up

The easiest way I've found to link the custom principal is by implementing the Application_AcquireRequestState event in the global.asax:

protected void Application_AcquireRequestState(object sender, EventArgs e)
{
    IPrincipal principal = null;

    var current = HttpContext.Current;

    // check if session is available; needed because this event can/does fire multiple times per request
    if (current.Session != null)
    {
        // check if we have the principal in session
        if (current.Session["magicstring"] != null)
        {
            principal = current.Session["magicstring"] as IPrincipal;
        }
        // catches both (1) key not in session and (2) cast not succesfull
        if (principal == null)
        {
            // create a new one and store it in the session
            principal = MyPrincipal.CreatePrincipal(new MyWebAccountNameProvider());
            current.Session["magicstring"] = principal;
        }

        // regardless of source (session or freshly created, store in appropriate context)
        current.User = principal;
    }
}

Actually, this event is a bit weird, because it can fire multiple times for a single request. The Session reference is only valid once however, which is why that check is there. So, what happens:

  1. The existence of a session variable is checked, and, if it exists, it is cast to an IPrincipal.
  2. If either the cast failed or the session var was empty, a new specific principal is constructed and stored in session.
  3. The custom principal is linked to the HttpContext.Current.User property, allowing us to use it in the rest of the application.

Wrapup and comments

This is by no means a do-all, end-all solution, but it works well. Depending on the tiering/layering of the solution, you can either check the HttpContext.Current.User property, or you can abstract that into a simple wrapper. I usually either use a static method on my principal that returns the actual active principal, or set up a context registry to hold my principal reference transparently across layers.

Tijmen 02:22, 28 August 2009

I've been working a lot with stored procedures and the Linq to Sql designer. One of the annoyances is that all of a sudden when you drop the nth sproc to the designer it would not allow creating the codebehind anymore. It'll then throw the most usefull message:

"The operation could not be completed"

There's an easy fix however, open a Visual Studio command prompt and hit

"devenv /resetskippkg"

 

Works like a charm.

Tijmen 08:50, 17 August 2009
I am sure I ran into this before, but it took me some time to figure out yet again. Something like that always shouts "blog it" to me, so here goes. I installed a ClickOnce application, that neatly installed itself and placed an appropriate shortcut in my start menu. I then fired up Launchy, rebuilt the catalog and started looking for the new app... which didn't show up.
Searching through the start menu using standard Windows functionality of win-key + start typing (which admittedly got a lot better and snappier in Windows 7, though nowhere near powerful enough for us pro-keystrokers) resulted in the correct shortcut, though.
Long story short: the ClickOnce shortcuts have an extension *.appref-ms. By adding that file type to the various directories that Launchy indexes (right click, options, catalog tab) and rebuilding the catalog, the shortcuts show up in Launchy as well. By the way, on my Windows 7 machine, the start menu shortcuts are in the following folders (I am not sure if Launchy sets those correctly from the start):
  • c:\ProgramData\Microsoft\Windows\Start Menu
  • c:\users\<username>\AppData\Roaming\Microsoft\Windows\Start Menu