I’ll let a few queries from my current project say all that needs to be said.

public IEnumerable GetRolledUpEventsFor(DateTime tradeDate, IEnumerable tickers)
        {
            return worker.On(connection, session =>
                                             {
                                                 OrderEventRollup rollup = null;
                                                 return session.QueryOver()
                                                     .Where(x => x.TradeDate == tradeDate)
                                                     .WhereRestrictionOn(x => x.Ticker).IsIn(tickers.ToArray())
                                                     .Select(
                                                         list =>
                                                         list.SelectGroup(x => x.Ticker).WithAlias(() => rollup.Ticker)
                                                             .SelectSum(x => x.Shares).WithAlias(() => rollup.SharesTotal))
                                                     .TransformUsing(Transformers.AliasToBean())
                                                     .List();
                                             });
        }
 public IEnumerable GetBrokersByCode(IEnumerable brokerCodes)
        {
            if (brokerCodes.Count() == 0) return Enumerable.Empty();
            return worker.On(connection, session =>
                                         session.Query()
                                             .Where(x => brokerCodes.Contains(x.Code))
                                             .ToList()
                );
        }
public IEnumerable GetByTradeDateAndTicker(DateTime tradeDate, string ticker)
        {
            return worker.On(connection, session =>
                                             {
                                                 CSMSecurity security = null;
                                                 return session.QueryOver()
                                                     .Fetch(x => x.CSMSecurity).Eager
                                                     .Fetch(x => x.TSOrderSecuritySpec).Eager
                                                     .Fetch(x => x.CSMSecurity.CSMSecurityType).Eager
                                                     .JoinAlias(x => x.CSMSecurity,() => security)
                                                     .Where(x => x.TradeDate == tradeDate)
                                                     .Where(() => security.Ticker == ticker)
                                                     .List();
                                             });
        }
So hawt indeed.
 
Categories: NHibernate

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

I saw this video float across twitter yesterday and think it is a great introduction to the kind of complexity that programmers deal with for your average business user. Brian does an amazing job of demonstrating the process in such a way that anyone can understand it.

Obtiva Geekfest - Programming for business users - By. Brain Marick from Lance Ennen on Vimeo.


 
Categories: Development | Fundamentals

Where I work we are moving toward using MSI installers for all deployments into production. We lean pretty heavily on the Wix (Windows Installer XML) project. Wix is an incredibly powerful library that allows you to do amazing things. The downside is its abuse of XML as a programming language. Anyone who knows me understands the level of hatred I have for angle bracket noise.

That is why I was really excited when I first discovered Wix# by Oleg Shilo. Wix# is a great managed interface for the Wix toolset. It offers a simple, if not verbose collection of objects that describe your installation package and options. I happily switched all of my builds over to using it and abandoned working with Wix xml directly. The downside to Wix# is its lack of complete support for IIS extensions. It also has kind of an old school flavor, a complete lack of unit test, several weird bugs and is not fully open source. Oleg hopes to eventually take the project commercial and I wish him the best of luck with it.

But, I think I can do better. I started my own project as a kind of breakable toy and made it fully open source. I’ve worked on and with Fluent NHibernate for quite a while now and really love their approach to basically generating xml files. With heavy influence from FNH and inspiration from Wix#, I have started Fluent Wix.

The goal of Fluent Wix is to provide a fluent interface over describing a deployment package. I would like the library to be usable from Powershell. I am currently focused on drilling through the Wix Schema down to laying an individual file on the file system.

If the project, interests you feel free to fork it on github and start contributing.


 

The South Sound .NET User Group is proud to announce an evening with Charlie Poole this coming Thursday night. The meeting will be held at our usual time of 7:00-9:00PM at the Olympia Center (222 Columbia NW, Rm 101).

Charlie Poole has spent more than 30 years as a software developer, designer, project manager, trainer and coach. After a long career in the government sector, he began working independently in 1996 with clients ranging from Microsoft to government agencies to internet startups.


Charlie's technical background is long and broad. In recent years, he has specialized in C++ and C# development in cross-platform settings. He has worked with the .NET framework since its inception, is one of the authors of the NUnit .NET testing framework and contributes to several other Open Source projects.

"For the past ten years, Charlie has worked as an Agile coach and trainer. He is a familiar presence at Agile and Open Source events and is one of the founders of the Agile Open Northwest conference."

Synopsis:
Like many folks, I started out with simple unit testing after the fact and eventually proceeded to Test-Driven Development. As I have ripened in age and (hopefully) experience I have started to see the need for something beyond TDD, BDD, STDD, DDD, etc - something that works at all levels of a project and for all project roles - developers, testers, managers and customers included.


In this talk, I'll tell about my own journey and where I think we need to go if we want to move beyond nominal "Agile Development" to real mastery. Along the way, I'll illustrate with bits of NUnit tests (including some new features) as well as some other testing approaches."


 
Categories: Events | Local

This just popped up on Twitter a few minutes ago and it is a brilliant break down on motivation. Everyone who manages people should watch this.


 
Categories: Random

I use these two functions to quickly setup Powershell to execute Ruby code under either MRI or IronRuby easily. Simply add them to your Powershell profile.

function set-ironruby() {
	$env:path = ";c:\ironruby\bin\;c:\ironruby\lib\ironruby\gems\1.8\bin\;" + $env:path
}

function set-ruby() {
$env:path = ";c:\ruby\bin\;" + $env:path
}

Then you can use it like so..

rubypsfunctions


 
Categories: Development

It seems like every day my unit testing style becomes more and more stylized and it seems I am driving toward something specific, elegant and readable. I want my tests to not only validate that the code does what I think it should do, but it also tells the story of what is happening and how. The latest permutation of this obsession has me focusing on the context of my specifications. Why have lines and lines of object initialization code when I can instead explicitly state the context that the tests are running under in an expressive way?

Consider the two following code samples. Does either help you to understand the intent of the system under test? Which do you prefer? Why? Do you find it silly? Pointless?

Old & Busted:

[TestFixture]
    public class when_getting_the_import_status_and_all_files_exist_for_a_date : with_a_imports_controller
    {
        private FileLoadStatus fileLoadStatus;

        public override void Context()
        {
            base.Context();
            var logs = new List { new FileLog { Id = 1, WasSuccessful = true } };
            var types = new List
                            {
                                new FileType()
                                    {
                                        Id = 1,
                                        Name = "foo",
                                        Logs = logs
                                    }
                            };

            logs.Each(x => x.Type = types.First());
            fileLoadStatus = new FileLoadStatus
                                 {
                                     FileTypes = types,
                                     Logs = logs
                                 };

            looker.Stub(x => x.GetStatusFor(Clock.Yesterday)).Return(fileLoadStatus);


        }

        public override void Because_of()
        {
            result = controller.GetStatusFor(Clock.Yesterday);
        }

        [Test]
        public void I_should_get_a_file_type()
        {
            result.FileTypeStatuses.Any(x => x.Name == "foo").ShouldBeTrue();
        }

        [Test]
        public void I_should_see_a_file_type_with_an_OK_status()
        {
            result.FileTypeStatuses.Where(x => x.Name=="foo")
                .FirstOrDefault().Status.ShouldBe("OK");
        }

        [Test]
        public void I_should_get_a_log_for_the_file_type()
        {
            result.Logs.Any(x => x.Id == 1).ShouldBeTrue();
        }
    }

New Hotness?:

[TestFixture]
    public class when_getting_the_import_status_and_a_file_has_loaded_twice_and_failed : with_a_imports_controller
    {

        private FileLoadStatus fileLoadStatus;
        FileType fileType;

        public override void Context()
        {
            base.Context();
            fileType = I.Have().AFileType()
                .WithALogFile().ThatProcessed(Clock.Yesterday).ThatSucceeded()
                .WithALogFile().ThatProcessed(Clock.Yesterday.AddMinutes(10)).ThatFailed();
            fileLoadStatus = fileType.ToFileLoadStatus();
            looker.Stub(x => x.GetStatusFor(Clock.Yesterday)).Return(fileLoadStatus);
        }

        public override void Because_of()
        {
            result = controller.GetStatusFor(Clock.Yesterday);
        }

        [Test]
        public void I_should_get_the_filetype()
        {
            result.FileTypeStatuses.Any(x => x.Name == fileType.Name).ShouldBeTrue();
        }
        [Test]
        public void I_should_see_the_file_type_with_an_Failed_status()
        {
            result.FileTypeStatuses.Where(x => x.Name == fileType.Name)
                .FirstOrDefault().Status.ShouldBe("Failed");
        }

        [Test]
        public void I_should_see_two_logs_for_the_file_type()
        {
            result.Logs.Count().ShouldBe(2);
        }
        
    }

 
Categories: Unit Testing

The South Sound .NET User Group is proud to announce an evening with Justin Bozonier this coming Thursday night. The meeting will be held at our usual time of 7:00-9:00PM at the Olympia Center (222 Columbia NW, Rm 101).

Justin Bozonier has been working as a professional programmer since 2004 at companies such as Microsoft, LexisNexis, and currently at Milliman, one of the top actuarial consulting firms in the United States. Currently an Actuarial Systems Developer, he is also one of the founding members of Alt.NET Seattle. His current interests include Domain Driven Design, Behavior Driven Development, Message Based Concurrency, Machine Learning and computer science in general.

Message Oriented Object Design (MOOD) is an object oriented design philosophy wherein we view objects as sending immutable messages/publishing events on channels. MOOD systems also rely on the configuration of object networks to enable collaboration between them. Perhaps most importantly, we achieve this not by using a new framework but just by changing how we look at and use our code.

Side Note: I have personally known Justin for a couple years now. Not only is he a brilliant developer with tons of talent, but his sheer enthusiasm for programming and life in general is infectious. You just can’t help but like the guy. Listening to him talk, will get you excited about programming and the endless possibilities it presents.


 
Categories: Events | Local

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