This last week Jeff Schumacher and I have been working on a fairly complex set of business logic driving the entire design from the outside in with specification style unit tests. In an effort to help our tester get a head start validating the logic and assumptions in our code we promised to create a simple UI. Jeff has some WPF experience, so I suggested we do a simple WPF application and he can show me his “XAML Fu”. I have yet to get beyond playing with XAML, so having a little toy project and pairing with someone who has some experience already is a great way to get your feet wet. I also suggested we use Calibun.Micro and awesome little library Rob Eisenberg that brings convention over configuration for WPF applications to the table. So we pulled down the library and cracked open Rob’s Soup to Nuts series of tutorials.

In part two of his series, Rob describes how to override Caliburn.Micro’s default Bootstrapper with a custom implementation using the Managed Extensibility Framework. At work we use Castle Windsor, so we followed along with the tutorial injecting Castle magic at the appropriate spots.

To provide a custom bootstrapper for Caliburn.Micro, you simply inherit from the Bootstrapper<T> where T is your shell view model and then override the GetInstance, GetAllInstances and BuildUp methods providing your own implementation. With the exception of the BuildUp method, they pretty much line up perfectly with Castle Windsor’s interface allowing you to simply wrap it. The BuildUp method is used to perform property injection on an already created instance, Castle Windsor does property injection by default on resolution of your types and does not explicitly expose a build up method. This is easily overcome by adding an extension method to the container to provide that service.

public static class WindsorExtensions
    {
       
        public static void BuildUp(this IWindsorContainer container, object instance)
        {
           instance.GetType().GetProperties()
                .Where(property => property.CanWrite && property.PropertyType.IsPublic)
                .Where(property => container.Kernel.HasComponent(property.PropertyType))
                .ForEach(property => property.SetValue(instance, container.Resolve(property.PropertyType), null));
        }
    }

The bootstrapper then looks like this:

public class CastleBootstrapper : Bootstrapper
    {
        private ApplicationContainer container;

        protected override void Configure()
        {
            container = new ApplicationContainer();
        }

        protected override object GetInstance(Type service, string key)
        {
            if (string.IsNullOrWhiteSpace(key))
                return container.Resolve(service);

            return container.Resolve(key);
        }

        protected override IEnumerable GetAllInstances(Type service)
        {
            return (IEnumerable) container.ResolveAll(service);
        }

        protected override void BuildUp(object instance)
        {
            container.BuildUp(instance);
        }
    }
}


The ApplicationContainer class is simply inherits from WindsorContainer, I like to seperate out my component registration from my bootstrapping code. It looks something like this:

public class ApplicationContainer : WindsorContainer
    {
        public ApplicationContainer()
        {
           
            Register(
                    Component.For().ImplementedBy().LifeStyle.Is(LifestyleType.Singleton),
                    Component.For().ImplementedBy().LifeStyle.Is(LifestyleType.Singleton)
           );

            RegisterViewModels();
        }

        private void RegisterViewModels()
        {
            Register(AllTypes.FromAssembly(GetType().Assembly)
                         .Where(x => x.Namespace.EndsWith("ViewModels"))
                         .Configure(x => x.LifeStyle.Is(LifestyleType.Singleton)));
        }
    }

This code is all that is needed to get the sample application from the tutorials to work with Castle Windsor.


 
Categories: Development | Tools

We use the amazing TopShelf to setup and configure our windows services. It makes it a snap to install your windows service into the service control manager. Simply issue the following commands against your exe and it is installed or uninstalled:

MyAwesomeService.exe /install
MyAwesomeService.exe /uninstall

This makes deployment pretty brain dead, but we want to make the process even easier by including a deployment installer. As mentioned previously, creating a installer with Wix# is a snap. And performing actions during the install couldn’t be simpler.

Here is the simple build definition for my current project:

public BuildResult Build()
        {
            WixObject[] installables = GetInstallables();
            var project = new Project(string.Format(ProductName, buildEnvironment.Version), installables)
                              {
                                  GUID = ProductId,
                                  MSIFileName = string.Format(ProductName, buildEnvironment.Version),
                                  UI = WUI.WixUI_ProgressOnly,
                                  Manufacturer = Manufacturer,
                                  SourceBaseDir = buildEnvironment.OutPutDirectory,
                                  AutoAssignedInstallDirPath = InstallPath,
                                  Properties = GetProperties(),
                                  Actions = GetActions()
                              };

            string message = Compiler.BuildMsi(project);

            return new BuildResult { WasSuccessful = true, Message = message };
        }

Notice, I set the project’s Actions property to the value returned by the method GetActions(). This is how I execute my install and uninstall commands during the installation process. The implementation of the method looks like this:

private Action[] GetActions()
        {
            return new[]
                       {
                           new InstalledFileAction("SomeCompany.SomeProduct.Service.exe", "/install", Return.check,
                                                   When.After, Step.InstallFinalize, Condition.NOT_Installed),
                           new InstalledFileAction("SomeCompany.SomeProduct.Service.exe", "/uninstall", Return.check,
                                                   When.Before, Step.InstallFinalize, Condition.Installed)
                       };
        }

And in the words of my good friend and coworker Eric Ridgeway, “That’s hot.”


 
Categories: Learning in Public | Tools

Here at Russell we have a fairly strict deployment story. As you can imagine with any financial company, when dealing with other people’s money mistakes are punishable by death. Having a failed rollout because your 37 page install document wasn’t completely accurate and left out some minor detail that prevented the server administrator from continuing is a pretty big mistake.

To mitigate this risk, we as developers try to control and automate as much of our deployments as possible. Some of the strategies we use include:

  • Automated build that produces a deployment package that is rigorously tested for completeness
  • A single rollout script to be run in SQL server that is tested with every build
  • Heavy use of PowerShell scripts to automate complex tasks like setting up MSMQ queues
  • Deployment of applications using MSI installers built with Wix

Wix or Windows Installer XML, is a great tool for creating very high quality, professional looking installers. The down side is that it has a learning curve steeper than Everest and suffers from severe angle bracket tax. It is not uncommon to struggle for several days trying to get a Wix based MSI to do all the little things you want it to accomplish for you.

To get over these hurdles you need a solid foundation of knowledge and a really nice abstraction layer. Kevin Miller has laid out the solid foundation for us in his series from 2007 called Creating Windows Installers Using WIX. I highly suggest reading it and walking through your own project using the raw Wix model.

When you are done with that, let me introduce you to a really nice abstraction layer. Oleg Shilo’s Wix# project allows you to define your installation package in C#, you know, a general purpose programming language that is designed to model real world processes. Not a markup language like XML. Seriously, if I could go back to 2001 and find the guy that decided that XML was the solution to all problems and beat him senseless, I would.

Go back to Mr. Miller’s great articles and compare his Wix XML to this:

using System;
using WixSharp;
  
class Script 
{
    static public void Main(string[] args)
    {
        var project = new Project("MyProduct",
                          new Dir(@"%ProgramFiles%\My Company\My Product",
                              new Files(@"Release\*.*”));
 
        project.GUID = new Guid("6f330b47-2577-43ad-9095-1861ba25889b");
 
        Compiler.BuildMsi(project);
    }
}

This is the simplest possible use of Wix#, but 8 lines of code damn sure beats the gratuitous ceremony of using Wix XML directly. Mr. Shilo’s project comes out of the box with 39 samples that demonstrate using this tool kit to do everything from creating virtual directories in IIS to editing the registry to forcing a reboot after installation. And there is a great introduction to the project on CodeProject.

It is difficult to tell how active the development is on Wix#, but Mr. Shilo does have the full source available from the projects page. I would be interested in seeing this project move out to a public repository like GitHub and seeing more community involvement. What do you say, Oleg? Let’s blow the roof off this mofo!


 
Categories: Learning in Public | Tools

JP Boodhoo of the Nothing But .NET Boot Camp fame released a really great introduction video to the Machine.Specifications BDD test framework.

Machine.Specifications Part 1 from Jean-Paul Boodhoo on Vimeo.


 
Categories: Development | Tools

If you are considering switching your project over to using VS2010 but still targeting the 3.5 sp1 framework here is a list of things to be aware of.

Tools:

  • Resharper 5.0 RTM’d last night, but the upgrade is $149 or $89 depending on what you have now
  • TD.NET 3.0 is a beta but it is working fine for me
  • WIX 3.5 is a beta and will make modifications to your .wixproj file
  • Could lead to build failures, have not had time to explorer yet

Solution & Proj Files:

  • Solution file changed only in that the version number on the first line is incremented to 11
    • You can change it to 10 and it will open fine in vs2008
    • If you want to use both vs2010 and vs2008 you will need two sln files
  • Normal DLL csproj projects have a few new nodes added but open and compile fine in vs2008
  • Web Project files have the same new nodes
    • The reference to Microsoft.WebApplication.targets msbuild file is changed to the vs2010 version
      • This change is most likely to support the new deployment stuff in 2010
      • Changing it back will cause vs2010 to prompt a migration again
      • This change causes my current build script to fail when performing a publish
  • The data base project file dbp appears to no longer be supported and is replaced by the dbproj file

At a minimum you will need to upgrade your build server to .net 4.0 and your team members will need to have it as well due to the web project file changes.


 
Categories: Development | Tools

Well here we are on Thursday and I am finally posting Tuesday’s video. When I started doing this I had no idea how long it would take to produce one of these videos. I have a pretty good idea now. ;)

In this installment I cover conventions, both ClassMap conventions and AutoMap conventions. I slowly convert the ClassMap implementation over to AutoMap by leaning on default convention and then adding my own as needed. This demonstration should give you a firm understanding of how conventions work in Fluent NHibernate.


 
Categories: Development | Fluent Interface | NHibernate | Tools

Hello Tuesday! Wait a minute this is Monday’s video. That’s right I spent so much time on Monday producing the Introduction video and planning the ClassMaps video, I didn’t get around to making Monday’s until Tuesday. But hey I am on vacation what are you expecting from me really?

So, today I am covering the topic of ClassMaps in Fluent NHibernate. I used Steve Bohlen’s Summer of NHibernate code from session 9 as a starting place. In this video you will see me get the code running on my machine, upgrade it to NHibernate 2.1.0 GA and then convert it over to using ClassMaps. The video clocks in at just over 30 minutes. Enjoy.


 
Categories: Development | Fluent Interface | NHibernate | Tools

Inspired by Steve Bohlen’s Summer of NHibernate screencast series, I thought I would spend some of my vacation creating an addendum to it called Vacation of Fluent NHibernate.

Links from the Screencast:


 
Categories: Development | Fluent Interface | NHibernate | Tools

Kata Potter is an interesting problem intended to be used as a learning exercise in TDD. The problem is described like this:

Once upon a time there was a series of 5 books about a very English hero called Harry. (At least when this Kata was invented, there were only 5. Since then they have multiplied) Children all over the world thought he was fantastic, and, of course, so did the publisher. So in a gesture of immense generosity to mankind, (and to increase sales) they set up the following pricing model to take advantage of Harry's magical powers.

One copy of any of the five books costs 8 EUR. If, however, you buy two different books from the series, you get a 5% discount on those two books. If you buy 3 different books, you get a 10% discount. With 4 different books, you get a 20% discount. If you go the whole hog, and buy all 5, you get a huge 25% discount.

Note that if you buy, say, four books, of which 3 are different titles, you get a 10% discount on the 3 that form part of a set, but the fourth book still costs 8 EUR.

Potter mania is sweeping the country and parents of teenagers everywhere are queuing up with shopping baskets overflowing with Potter books. Your mission is to write a piece of code to calculate the price of any conceivable shopping basket, giving as big a discount as possible.

I have been working on solving this kata over the last couple weeks. One goal I had was to understand how Machine.Specifications (MSpec for short) fits in to the BDD development process. MSpec is a framework written by Aaron Jensen that sits on top of your current unit testing framework (as long as you happen to be using NUnit or XUnit). You can read Aaron’s introduction to MSpec here where he does a much finer job at explaining it that I can.

My goal with MSpec was to be able to define the acceptance criteria for Kata Potter before writing a single line of implementation code. MSpec also has the added benefit of allowing me to execute my acceptance criteria on the code as it evolves and report back on my progress. With MSpec I can express what the system under test must do to satisfy all the requirements.

So given MSpec’s utility I started out to write a set of requirements based on the Kata Potter description.

  • Given a cart containing a single book when the price is calculated it should return the full price of the book.
  • Given a cart containing two different books when the price is calculated it should return the price of both books with a 5% discount applied.
  • Given a cart containing three different books when the price is calculated it should return the price of all books with a 10% discount applied.
  • Given a cart containing four different books when the price is calculated it should return the price of all books with a 20% discount applied.
  • Given a cart containing five different books when the price is calculated it should return the price of all books with a 25% discount applied.

This covers the full set of books, but the kata gives us another example:

  • Given a cart containing four books where two are the same title when the price is calculated it should return price of three books discounted by 10% and the full price of the fourth.

Using MSpec I can express these requirements in an executable fashion like this:

using Machine.Specifications;

namespace Kata.Potter.CoreTests.Specifications
{
    [Subject("calculating discount prices")]
    public class when_calculating_the_price_of_a_book
    {
        It should_return_the_full_price_of_the_book;
    }

    [Subject("calculating discount prices")]
    public class when_calculating_the_price_of_two_different_books
    {
        It should_apply_a_five_percent_discount;
    }

    [Subject("calculating discount prices")]
    public class when_calculating_the_price_of_three_different_books
    {
        It should_apply_a_ten_percent_discount;
    }

    [Subject("calculating discount prices")]
    public class when_calculating_the_price_of_four_different_books
    {
        It should_apply_a_twenty_percent_discount;
    }

    [Subject("calculating discount prices")]
    public class when_calculating_the_price_of_five_different_books
    {
        It should_apply_a_twenty_five_percent_discount;
    }

    [Subject("calculating discount prices")]
    public class when_calculating_the_price_of_four_books_where_two_are_the_same
    {
        It should_apply_a_twenty_percent_discount_to_three_of_the_books;
    }
}

With out a single line of code implementing these specifications, I can even execute my tests. I get the following display in the ReSharper test runner:

KataSpecs

Notice that the runner ignores all my tests currently returning the message that the specifications are “Not implemented”. As I write code to satisfy the requirements, the tests will being to go red and then green as each specification is implemented.

The next step in this process is to begin identifying collaborators in the system. Based on the requirements I know that I need objects that represent a Book, a Shopping Cart and a Calculator that calculates the price of all the books in the cart. I’ll begin by creating shell classes that I can use to wire up my specifications to implementation code.

public class Book
    {
        public Book(string title, decimal price)
        {
            Title = title;
            Price = price;
            IsDiscounted = false;
        }

        public string Title { get; private set; }
        public decimal Price { get; set; }
        public bool IsDiscounted { get; set; }
    }

    public class Cart
    {
        public Cart()
        {
            Books = new List<Book>();
        }

        public IList<Book> Books { get; private set; }

        public void AddBook(Book book)
        {
            Books.Add(book);
        }
    }

    public class PriceCalculator
    {
        public decimal CalculatePriceFor(Cart cart)
        {
            return 0;
        }
    }

With this simple implementation, I can now modify my MSpec specifications to exercise these objects. I’ll start with the first one to give you the feel of what it looks like.

[Subject("calculating discount prices")]
    public class when_calculating_the_price_of_a_book
    {
        private static Cart cart;
        private static PriceCalculator calculator;
        private static decimal price;

        Establish context = () =>
                                {
                                    cart = new Cart();
                                    cart.AddBook(new Book("Book 1", 8M));
                                    calculator = new PriceCalculator();
                                };
        Because of = () => price = calculator.CalculatePriceFor(cart);               

        It should_return_the_full_price_of_the_book = () => price.ShouldEqual(8);
    }

First, I establish my specification’s context by newing up my Cart and PriceCalculator classes and adding a single book to the cart. This establishes the environment that the test will run in which matches the name of the class pretty closely. I am calculating the price of a single book. Next, I clearly call out what action is performed to test against. I tell the calculator to calculate the price for the given cart. Finally, I make assertions on the state of my context objects. For this specification, all I need to do is validate that the calculated price is equal to the price of the book.

If I execute my specifications now, this spec will turn from ignored to red. I have now implemented the collaborators and weaved them into specifications to be validated. Here is what shows up in the ReSharper runner:

kataspecs2

The next thing we need to do is fill in the rest of the specifications and make them all turn red as well. If I do this following the pattern of the test we already have I am going to create a lot of duplicated code. Each specification class will have the same private members and most of the context as well. So first I am going to pull those elements out into a base class and refactor my first specification like so:

    public class with_price_calculator
    {
        protected static Cart cart;
        protected static PriceCalculator calculator;
        protected static decimal price;
        protected static decimal correctPrice;

        Establish context = () =>
                            {
                                cart = new Cart();
                                calculator = new PriceCalculator();
                            };
    }

    [Subject("calculating discount prices")]
    public class when_calculating_the_price_of_a_book : with_price_calculator
    {
        Establish context = () =>
                                {
                                    cart.AddBook(new Book("Book 1", 8M));
                                };
        Because of = () => price = calculator.CalculatePriceFor(cart);               

        It should_return_the_full_price_of_the_book = () => price.ShouldEqual(8);
    }

One of the cooler features of MSpec is the way it chains delegates together during execution. Notice that my base class has an Establish statement and my specifcation class has one as well. The specification class inherits from the base class but it does not override the Establish statement. Instead MSpec will execute all the Establish statements in the inheritance chain from the “base-ist” to the “descended-ist”. I can now implement the remaining specification quickly like this:

    public class with_price_calculator
    {
        protected static Cart cart;
        protected static PriceCalculator calculator;
        protected static decimal price;
        protected static decimal correctPrice;

        Establish context = () =>
                            {
                                cart = new Cart();
                                calculator = new PriceCalculator();
                            };
    }

    [Subject("calculating discount prices")]
    public class when_calculating_the_price_of_a_book : with_price_calculator
    {
        Establish context = () =>
                                {
                                    cart.AddBook(new Book("Book 1", 8M));
                                };
        Because of = () => price = calculator.CalculatePriceFor(cart);               

        It should_return_the_full_price_of_the_book = () => price.ShouldEqual(8);
    }

    [Subject("calculating discount prices")]
    public class when_calculating_the_price_of_two_different_books : with_price_calculator
    {
        Establish context = () =>
        {
            cart.AddBook(new Book("Book 1", 8M));
            cart.AddBook(new Book("Book 2", 8M));
            correctPrice = 8*2 - (8*2*.05M);
        };

        Because of = () => price = calculator.CalculatePriceFor(cart);

        It should_apply_a_five_percent_discount = () => price.ShouldEqual(correctPrice);
    }

    [Subject("calculating discount prices")]
    public class when_calculating_the_price_of_three_different_books : with_price_calculator
    {
        Establish context = () =>
        {
            cart.AddBook(new Book("Book 1", 8M));
            cart.AddBook(new Book("Book 2", 8M));
            cart.AddBook(new Book("Book 3", 8M));
            correctPrice = 8 * 3 - (8 * 3 * .1M);
        };

        Because of = () => price = calculator.CalculatePriceFor(cart);

        It should_apply_a_ten_percent_discount = () => price.ShouldEqual(correctPrice);
    }

    [Subject("calculating discount prices")]
    public class when_calculating_the_price_of_four_different_books : with_price_calculator
    {
        Establish context = () =>
        {
            cart.AddBook(new Book("Book 1", 8M));
            cart.AddBook(new Book("Book 2", 8M));
            cart.AddBook(new Book("Book 3", 8M));
            cart.AddBook(new Book("Book 4", 8M));
            correctPrice = 8 * 4 - (8 * 4 * .2M);
        };

        Because of = () => price = calculator.CalculatePriceFor(cart);
        It should_apply_a_twenty_percent_discount = () => price.ShouldEqual(correctPrice);
    }

    [Subject("calculating discount prices")]
    public class when_calculating_the_price_of_five_different_books : with_price_calculator
    {
        Establish context = () =>
        {
            cart.AddBook(new Book("Book 1", 8M));
            cart.AddBook(new Book("Book 2", 8M));
            cart.AddBook(new Book("Book 3", 8M));
            cart.AddBook(new Book("Book 4", 8M));
            cart.AddBook(new Book("Book 5", 8M));
            correctPrice = 8 * 5 - (8 * 5 * .25M);
        };

        Because of = () => price = calculator.CalculatePriceFor(cart);

        It should_apply_a_twenty_five_percent_discount = () => price.ShouldEqual(correctPrice);
    }

    [Subject("calculating discount prices")]
    public class when_calculating_the_price_of_four_books_where_two_are_the_same : with_price_calculator
    {
        Establish context = () =>
        {
            cart.AddBook(new Book("Book 1", 8M));
            cart.AddBook(new Book("Book 2", 8M));
            cart.AddBook(new Book("Book 3", 8M));
            cart.AddBook(new Book("Book 3", 8M));
            correctPrice = (8 * 3 - (8 * 3 * .1M)) + 8;
        };

        Because of = () => price = calculator.CalculatePriceFor(cart);

        It should_apply_a_ten_percent_discount_to_three_of_the_books = () => price.ShouldEqual(correctPrice);
    }

Note that I have added another member to the base class to capture what I think the correct price should be to then use as an assert later on. Executing my specifications now show all red. I can continue implementing functionality using traditional TDD or by writing more specifications for each collaborator using the same techniques.

Next time, I will cover the actual implementation that solves the kata potter that I arrived at through this process.


 
Categories: Development | Tools | Unit Testing

During the Olympia Software Craftsmanship Workshop last weekend, Jeff Olsen (@olsonjeffery) demonstrated the use of the web testing framework Selenium. I was really impressed with the Selenium IDE and how easy it was to use in Firefox. One of the menu items of the IDE is to export a test as C#.

Export

This piqued my curiosity and I wanted to find out exactly what it takes for a .NET developer to get started using Selenium. This post is intended to help others get started.

First, a list of the stuff you will want to download:

You can get started right away by simply downloading the Selenium IDE for Firefox. There is a great tutorial here that will guide you through getting started. The other downloads are not required to use the IDE.

If you want to integrate your tests into your build process or write tests as if they were unit tests, you will need the two asterisked items at a minimum. The Selenium Remote Control comes in two parts. There is a server that runs under the Java Runtime Environment and several Client libraries for just about any flavor of programming you may prefer.

SeleniumRC

As, you can see I have added a batch script to launch the server on my local machine. The file contains a single command:

"C:\Program Files (x86)\Java\jre6\bin\java.exe" -jar selenium-server-1.0\selenium-server.jar

If you run the batch script, this is what you will see.

SeleniumRunning

Selenium is now listening on its default port of 4444 for commands from the client library. The server portion of Selenium can run anywhere. It would be fairly easy to set it up to run on a VM or on your build server with minimal effort.

So now let's write some tests. This blog has a built in administrative system. After you authenticate, a link bar is displayed with the various administrative tasks. A simple set of specifications, might look like this:

  1. When authenticating with valid credentials, the configuration menu link should be present.
  2. When authenticating with invalid credentials, the configuration menu link should not be present.

Let's start by creating a new test assembly. I called mine NotMyself.Blog.Specifications. Simply create a new Class Library and call it what ever you want. Next add references to nmock, nunit.core, nunit.framework and ThoughtWorks.Selenium.Core located in the selenium-dotnet-client-driver-1.0 folder in the Selenium Remote Control distribution.

References

I am not sure if there is a direct dependency on nmock or nunit for that mater. ThoughtWorks.Selenium.Core.dll is the meat & potatoes here. In a future post, I'll try getting up and running with MSTest or MBUnit.

To execute against the Selenium Server, we need to do some set up. The following base class demonstrates what is needed.

using System;
using System.Text;
using NUnit.Framework;
using Selenium;

namespace NotMyself.Blog.Specifications
{
public class SeleniumTestContext
{
protected ISelenium browser;
protected StringBuilder verificationErrors;

[SetUp]
public void SetupTest()
{
browser = new DefaultSelenium("localhost", 4444, "*iexplore", "http://iamnotmyself.com/");
browser.Start();
verificationErrors = new StringBuilder();

Context();
BecauseOf();
}

public virtual void Context() { }
public virtual void BecauseOf() { }
[TearDown]
public void TeardownTest()
{
try
{
browser.Stop();
}
catch (Exception)
{
// Ignore errors if unable to close the browser
}
Assert.AreEqual("", verificationErrors.ToString());
}
}
}

The above class sets up a couple fields and then news up a DefaultSelenium object. This object takes four constructor parameters; the URL hosting the Selenium Server, the port the server is running on, a string that represents the browser we want the tests run in (in this case IE, but we could use "*chrome" to use FireFox) and finally the root URL of the site we are testing.

Next up let's create a context for our authentication tests.

namespace NotMyself.Blog.Specifications
{
internal class AuthenticationContext : SeleniumTestContext
{
protected string authenticationUrl = "/notreallythe/pathtomy/page.aspx";
protected string badPassword = "reallynotmypassword";
protected string goodPassword = "notreallymypassword";
protected string userName = "notreallymyusername";
}
}

This class simply allow me to share some information across multiple test classes. Finally we are ready to write our tests.

using NUnit.Framework;

namespace NotMyself.Blog.Specifications
{
[TestFixture]
public class When_Authenticating_With_Valid_Credentials : AuthenticationContext
{
public override void BecauseOf()
{
browser.Open(authenticationUrl);
browser.Type("LoginBox_username", userName);
browser.Type("LoginBox_password", goodPassword);
browser.Click("LoginBox_doSignIn");
browser.WaitForPageToLoad("30000");
}

[Test]
public void The_Configuration_Menu_Link_Should_Be_Present()
{
Assert.IsTrue(browser.IsElementPresent("_ctl6_hyperLinkEditConfig"));
}
}

[TestFixture]
public class When_Authenticating_With_Invalid_Credentials : AuthenticationContext
{
public override void BecauseOf()
{
browser.Open(authenticationUrl);
browser.Type("LoginBox_username", userName);
browser.Type("LoginBox_password", badPassword);
browser.Click("LoginBox_doSignIn");
browser.WaitForPageToLoad("30000");
}

[Test]
public void The_Configuration_Menu_Link_Should_Not_Be_Present()
{
Assert.IsFalse(browser.IsElementPresent("_ctl6_hyperLinkEditConfig"));
}
}
}

These tests simply issue commands as if it were interacting directly with the browser telling it to open a URL, type some text into form fields, click a button. Validation works the same way, I interrogate the browser to see if specific elements exist.

Finally, all we have to do is fire up the Selenium Server by running the batch script, load up our test assembly into our favorite test runner and watch the tests execute. If you are running the Selenium Server locally you can sit back and watch the browser fire up and the tests execute right before your eyes. Very cool.

TestResults


 
Categories: Development | Tools | Unit Testing

How did they go from version 1.0 of Entity Framework directly to 4.0?

Anyway, here is a nice overview of the new model first story that Microsoft has baked into the new EF in Visual Studio 2010.

After having watched this I have upgraded my impression of EF from “Complete Garbage” to “Not Entirely Horrifying”.

The RAD editor gives me pause as that is a sure sign of generating garbage behind the scenes. Is it human readable/modifiable?

The original EDMX format was incredibly brittle and very anti-source control system friendly. Have they made improvements to that?

I’ll have to play with it this weekend and see what it is like to actually build a simple app with it.

It is nice to see that MS is listening and at least attempting to play catch up with nHibernate. Would be interesting to do a feature by feature comparison between the two.


 
Categories: Random | Tools

I am a OSS enthusiast and want to use tools like nHibernate in my daily application development practices. What I am not is a CIO or Architect at my company. There are several roadblocks, misconceptions and valid concerns that are raise when I suggest using an OSS tool in one of our projects. One of the biggest concerns I have heard is that of responsibility. The question usually is phrased like this:


"When we encounter a blocking bug what do we do?"


The overwhelming OSS response to this is: "Fix it yourself and submit a patch." And this is where I lose management. Management doesn't want to take on the responsibilities of fixing platform bugs. In their eyes it is much easier to purchase packages from vendors who take on those responsibilities. The role of tools like nHibernate, Ninject or even Prism in my environment is to allow me to focus on business value and functionality. We are not a platform company.


I want to find a solution to this problem, and I think it falls down to money. My company is willing to pay good money to a vendor for a tool that allows us to deliver business value quickly. I wonder if that same cash flow relationship could be applied to OSS.

Say, I have to make a choice between vendor Product X and nHibernate for ORM. Product X requires a license fee of $1000 per developer. I chose nHibernate and put my $1000 per developer in the bank as a emergency fund.

Six months later, I encounter a bug or blocking problem in nHibernate that is going to prevent me from releasing my product. I can't fix it myself. I do not have the time or the skill needed to do so. I create a test case for the problem and submit it with a portion of my emergency fund to the community for a solution.

My question is, do you think anyone would accept it? What if we wanted them to be contractually obligated to fix the bug upon acceptance? Is anyone out there currently doing this? Would any of the current developers want to do this? Is this a viable alternative to vendor software here?

So here is a list of the OSS tools I would like to use. Anyone out there willing to commit to saying, "Yes, if you can provide me with a test case, I can provide you with a fix for that OSS tool. I charge $X amount per hour or this flat fee."

  • nHibernate
  • Fluent nHibernate
  • Castle Winsor
  • Ninject
  • Rhino.Security
  • Prism
  • MVC Contrib
  • Caliburn

If your particular pet OSS project is not listed, I would still like to hear from you. This list came of the top of my head from what I am currently interested in.


 
Categories: Development | Tools

My company is investigating a dramatic shift in our product offering. We are looking at offering a SAAS product delivered via Silverlight. Our current offering is a large scale  classic ASP.NET case management system that is installed on site with the client and heavily customized. Our SAAS application is intended to start as a scaled down version of this application.

One of our main goals was to produce a highly modularized application that has been described as "simple widgets of functionality" that are driven by tasks instead of long menu trees. Our source of inspiration is the iPhone and it's clean interface.

Using the amazing Balsamiq, I generated a couple mock ups of a possible UI. I needed something concrete to work toward while learning WPF & Silverlight and modifying my mind set from stateless web mentality.

Desktop 

Side Note: Balsamiq is AWESOME. If you have not tried it go now and do it this blog post will wait.

These high level vision statements lead me down the path of a component based UI. I have had a copy of the Composite Application Guidance for WPF sitting on my desk for a couple of months, so I thought I would give that a chance. I then created a separate version of my mock up that described the areas and their function with in the context of a "desktop" screen.

areas

I then downloaded Prism & Unity and with a copy of Silverlight 2 in Action, I began my journey into the bowels of XAML and figuring out exactly how layout works. After a day or so of discovery with the Canvas, Grid & StackPanel controls I came up with this. It's a fairly simple layout consisting of five rows and a hidden control for user notifications. Working with XAML was very difficult for me at first as I wanted to resist table based layouts like the plague due to my HTML bigotry. But once I gave in, I started making progress.

One goal I had was to explore Prism's Region types and how they interact with the UI. In my application shell I had defined regions for each of the major areas of the UI and I wanted to create a "Place Holder" view that I could populate each of the regions with that would give me some information at runtime.

Following the Prism sample code, I created a ApplicationModule class which would represents the Applications role in the UI modularity. This module is the first to load and set default values within the application before moving on to interrogate other assemblies for other modules. One thing the application module does is to set all regions to a default place holder view like so:

 

public class ApplicationModule : IModule
{
private readonly IUnityContainer container;
private readonly IRegionManager regionManager;
private readonly IRegionViewRegistry regionViewRegistry;

public ApplicationModule(IUnityContainer container,
IRegionManager regionManager,
IRegionViewRegistry regionViewRegistry)
{
this.container = container;
this.regionManager = regionManager;
this.regionViewRegistry = regionViewRegistry;
}

#region IModule Members

public void Initialize()
{
RegisterTypesAndServices();
RegisterViewsWithRegions();
}

private void RegisterViewsWithRegions()
{
//registering placeholders with current regions
this.regionManager.RegisterViewWithRegion(RegionNames.Branding,
() => this.container.Resolve().View);
this.regionManager.RegisterViewWithRegion(RegionNames.Menu,
() => this.container.Resolve().View);
this.regionManager.RegisterViewWithRegion(RegionNames.Breadcrumb,
() => this.container.Resolve().View);
this.regionManager.RegisterViewWithRegion(RegionNames.Content,
() => this.container.Resolve().View);
this.regionManager.RegisterViewWithRegion(RegionNames.SystemNotification,
() => this.container.Resolve().View);
this.regionManager.RegisterViewWithRegion(RegionNames.UserNotification,
() => this.container.Resolve().View);

}

private void RegisterTypesAndServices()
{
this.container.RegisterType();

}

#endregion
}

I then wanted my place holder view to display a bit of information about its current context. Specifically I wanted the view to tell me what region it belonged to and its current dimensions. The XAML for this is not even worth looking at, it's a user control with a text block. The problem I ran into was getting any kind of information about the current context of the user control. My first attempt lead me to the VisualTreeHelper class and this code:

 

var parent = VisualTreeHelper.GetParent(this) as FrameworkElement;
this.PlaceHolderText.Text = parent.Name ?? "Placeholder";

 

This basically left me with a blank screen. Interesting enough the parent of my user control was not the region that contained it but a stack panel with no name that is not even defined in the XAML. It appears that the region is not a UI element so much as a concept within prism. After a couple hours of working with this I was stumped and hit the twitterverse to see if Glenn Block might offer a suggestion.

Glenn was the PM at Microsoft for the Composite Application Guidance for WPF. Seriously his name features prominently on the Authors page. If anyone could point me in the right direction, it would be this guy. It was somewhat of an obvious noob question, but I was very focused on the application DOM. He suggested that I check out the RegionManager.

After fiddling around with the region manager I came up with this:

public partial class PlaceholderView : UserControl, IPlaceholderView
{
private IRegionManager regionManager;

public PlaceholderView(IRegionManager regionManager)
{
InitializeComponent();
this.regionManager = regionManager;
}


private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
foreach (IRegion region in regionManager.Regions)
{
foreach (UserControl view in region.Views)
{
if (view == this)
{
PlaceHolderText.Text =
string.Format("{0} PlaceHolder : {1}x{2}",
region.Name, view.RenderSize.Width, view.RenderSize.Height);
return;
}
}
}
}
}

 

This almost has me there. For some reason, I get the correct width of the region my user control is inhabiting but the height always reports as zero. I am sure it has to do with how I have structured my application shell and plan to track this one down today.

In the end, I really like Silverlight. Prism allowed me to put something together fast based on a mock up and has DI baked in in a nice way.


 
Categories: Development | Tools

January 27, 2009
@ 08:45 AM

So I have been living with my Mac Book Pro for a couple months now. I have purposely tried to use OSX for day to day things to force myself to get used to the OS. Here is a nice list of the applications that I have found useful so far.

This list is in no way targeted at long time Mac fans. Instead it is intended for newb/converts like me who are getting used to a whole new environment of software.

Quick Silver – Awesome tool for launching applications or finding documents. Simply hit Ctrl+Space and start typing what it is you want.. QuickSilver will display a list of items that match what you are typing. Once you have typed a set of letters and selected something QuickSilver will learn what you wanted and begin suggesting that thing faster… for example I can type Ctrl-Space, VM, Enter and launch VM Ware…. It’s a cool app.

Adium – Multi-Service messaging client very similar to Pigden. Can connect to MSN, ICQ, AOL, Facebook, GTalk, MySpace and many others.

Colloquy – Pretty straight forward IRC client if you are into that sort of thing.

Remote Desktop Mac – This combined with with VPN connection to work is awesome. There is pretty much nothing I can't do now with my Mac and a network connection.

Twitterrific – Simple twitter client if you are into that sort of thing.

MonoDevelop – Mono is the open source implementation of the .NET framework. MonoDevelop a IDE for developing using Mono. If you ever wondered what it would be like without Visual Studio here you go.

Skype – Skype…

VMWare Fusion – Virtual Machine goodness…

XCode – The free IDE for developing on the Mac. Want to make a IPhone app? Here you go. Objective C is fun… really it is…

Bonus Tips: Be sure to enable Spaces via the Expose & Spaces menu. This lets you have the sliding desktop effect that I use all the time. A neat keyboard combo is Function+F8, this displays all your spaces on the screen and you can click one to go to that space. Expose is Function+F8 this will shrink all the windows on your screen and lay them out so that you can see them all. Then click the window you want and they all go back where they were with the one you selected in focus.

Bonus Bonus Tip: The World of Warcraft Mac client runs like a champ on my MBP. ;)
 

Categories: Commentary | Random | Tools

Programming Visual Basic applications?

Typemock have released a new version of their unit testing tool, Typemock Isolator 5.2.
This version includes a new friendly VB.NET API which makes Isolator the best Isolation tool for unit testing A Visual Basic (VB) .NET application.

Isolator now allows unit testing in VB or C# for many ‘hard to test’ technologies such as SharePoint, ASP.NET MVC, partial support for Silverlight, WPF, LINQ, WF, Entity Framework, WCF unit testing and more.

Note that the first 25 bloggers who blog this text in their blog and tell us about it, will get a Free Full Isolator license (worth $139). If you post this in a VB.NET dedicated blog, you'll get a license automatically (even if more than 25 submit) during the first week of this announcement.

Go ahead, click the following link for more information on how to get your free license.


 
Categories: Shameless Plug | Tools | Unit Testing

December 5, 2008
@ 07:41 AM
using System;
using System.Reflection;

namespace AllianceEnterprises.TestTools
{
public static class ReflectionHelper
{
public static void SetPrivateField(object item, string fieldName, object value)
{
item.GetType()
.GetField(fieldName, BindingFlags.NonPublic | BindingFlags.Instance)
.SetValue(item, value);
}

public static void SetStaticField(string fieldName, object value)
{
typeof (T).GetField(fieldName, BindingFlags.NonPublic | BindingFlags.Static)
.SetValue(null, value);
}
}
}

 
Categories: Blogging | Random | Tools

November 24, 2008
@ 08:14 PM

Well, I finally did it. I went over to the darkside and picked up a 15" MacBook Pro and a copy of VMWare Fusion. I got the box home and had a Bootcamp partition with Windows 2008 Workstation installed within an hour. Install Visual Studio 2008 and I was ready to do some development in one Space while working on Keynote presentations in another.

My journey though Mac software beings. I sit here now typing this up in a very nice blog post editor called Ecto. It's all good.

Look for more post as I explore the developer tools on the Mac.


 
Categories: Development | Random | Tools

Yesterday, my team had a developer forum session to assist one our own get our latest release to build on our build server from a new branch. He had been working on it for a couple days and was getting nowhere. He would follow our documented process to create the new build and when he got to the end of it the build threw the following error:

The path C:\Build\ProductReleases\FullBuildv5.4.2x\Sources is already mapped to workspace BuildServer_23.

We used the Team Explorer IDE and attempted to identify this rogue workspace. Try as we might we couldn't locate it. We tried deleting all the source code on the file system. We tried nuking all the workspaces we could see through the IDE.

In the end we had seven developers in a room shouting out ideas to a frustrated developer sitting the keyboard. So we broke for lunch.

After lunch, I returned to my desk to troll the MSDN Team Foundation Server Developer Center. Using the tf workspaces command, you can get a list of all the workspaces you have created:

C:\>tf workspaces

Server: BuildServer
Workspace Owner          Computer Comment
--------- -------------- -------- --------
BOBBY     work\Bobby 	 BOBBY

But if you add the owner switch, you can get a list of all the workspaces on the server:

C:\>tf workspaces /owner:*

Server: BuildServer
Workspace      Owner      Computer  Comment
-----------    ---------- --------- -------------------------------
BuildServer    Shane      BuildServer
BuildServer    Craig      BuildServer
BuildServer    TFSSETUP   BuildServer
BuildServer    Keith      BuildServer
BuildServer_1  TFSSERVICE BuildServer  Workspace created by Team Build
BuildServer_10 TFSSERVICE BuildServer  Workspace created by Team Build
BuildServer_12 TFSSERVICE BuildServer  Workspace created by Team Build
BuildServer_13 TFSSERVICE BuildServer  Workspace created by Team Build
BuildServer_14 TFSSERVICE BuildServer  Workspace created by Team Build
BuildServer_16 TFSSERVICE BuildServer  Workspace created by Team Build
BuildServer_2  TFSSERVICE BuildServer  Workspace created by Team Build
BuildServer_23 TFSSERVICE BuildServer  Workspace created by Team Build
BuildServer_28 TFSSERVICE BuildServer  Workspace created by Team Build
BuildServer_3  TFSSERVICE BuildServer  Workspace created by Team Build
BuildServer_30 TFSSERVICE BuildServer  Workspace created by Team Build
BuildServer_31 TFSSERVICE BuildServer  Workspace created by Team Build
BuildServer_32 TFSSERVICE BuildServer  Workspace created by Team Build
BuildServer_4  TFSSERVICE BuildServer  Workspace created by Team Build
BuildServer_6  TFSSERVICE BuildServer  Workspace created by Team Build
BuildServer_7  TFSSERVICE BuildServer  Workspace created by Team Build
BuildServer_8  TFSSERVICE BuildServer  Workspace created by Team Build
BuildServer_9  TFSSERVICE BuildServer  Workspace created by Team Build

From this output we can see that our build service user TFSSERVICE has a lot of workspaces defined. Considering we have 3 builds so far. Something is very wrong here.

Our original error message referenced a workspace named BuildServer_23 which does show up in our list. Using the tf workspace command, we can completely remove the workspace:

C:\>tf workspace /delete /server:BuildServer BuildServer_23;TFSSERVICE
A deleted workspace cannot be recovered.
Workspace 'BuildServer_23;TFSSERVICE' on server 'BuildServer' has 0 pending change(s).
Are you sure you want to delete the workspace? (Yes/No) Y

Our build now runs as expected. It's now time to verify what all those other workspaces are and remove them if they are not needed.

Hope this helps someone out there if you are desparately googling for away around this error.


 
Categories: Development | Tools

The application I am currently working on has a hand rolled implementation of Ajax that is somewhat awkward to work with. At the end of our last sprint, I was tasked with spiking what it would take to migrate to the .NET Ajax 1.0 extensions while everyone else was working on release week tasks.

It took a couple days to figure out all the installs, web.config modifications, component vendor compatibility and other various things. But in the end, I had a simple page with two sample Ajaxified controls that worked.

I then turned to the task of unraveling the way the current implementation was wired up and modifying a single page to use the Ajax framework instead. A few minor safe refactorings and quirks later, I had a semi-functional reference implementation with one giant problem.

The page contained a series of drop down lists that filter each other as you make selections. On initial page load, I could select an item any drop down and it would appropriately modify the others. The second selection always returned the following error:

Sys.WebForms.PageRequestManagerServerErrorException: An unknown error occurred while processing the request on the server. The status code returned was: 404

Reguardless of what list I selected from first, the second request would fail. My IIS logs revealed that my request was being sent to server, but for whatever reason the URL changed.

2008-10-17 14:52:14 W3SVC1 127.0.0.1 POST /Aware/Xtend/mParticipant/NewPlannedService.aspx  80 - 127.0.0.1 200 0 0

2008-10-17 14:52:20 W3SVC1 127.0.0.1 POST /Aware/mParticipant/NewPlannedService.aspx  80 - 127.0.0.1 404 0 0

Using Fiddler, I was able to see that a value for formAction was being sent back to the client that was invalid. You can also see that the second request is going to a non-existent page:

FiddlerOutPut

I was able to resolve the issue by explicitly setting the value of my forms action back to the correct path at the end of my call back method like so:

this.Form1.Action = Request.Url.PathAndQuery

But this seemed like a hack in the worst way and smelled somewhat like moldy cheese to me. And I still didn't understand what was causing the issue.

The application makes extensive use of Server.Transfer as a "performance enhancement". I noticed that the form I was working with was one of these cases where Page1.aspx transfers execution to my Ajaxified page.

I decided to try to isolate the behavior and reproduce it in a simple example project.

I fired up Visual Studio and created a new Ajax website. I added two pages; Default.aspx and AjaxPage.aspx. I implemented a simple ajax call back on my ajax page and the default page transfer execution in its Page_Load method.

To my surprise, it worked with no problems. I didn't see the nasty error at all. I verified with Fiddler. I was stumped.

I started thinking about the behavior in my application. The only difference I could think of was that the page that was being transferred to was in a different subdirectory than the original page. So I created a folder in my test project and moved AjaxPage.aspx into it. And this time I got the error. I confirmed with Fiddler that my "Folder" sub directory was being dropped off the second request and that it was missing from the response from the first request.

My smelly cheese hack worked as well for my test project. But I didn't want to solve this issue with a server side hack. So I created the following client side Javascript to hook into the client ajax framework and solve it there in a single place:

var orginalFormAction = null;

//capture the current form action value
function BeginRequestHandler() {
  orginalFormAction = theForm.action;
}

//set the form action value back to the
//correct value
function EndRequestHandler() {
  theForm.action = orginalFormAction;
  theForm._initialAction = orginalFormAction;
}

function RegisterRequestHandlers() {

  if (typeof (Sys) != "undefined") {
  
    Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
    Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(BeginRequestHandler);
    Sys.Application.notifyScriptLoaded();
    
  }
}

//register request handlers after the application 
//has successfully loaded.
Sys.Application.add_load(RegisterRequestHandlers);

I can then add the script to any ajax page, by adding the following code to my Page_Load event handler:

protected void Page_Load(object sender, EventArgs e)
    {
      PageScriptManager.Scripts.Add(
        new ScriptReference("~/Script/Ajax.Server.Transfer.Fixer.js")
        );
    }

Problem solved and I didn't have to rewrite the entire application to get rid of Server.Transfer calls. On to other things.

Fiddler Tip: To get Fiddler to capture traffic when you are debugging on local host, after you hit F5 to begin degugging change the address so that localhost has a "." after it. For instance, you start debugging and the you have the following URL in the Address bar: http://localhost:49573/Default.aspx Change it to http://localhost.:49573/Default.aspx hit enter and Fidder will start picking up your traffic.


 
Categories: Development | Tools

Introduction

As you may have noticed, I have become interested in the concept of Object Relational Mapping and the NHibernate framework. One of the more painful/tedious aspects of using NHibernate is hand writing the xml mapping files. That is why I got excited when I heard that Jeremy Miller was open sourcing his mapping generation libraries.

FHLogo The Fluent NHibernate project is an effort to create a set of APIs that generate NHibernate mapping files using a fluent interface. I downloaded the source code from the Google Code Repository and quickly found myself adding fluent methods. I submitted my changes to the project and was accepted as a contributor.

One of the tasks identified by the project owner, James Gregory, was to create a quick start guide that easily fit into the NHibernate Quick Start section 1.3 Mapping the cat. I assigned the task to myself and start hacking some code.

Creating the Mapping Class

First, create a new class project QuickStart.Domain to hold  domain model objects that need to be mapped. To this assembly,  add the Cat class from the NHibernate quick start.

namespace QuickStart.Domain
{
    public class Cat
    {
        public virtual string Id { get; set; }

        public virtual string Name { get; set; }

        public virtual char Sex { get; set; }

        public virtual float Weight { get; set; }
    }
}

This is what the class looks like after a little ReSharper Code Clean Up loving.

Then add a second class project QuickStart.Domain.Mapping to hold  domain model mapping classes using the Fluent NHibernate library. Add references to both the FluentNHibernate.dll and the domain model library.

Create a new class in the mapping library called CatMap. This class will inherit from ClassMap<T> where T is the type you are creating the map for, in this case Cat. Create a constructor for the CatMap class. The constructor is where the mappings will be defined.

Because CatMap is an instance of ClassMap, you can begin using the fluent interface in the constructor right away.

public CatMap()
        {
            this.TableName = "Cat";
        }

The TableName property of the ClassMap object specifies the name of the table in the data store that stores the Cat class. This explicit setting of the table name is unnecessary. If one is not provided the API will assume the table has the same name as the class being mapped. So, for the rest of this example, it will be dropped.

The API offers several fluent methods for defining an identifier though the Id method of ClassMap. The Cat example uses the UUID generator which looks like this:

 

public CatMap()
        {           
            this.Id(x => x.Id)
                .GeneratedBy
                .UuidHex("B");
        }
 

An identity column in SQL server would be mapped like this:

public CatMap()
        {
            Id(x => x.Id);
        }

These two examples take advantage of the new C# 3.0 syntax sugar lambda expressions. An explanation of lambda expressions is outside the scope of this article, but  tons of information is available on the topic on the web.

The remainder of the CatMap constructor uses the Map method of ClassMap to define the remaining properties of the class.

public CatMap()
        {
            this.TableName = "Cat";
           
            this.Id(x => x.Id)
                .GeneratedBy
                .UuidHex("B");

            //non-nullable string with a length of 16
           this.Map(x => x.Name)
                .WithLengthOf(16)
                .CanNotBeNull();

            //simple properties
            this.Map(x => x.Sex);
            this.Map(x => x.Weight);
        }

Both the Sex and Weight properties of the Cat class are mapped quickly with a single call to them Map method. You do not need to explicitly specify the type of your properties, Fluent NHibernate will infer it based on the type being mapped. The Name property has an additional two fluent calls to limit the length of the property to sixteen characters and to disallow null values.

Usage of this mapping generates the following XML document:

<?xml version="1.0" encoding="utf-8"?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" 
  default-lazy="false" 
  assembly="QuickStart.Domain" namespace="QuickStart.Domain">
  <class name="Cat" table="Cat" xmlns="urn:nhibernate-mapping-2.2">
    <id name="Id" column="Id" type="String" unsaved-value="0">
      <generator class="uuid.hex">
        <param name="format">B</param>
      </generator>
    </id>
    <property name="Weight" column="Weight" type="Single">
      <column name="Weight" />
    </property>
    <property name="Sex" column="Sex" type="Char">
      <column name="Sex" />
    </property>
    <property name="Name" column="Name" length="16" type="String" not-null="true">
      <column name="Name" />
    </property>
  </class>
</hibernate-mapping>

This mapping xml is a bit more verbose than the original example from the NHibernate quick start, but this post is being written using an alpha version of the Fluent NHibernate library. There is a lot of clean up and work left to be done.

Hooking It All Up

So, how exactly did I go from CatMap to generated XML document? There is currently no recommended methodology that I am aware of, but I am happy to share how I accomplished it.

I started by adding an interface to the Mapping library called IMapGenerator that looks like this:

namespace QuickStart.Domain.Mapping
{
    public interface IMapGenerator
    {
        string FileName { get; }
        XmlDocument Generate();
    }
}

 

FileName is defined in the fluent interface on the ClassMap class, I know I added it while writing this code ;). It represents the conventional name for the NHibernate mapping files. For example, We are mapping the class Cat so FirstName would contain the string "Cat.hbm.xml". Generate on the other hand, will be a wrapper around the ClassMap's CreateMapping method.

I then added the interface to the CatMap class. The final CatMap looks like this:

namespace QuickStart.Domain.Mapping
{
    public class CatMap : ClassMap<Cat>, IMapGenerator
    {
        public CatMap()
        {
             Id(x => x.Id)
                .GeneratedBy
                .UuidHex("B");

            Id(x => x.Id);

            //non-nullable string with a length of 16
            Map(x => x.Name)
                .WithLengthOf(16)
                .CanNotBeNull();

            //simple properties
            Map(x => x.Sex);
            Map(x => x.Weight);
        }
        
        public XmlDocument Generate()
        {
            return CreateMapping(new MappingVisitor());
        }
    }
}

 

I now have a way to identify all my mapping classes using the interface. I wanted to be able to automatically get a list of all the classes that implement the IMapGenerator interface, so  created a helper class GeneratorHelper with a single static method GetMapGenerators. The class lives in the Mapping library and looks like this:

namespace QuickStart.Domain.Mapping
{
    public class GeneratorHelper
    {
        private const string GENERATOR_INTERFACE = "IMapGenerator";

        public static IList<IMapGenerator> GetMapGenerators()
        {
            IList<IMapGenerator> generators = new List<IMapGenerator>();
            Assembly assembly = Assembly.GetAssembly(typeof(IMapGenerator));
            foreach (Type type in assembly.GetTypes())
            {
                if (null == type.GetInterface(GENERATOR_INTERFACE)) continue;
                var instance = Activator.CreateInstance(type) as IMapGenerator;
                if (instance != null)
                    generators.Add(instance);
            }
            return generators;
        }
    }
}

This method uses reflection to locate and load the assembly that contains the IMapGenerator interface. It then iterates over the types in the loaded assembly and checks to see if the type implements the IMapGenerator interface. If a match is found, an instance of that class is created and added to the generators list.

Finally, I created a console application, QuickStart.Domain.Mapping.Mapper, and added a reference to my Mapping library. The implementation of my console app is fairly straight forward.

 

namespace QuickStart.Domain.Mapping.Mapper
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            IList<IMapGenerator> generators =
                GeneratorHelper.GetMapGenerators();
            
            foreach (IMapGenerator generator in generators)
            {
                XmlDocument classMapXML = generator.Generate();
                classMapXML.Save(generator.FileName);
            }
        }
    }
}

 

The app calls the generator helper class to get a list of IMapGenerator objects which it then iterates over calling each objects Generate method and saves the result using the conventional name for mapping files. It works fairly well and I can add as many mapping classes as I need to the Mapping library and spin out xml any time I need.

Now where Fluent NHibernate becomes really interesting is when you decide to do away with xml mapping files all together. For a great example of this check out Zachariah Young's post, "Does the Fluent NHibernate create static XML mapping files?".


 
Categories: Development | Fluent Interface | NHibernate | Tools

At the end of yesterdays internal study group meeting, the organizer mentioned that I would be giving a presentation on NHibernate the following week. I plan to give a simple dog and pony show of persisting a simple object to the database and all of the setup needed to accomplish the task.

One of the participants asked for a brief description of NHibernate. I explained that it is an ORM framework (Object Relational Mapping). I expanded a bit by saying that NHibernate removes the dependency between your domain objects and your relational database by handling mapping from one to the other.

After a couple more questions it was determined that NHibernate generates SQL and is therefore inferior to stored procedures. It was the general feeling that stored procedures were the be all end all for performance and optimization. I attempted to explain that NHibernate generates parameterized queries which have all the advantages of cached query plans that stored procedures do. By this time the meeting was breaking up and I had a mission.

I wanted to challenge the dogmatic urban legend passed down from .NET developer to .NET developer since the classic ASP days. That dogma simply states you should always access your database via stored procedure for "performance reasons". Inline SQL is BAAAAAAD.

So I fired up Visual Studio, created a class and started writing tests.

The first thing I wanted to do was to create a baseline. I created a User table in a fresh SQLExpress database and wrote a test to pop 1000 rows into it in the crustiest "I just read my first Wrox book" way I could think of. I added some timing code and let it rip. The test looks like this:

 

       [Test]
        public void Time_Inline_Inserts_To_User_Table()
        {
            DateTime start = DateTime.Now;

            using (SqlConnection c = new SqlConnection(connectionString))
            {
                c.Open();
                for (int i = 0; i < INSERT_COUNT; i++)
                {
                    using (SqlCommand co = new SqlCommand())
                    {
                        co.Connection = c;
                        co.CommandText =
                            "INSERT INTO dbo.Users "
                            + "(Handle, FirstName, LastName, Password, EmailAddress, LastLogon) "
                            + "VALUES ("
                            + "'UserHandle" + i + "',"
                            + "'UserFirstName" + i + "',"
                            + "'UserLastName" + i + "',"
                            + "'UserPassword" + i + "',"
                            + "'User" + i + "@email.com',"
                            + DateTime.Now.ToShortDateString() + ")";

                        co.ExecuteNonQuery();
                    }
                }
                c.Close();
            }
            DateTime end = DateTime.Now;
            TimeSpan time = end - start;

            Console.WriteLine(
                string.Format("{0} milliseconds to run {1} inserts by inline query", 
                time.TotalMilliseconds, INSERT_COUNT));
        }

From a fresh load of my test assembly into MbUnit, this code takes 1312.5 milliseconds to run 1000 inserts. Running the test repeatedly drops the time to 437.5 miliseconds. It appears that SQL Server does some optimizations for inline inserts regardless of what the tribe tells me.

Next up, I wanted to see if parameterizing the query would improve the performance. The test case looks like this:

        [Test]
        public void Time_Parameterized_Query_Inserts_To_User_Table()
        {
            DateTime start = DateTime.Now;

            using (SqlConnection c = new SqlConnection(connectionString))
            {
                c.Open();
                for (int i = 0; i < INSERT_COUNT; i++)
                {
                    using (SqlCommand co = new SqlCommand())
                    {
                        co.Connection = c;
                        co.CommandText =
                            "INSERT INTO dbo.Users (Handle, FirstName, LastName, Password, EmailAddress, LastLogon) VALUES (@p1,@p2,@p3,@p4,@p5,@p6)";
                        co.CommandType = System.Data.CommandType.Text;
                        co.Parameters.AddWithValue("@p1", "UserHandle" + i);
                        co.Parameters.AddWithValue("@p2", "UserFirstName" + i);
                        co.Parameters.AddWithValue("@p3", "UserLastName" + i);
                        co.Parameters.AddWithValue("@p4", "UserPassword" + i);
                        co.Parameters.AddWithValue("@p5", "User" + i + "@email.com");
                        SqlParameter param = new SqlParameter("@p6", SqlDbType.DateTime);
                        param.Value = new DateTime(2000, 1, 1);
                        co.Parameters.Add(param);

                        co.ExecuteNonQuery();

                    }
                }
                c.Close();
            }

            DateTime end = DateTime.Now;
            TimeSpan time = end - start;

            Console.WriteLine(
                string.Format("{0} milliseconds to run {1} inserts by parameterized query", 
                    time.TotalMilliseconds, INSERT_COUNT));

        }

This test runs in 1296.9 milliseconds on a fresh load of my test assembly. Repeated runs drops the test run to ~350 milliseconds a slight advantage over the inline query. I imagine this gap would widen with a more complex query.

Finally, we have the acclaimed SQL Stored Procedure dogmatic method of how everything should be done! The stored procedure in the code below is pretty much exactly what you expect it to be.

       [Test]
        public void Time_Stored_Proceedure_Inserts_To_User_Table()
        {
            DateTime start = DateTime.Now;

            using (SqlConnection c = new SqlConnection(connectionString))
            {
                c.Open();
                for (int i = 0; i < INSERT_COUNT; i++)
                {
                    using (SqlCommand co = new SqlCommand())
                    {
                        co.Connection = c;
                        co.CommandText = "AddUser";
                        co.CommandType = CommandType.StoredProcedure;
                        co.Parameters.AddWithValue("@p1", "UserHandle" + i);
                        co.Parameters.AddWithValue("@p2", "UserFirstName" + i);
                        co.Parameters.AddWithValue("@p3", "UserLastName" + i);
                        co.Parameters.AddWithValue("@p4", "UserPassword" + i);
                        co.Parameters.AddWithValue("@p5", "User" + i + "@email.com");
                        SqlParameter param = new SqlParameter("@p6", SqlDbType.DateTime);
                        param.Value = new DateTime(2000, 1, 1);
                        co.Parameters.Add(param);

                        co.ExecuteNonQuery();

                    }
                }
                c.Close();
            }

            DateTime end = DateTime.Now;
            TimeSpan time = end - start;

            Console.WriteLine(
                string.Format("{0} milliseconds to run {1} inserts by stored proceedure", 
                    time.TotalMilliseconds, INSERT_COUNT));

        }

This test runs unexpectedly in 1390.6ms. This seems like quite a long time for a stored procedure that is stored in the database and from my understanding with a query plan in place. Subsequent executions of the test yield execution times ~320ms. Just to verify this, I closed the MbUnit test runner application and reran these tests. I got the same results.

Now that we have a baseline of the various direct SQL methods that are well accepted in the .NET community, I want to see how NHibernate performs at these tasks. I see two methods available though NHibernate spinning up a session and cramming User objects into its Save() method and adding a transaction into the mix.

My first NHibernate test looks like this:

       [Test]
        public void Time_NHibernate_Inserts_To_User_Table()
        {
            DateTime start = DateTime.Now;
            using (ISession session = factory.OpenSession())
            {
                for (int i = 0; i < INSERT_COUNT; i++)
                {
                    User u = new User();
                    u.Handle = "UserHandle" + i;
                    u.FirstName = "UserFirstName" + i;
                    u.LastName = "UserLastName" + i;
                    u.Password = "UserPassword" + i;
                    u.EmailAddress = "User" + i + "@email.com";
                    u.LastLogon = DateTime.Now;

                    session.Save(u);

                }
                session.Close();

            }

            DateTime end = DateTime.Now;
            TimeSpan time = end - start;

            Console.WriteLine(
                string.Format("{0} milliseconds to run {1} inserts by nhibernate", 
                    time.TotalMilliseconds, INSERT_COUNT));

        }

This test runs in 1656.3ms with reruns clocking in at ~560ms. It looks like NHibernate might have a slight performance hit when compared to stored procedures.

My last test using NHibernate transactions looks like this:

       [Test]
        public void Time_NHibernate_Tansaction_Inserts_To_User_Table()
        {
            DateTime start = DateTime.Now;
            using (ISession session = factory.OpenSession())
            {

                ITransaction transaction = session.BeginTransaction();
                for (int i = 0; i < INSERT_COUNT; i++)
                {
                    User u = new User();
                    u.Handle = "UserHandle" + i;
                    u.FirstName = "UserFirstName" + i;
                    u.LastName = "UserLastName" + i;
                    u.Password = "UserPassword" + i;
                    u.EmailAddress = "User" + i + "@email.com";
                    u.LastLogon = DateTime.Now;

                    session.Save(u);

                }
                transaction.Commit();
                session.Close();

            }

            DateTime end = DateTime.Now;
            TimeSpan time = end - start;

            Console.WriteLine(
                string.Format("{0} milliseconds to run {1} inserts by nhibernate with transaction", 
                    time.TotalMilliseconds, INSERT_COUNT));

        }

This test runs in 1406.3ms with follow up runs in 300ms. A dramatic increase in performance over over the non transactional processing. So the final performance test results looks something like this:

Test 1st Run nth Run
Inline SQL 1312.5ms ~430ms
Parameterized Query 1296.9ms ~350ms
Stored Procedure 1390.6ms ~320ms
NHibernate 1565.3ms ~560ms
NHibernate w/Transaction 1406.3ms ~300ms

I am not going to try to interpret these results, but simply publish them and see what feedback I get from the collective. My next steps are to increase the complexity of what I am doing; add some joins into the mix. I want to see if the performance gap widens or a clear winner emerges.

If you would like to see the entire code base for these tests, I have published them to my CodePlex repository and would love to hear your ideas on squeezing out performance with both SQL and NHibernate. Look for the NHibTester solution.


 
Categories: Performace | Tools | Unit Testing

In a recent post, I discovered a flaw in my world domination plot. I had written a Unit Test to test my expectation that the method GetByID() of the class UserRepository returned the expected User. When UserRepository.GetById() is called, it calls IDataProvider.GetById(), which returns an instance User to the UserRepository which in turn returns it to the caller.

My UserRepository class delegates database access to the interface IDataProvider. This allows me to substitute any implementation of IDataProvider to satisfy this responsibility. In non testing code I use Dependancy Injection to map UserDataProvier to IDataProvider. But in testing code I do not really want to hit a database as it slows the testing process down. So I use Rhino.Mocks instead.

Rhino.Mocks is a framework for creating mock objects for use in Unit Testing. Provide Rhino.Mocks with an Interface and it will give you back an object that implements that interface. You can also tell it to expect certain calls against the interface and how it should respond.

My Unit Test looked something like this:

      [Test]
        public void GetByIdTest()
        {
            MockRepository mock = new MockRepository();

            IDataProvider dataProvider = (IDataProvider)mock.CreateMock<IDataProvider>();
            UserRepository target = new UserRepository(dataProvider);

            Expect.Call(dataProvider.GetById(1)).Return(new User() { Id = 1 });

            mock.ReplayAll();
            User u = target.GetById(1);
            mock.VerifyAll();

            Assert.AreEqual(1, u.Id);
        }

As you can see this test, creates a MockRepository that is provided by the Rhino.Mocks framework. It then declares an instance of IDataProvider but delegates the creation of that instance to the MockRepository's CreateMock method. This tells Rhino.Mocks to create a dummy instance of the IDataProvider interface. Next we new up a UserRepository (the actual target of the unit test) and provide our mocked IDataProvider to it's constructor. Then we tell Rhino.Mocks to expect a call to our mock IDataProvider's GetById method and to return a new instance of User with it's Id property set to 1. Finally, we do our testing and validation.

This test fails to compile. The entity class User has read only properties. Id happens to be one of them. In the domain model for this particular application Id is a unique identifier and once a User instance is returned from the data access layer, it should never be modified.

So this presents a unique challenge, how do I test that UserRepository.GetById(1) returns an instance of User with an Id of 1?

I went down the path of trying to use Ninject (an Inversion of Control container), to inject the value in a newed up instance. But this had code smell for me. Why am I creating a dependency on Ninject to get my Unit Tests to work. That just seemed wrong to me. So I began digging in the Rhino.Mocks documentation wiki to see if it had a method for resolving this.

That was when Aiden Montgomery in the #ALT.NET IRC channel suggested that I use Reflection. He even went so far as to download my source from CodePlex and demonstrate what he was suggesting in my application.

The final test ended up looking something like this:

[Test]
        public void GetByIdTest()
        {
            MockRepository mock = new MockRepository();
            
            Type userType = typeof(User);
            PropertyInfo pi = userType.GetProperty("Id");
            User user = new User();
            pi.SetValue(user, 1, null);

            IDataProvider dataProvider = 
                (IDataProvider) mock.CreateMock<IDataProvider>();
            UserRepository target = new UserRepository(dataProvider);

            Expect.Call(dataProvider.GetById(1)).Return(user);

            mock.ReplayAll();
            User u = target.GetById(1);
            mock.VerifyAll();

            Assert.AreEqual(1, u.Id);
        }

 

This of course passed, didn't add a non-BCL dependency and maintained the original intent of the test and the domain model. With all the shiny new toys, I was forgetting to see the forest through the trees and return to the simplest solution. Thanks to Aiden for bringing me back down from the clouds.


 
Categories: Development | Tools | Unit Testing

Stephen Bohlen of Microdesk recently posted to the ALT.NET mailing list that he plans to release his internal training material on NHibernate to the world at large. The first two, of a planned  5, are online and ready for consumption.


I have been doing some noodling with NHibernate recently, so I downloaded the screen casts and watched them this morning. The quality is excellent, the material is comprehensive and Stephen's teaching style is top notch.

If you are interested in learning what NHibernate is all about and what you can do with it, I cannot recommend these enough. Grab them here:


 
Categories: Development | Fundamentals | Tools

I have been reading a ton of the ALT.NET bloggers and mailing list lately. They are constantly talking about the methodology of software development and the tools they use. On the concept front Domain Driven Design, Inversion of Control, Separation of Concerns and Test Driven Development are all popular topics that have been stewing in my mind. I also wanted to give some of the tools like Nhibernate, Rhino.Mocks and Ninject a try. I was also itching to get into the new Microsoft ASP.NET MVC code.

For the last couple months, I have been festering in the swamp of legacy VB.NET spaghetti code and haven't had the time or motivation to write something fresh just for the sheer joy of creation. Friday, I kind of snapped, fired up Visual Studio 2008, downloaded the tool stack and started hacking away.

Things seemed to just click on all of the topics I had been reading about. I started out with NHibernate and getting a simple User entity to persist to a SQL Sever 2005 database. I then moved on to implementing the Repository Pattern for my User entity abstracting away the actual persistence to a DataProvider class wrapping NHibernate. By this time I had Factory Patterns all over the place, so I added a reference to Ninject.Core and got rid of those too. I then whipped out a MVC site to consume my new repository.

After an evening of furious experimentation, I had a complete database to web page end to end implementation of my User entity. I was stoked, still am. I am currently working on getting unit tests in place using Rhino.Mocks, integration tests on my data access layer and fully implementing CRUD in the MVC site. It is a hell of a lot of fun.

If anyone is interested in seeing what I am working on or want a simple example of using all these things together in an easily understandable way, I posted my work to CodePlex. If you are new to this stuff like I am, download it and check it out. If you are an old hat and want to give me some pointers or tips, please download it and fill me in.

If you work with me and happen to read my blog and are interested, I would love to talk to you about the project and what I learned and discovered. Hit me up.


 
Categories: Development | Fundamentals | Tools | Unit Testing

I came across an interesting issue tonight exploring the use of Rhino.Mocks in unit tests. I have a class UserRepository that implements my current understanding of the Repository Pattern. My repository uses the interface IDataProvider to persist my User entity. The concrete class UserDataProvider wraps NHibernate.

My goal was to write unit tests that cover the methods of UserRepository. I used Rhino.Mocks to mock away UserDataProvider to prevent actually needing a database.

Things were going fine:

public void SaveTest(){
            MockRepository mock = new MockRepository();

            IDataProvider dataProvider = 
                  (IDataProvider) mock.CreateMock<IDataProvider>();
            UserRepository target = new UserRepository(dataProvider);
            User u = new User();
            
            Expect.Call(dataProvider.Save(u)).Return(1);
            Expect.Call(dataProvider.GetById(1)).Return(u);
            
            mock.ReplayAll();
            User x = target.Save(u);
            mock.VerifyAll();

            Assert.AreEqual(x, u);
        }
 
public void GetListTest(){
            MockRepository mock = new MockRepository();
            IDataProvider dataProvider = 
                 (IDataProvider)mock.CreateMock<IDataProvider>();
            UserRepository target = new UserRepository(dataProvider);

            Expect.Call(dataProvider.GetList()).Return(
                new List<object> { new User(), new User()});

            mock.ReplayAll();
            IList<User> users = target.GetList();
            mock.VerifyAll();
            Assert.AreEqual(2, users.Count);  
        }

Then I hit a snag. My User entity has a property Id that is read only. The users Id comes form the database and should not be able to be modified. So my next test has a bit of a problem and fails to compile.

public void GetByIdTest() {
            MockRepository mock = new MockRepository();

            IDataProvider dataProvider = (IDataProvider)mock.CreateMock<IDataProvider>();
            UserRepository target = new UserRepository(dataProvider);

            //TODO: Interesting Problem here. My actual dataProvider uses NHib
            //and would be able to meet this expectation. But my mock
            //cannot set the read only id property so this test will not
            //even compile.
            Expect.Call(dataProvider.GetById(1)).Return(new User() { Id = 1 });

            mock.ReplayAll();
            User u = target.GetById(1);
            mock.VerifyAll();

            Assert.AreEqual(1, u.Id);
        }

 

NHibernate has no problem injecting the value when I fetch the object from it, but my simple little expectation above chokes on it. I am not sure how to get around this one with out violating the intent of the test. I'll have to dig into the Rhino.Mocks documentation and see what tools it offers to get around this situation.

So far Rhino.Mocks is a great time saver. If I actually had to generate a fake for IDataProvider it would take quite a bit of time. I'll have to work it into my regular work life and see how it fairs there.

I'll update this post when I find a resolution to the issue at hand.


 
Categories: Development | Tools | Unit Testing