Author: Krzysztof

Windsor’s Nuget package and code – your input needed

As we’re nearing to release the next version of Castle Windsor I’m also thinking about how we could leverage Nuget better.

One idea I had was to include elements I (and most people) end up writing in every project using Windsor – a Bootstrapper class which is responsible for setting up the container, a folder for installers, and an installer in it.

This is what a solution would look like after creating an empty project and installing Windsor via Nuget:

Visual Studio after installing Windsor via Nuget, including code

Visual Studio after installing Windsor via Nuget

The goal of this would be to put the code in your solution having the bare-bone useful minimum, with intention you’d customize it as needed. Most people end up adding at least and so the bootstrapper would look like this:

using Castle.Facilities.TypedFactory;
using Castle.MicroKernel.Resolvers.SpecializedResolvers;
using Castle.Windsor;
using Castle.Windsor.Installer;

namespace WpfApplication1
{
    public class WindsorBootstrapper
    {
        public IWindsorContainer BuildContainer()
        {
            IWindsorContainer container = Instantiate();
            Configure(container);
            InstallComponents(container);
            return container;
        }

        private IWindsorContainer Instantiate()
        {
            return new WindsorContainer();
        }

        private void Configure(IWindsorContainer container)
        {
            container.AddFacility<TypedFactoryFacility>();

            var resolver = new CollectionResolver(container.Kernel, allowEmptyCollections: false);
            container.Kernel.Resolver.AddSubResolver(resolver);
        }

        private void InstallComponents(IWindsorContainer container)
        {
            container.Install(FromAssembly.This());
        }
    }
}

The installer is a tougher nut to crack. Because they are so specific to your application it’s impossible to create a generic one that will be useful. I’m thinking either about shooting for the widest scenario, and create either an empty one, with generic name like RepositoriesInstaller, or to get it one step farther and add some real-like code, but comment it out, like this:

using Castle.MicroKernel.Registration;
using Castle.MicroKernel.SubSystems.Configuration;
using Castle.Windsor;

namespace WpfApplication1.Installers
{
    public class RepositoriesInstaller : IWindsorInstaller
    {
        public void Install(IWindsorContainer container, IConfigurationStore store)
        {
            // Customize to the needs of your application

            //container.Register(Classes.FromThisAssembly()
            //                       .BasedOn(typeof (IRepository<>))
            //                       .WithService.Base()
            //                       .LifestyleTransient());
        }
    }
}

My hope is, this would give advanced users a jump-start and provide a gentle introduction for people new to Windsor, and push them towards established practices when using Windsor (closer to to the pit of success).

This is just an idea, and I would like to hear your feedback. What do you think about it? Do you think it should be included at all in the Castle.Windsor package, or should we create a separate package called something like Castle.Windsor-wc (for “with code”) for this?

How to force Nuget not to update log4net to 1.2.11

That’s a quick one. There’s been a new release of log4net recently that’s signed with a new key, and therefore is incompatible with old version 1.2.10.

Therefore, due to near-ubiquity of the library in .NET space, it may cause some problems if you happen to have a dependency (direct or indirect) on it.

The matters are made worse by Nuget’s default of getting the latest available version of the package. I dealt with this problem the other day, and I saw a few people in my twitter stream struggling with the same issue.

The solution is quite simple. It’s not specific to log4net and I’m not picking on log4net here. Here’s how you can restrict Nuget’s package to specific version in your solution.

 

So imagine you install a package that has a dependency on log4net. In this case, the dependency is specified as specifically version 1.2.10 (as opposed to Nuget’s default: this version of newer).

nuget_core

If after that we install another package that also depends on log4net but doesn’t restrict the version, we’ll have a problem.

nuget_log4net_fail

The package we were trying to install doesn’t get installed. Actually, even if it did, we would have a problem since it most likely was compiled against log4net 1.2.10 anyway, and if Nuget updated log4net to version 1.2.11 the app would throw an exception at runtime due to mismatched assembly.

So there is a solution to restrict version of the package to specific version (in this case 1.2.10) as specified in the documentation.

nuget_log4net_fail_solution

After adding allowedVersions=”[1.2.10]” we can try again and this time the package will install properly.

nuget_log4net_fail_avoided

Notice it says it installed log4net 1.2.11. I checked my packages folder, and project dependencies and the version referenced was 1.2.10 so all is good.

Hope that helps

Testing framework is not just for writing… tests

Quick question – from the top of your head, without running the code, what is the result of:

var foo = -00.053200000m; 
var result = foo.ToString("##.##");

Or a different one:

var foo = "foo"; 
var bar = "bar"; 
var foobar = "foo" + "bar"; 
var concaternated = new StringBuilder(foo).Append(bar).ToString(); 

var result1 = AreEqual(foobar, concaternated); 
var result2 = Equals(foobar, concaternated);


public static bool AreEqual(object one, object two) 
{ 
    return one == two; 
}

How about this one from NHibernate?

var parent = session.Get<Parent>(1); 

DoSomething(parent.Child.Id); 

var result = NHibernateUtil.IsInitialized(parent.Child);

The point being?

Well, if you can answer all of the above without running the code, we’re hiring. I don’t, and I suspect most people don’t either. That’s fine. Question is – what are you going to do about it? What do you do when some 3rd party library, or part of standard library exhibits unexpected behaviour? How do you go about learning if what you think should happen, is really what does happen?

Scratchpad

I’ve seen people open up Visual Studio, create ConsoleApplication38, write some code using the API in question including plenty of Console.WriteLine along the way (curse whoever decided Client Profile should be the default for Console applications, switch to full .NET profile) compile, run and discard the code. And then repeat the process with ConsoleApplication39 next time.

 

The solution I’m using feels a bit more lightweight, and has worked for me well over the years. It is very simple – I leverage my existing test framework and test runner. I create an empty test fixture called Scratchpad.

scratchpad

scratchpad_fixture

This class gets committed to the VCS repository. That way every member of the team gets their own scratchpad to play with and validate their theories, ideas and assumptions. However, as the name implies, this all is a one-off throwaway code. After all, you don’t really need to test the BCL. One would hope Microsoft already did a good job at that.

If you’re using git, you can easily tell it not to track changes to the file, by running the following command (after you commit the file):

git update-index –assume-unchanged Scratchpad.cs

scratchpad_git

With this simple set up you will have quick place to validate your assumptions (and answer questions about API behaviour) with little friction.

scratchpad_test

So there you have it, a new, useful technique in your toolbelt.

Approval testing – value for the money

I am a believer in the value of testing. However not all tests are equal, and actually not all tests provide value at all. Raise your hand if you’ve ever seen (unit) tests that tested every corner case of trivial piece of code that’s used once in a blue moon in an obscure part of the system. Raise your other hand if that test code was not written by human but generated.

 

As with any type of code, test code is a liability. It takes time to write it, and then it takes even more time to read it and maintain it. Considering time is money, rather then blindly unit testing everything we need to constantly ask ourselves how do we get the best value for the money – what’s the best way to spend time writing code, to write the least amount of it, to best cover the widest range of possible failures in the most maintainable fashion.

Notice we’re optimising quite a few variables here. We don’t want to blindly write plenty of code, we don’t want to write sloppy code, and we want the test code to properly fulfil its role as our safety net, alarming us early when things are about to go belly up.

Testing conventions

What many people seem to find challenging to test is conventions in their code. When all you have is a hammer (unit testing) it’s hard to hit a nail, that not only isn’t really a nail, but isn’t really explicitly there to being with. To make matters worse the compiler is not going to help you really either. How would it know that LoginController not implementing IController is a problem? How would it know that the new dependency you introduced onto the controller is not registered in your IoC container? How would it know that the public method on your NHibernate entity needs to be virtual?

 

In some cases the tool you’re using will provide some level of validation itself. NHibernate knows the methods ought to be virtual and will give you quite good exception message when you set it up. You can verify that quite easily in a simple test. Not everything is so black and white however. One of diagnostics provided by Castle Windsor is called “Potentially misconfigured components”. Notice the vagueness of the first word. They might be misconfigured, but not necessarily are – it all depends on how you’re using them and the tool itself cannot know that. How do you test that efficiently?

Enter approval testing

One possible solution to that, which we’ve been quite successfully using on my current project is approval testing. The concept is very simple. You write a test that runs producing an output. Then the output is reviewed by someone, and assuming it’s correct, it’s marked as approved and committed to the VCS repository. On subsequent runs the output is generated again, and compared against approved version. If they are different the test fails, at which point someone needs to review the change and either mark the new version as approved (when the change is legitimate) or fix the code, if the change is a bug.

 

If the explanation above seems dry and abstract let’s go through an example. Windsor 3 introduced way to programmatically access its diagnostics. We can therefore write a test looking through the potentially misconfigured components, so that we get notified if something on the list changes. I’ll be using ApprovalTests library for that.

[Test] 
pub­lic void Approved_potentially_misconfigured_components() 
{ 
    var con­tainer = new Wind­sor­Con­tainer(); 
    container.Install(FromAssembly.Containing<HomeController>());

    var han­dlers = GetPotentiallyMisconfiguredComponents(container); 
    var mes­sage = new String­Builder(); 
    var inspec­tor = new DependencyInspector(message); 
    fore­ach (IEx­poseDe­pen­den­cy­Info han­dler in han­dlers) 
    { 
        handler.ObtainDependencyDetails(inspector); 
    } 
    Approvals.Approve(message.ToString()); 
}

pri­vate sta­tic IHan­dler[] GetPotentiallyMisconfiguredComponents(WindsorContainer con­tainer) 
{ 
    var host = container.Kernel.GetSubSystem(SubSystemConstants.DiagnosticsKey) as IDi­ag­nos­tic­sHost; 
    var diag­nos­tic = host.GetDiagnostic<IPotentiallyMisconfiguredComponentsDiagnostic>(); 
    var han­dlers = diagnostic.Inspect(); 
    return han­dlers; 
}

What’s important here is we’re setting up the container, getting the misconfigured components out of it, produce readable output from the list and passing it down to the approval framework to do the rest of the job.

Now if you’ve set up the framework to pup-up a diff tool when the approval fails you will be greeted with something like this:

approval_diff

You have all the power of your diff tool to inspect the change. In this case we have one new misconfigured component (HomeController) which has a new parameter, appropriately named missingParameter that the container doesn’t know how to provide to it. Now you either slap yourself in the forehead and fix the issue, if that really is an issue, or approve that dependency, by copying the diff chunk from the left pane to the right, approved pane. By doing the latter you’re notifying the testing framework and your teammates that you do know what’s going on and you know it’s not an issue the way things are going to work. Coupled with a sensible commit message explaining why you chose to approve this difference you get a pretty good trail of exception to the rule and reasons behind them.

 

That’s quite an elegant approach to a quite hard problem. We’re using it for quite a few things, and it’s been giving us really good value for little effort it took to write those tests, and maintain them as we keep developing the app, and the approved files change.

 

So there you have it, a new, useful tool in your toolbelt.

API design challenge – builder

Now that Windsor 3 is released I can concentrate on some of my other ideas and projects. While working on one of them, called Cartographer, I encountered an interesting API design problem.

 

I have a class (a builder to be precise) that has a task of setting up a central object (an IMapper implementation) in Cartographer (If you’ve ever used Autofac, it is somewhat analogous to ContainerBuilder). What is interesting about it, is I have three goals for that class:

  1. Provide API for high level configuration and extension points that are universal to and intrinsic to any IMapper implementation.
  2. Provide API for low level configuration of the default IMapper implementation that the builder creates, that will meet the following criteria:
    1. Not force user to customize anything, as the default setup should be enough to get started in most cases.
    2. Allow users to easily swap/extend parts of the dependency chain of the default mapper.
    3. Work well and be natural both with and without IoC container .
  3. Be simple and discoverable to the users (and provide good Intellisense experience).

How would you design the API for this class?

 

Oh, and happy new year.

Castle Windsor 3.0 is released

Castle Windsor

After successful beta and RC releases final version of Castle Windsor (as well as Castle Core, and a whole set of facilities) has now been released. There are no major changes between final version and RC. The difference is some minor bug fixes, improved exception messages and some small improvements all over the place.

 

The packages are available now, on Nuget (with symbols), and via standard .zip download.

 

Last but not least – thank you to everyone who downloaded beta and release candidate and provided feedback. You guys rock.

Getting closer… Castle Windsor 3 RC 1

Few weeks later than originally expected but here it is – Castle Windsor 3.0 (along with its facilities and Castle.Core) achieved release candidate status.

There is one major new feature in this release: registration API gained ability to specify properties to ignore/require. There are some scenarios where that’s useful, for example where integrating with some 3rd party framework that forces you to inherit from a base class which exposes its dependencies as properties. Creating pass-through constructors for each inherited class can be mundane. In those cases you can simply mark those base class properties as required, in which case Windsor will not allow them to be resolved unless all base property dependencies are satisfied. PropertyFilter enum supports several other most common scenarios, and for advanced cases there’s an overload that gives you more control.

Container.Register(
    Classes.FromThisAssembly()
        .BasedOn<ICommon>()
        .Configure(c => c.Properties(PropertyFilter.RequireBase)));

To address performance hit at startup Windsor no longer enables performance counters by default. Now, you have to do it explicitly:

var container = new WindsorContainer();
var diagnostic = LifecycledComponentsReleasePolicy.GetTrackedComponentsDiagnostic(container.Kernel);
var counter = LifecycledComponentsReleasePolicy.GetTrackedComponentsPerformanceCounter(new PerformanceMetricsFactory());
container.Kernel.ReleasePolicy = new LifecycledComponentsReleasePolicy(diagnostic, counter);

Full changelog is included in the packages. Please, if possible, take the time to upgrade to this version and if you find any issues report them so that the final release is rock solid. If no major issues are found, the final release will be published in two weeks.

The binaries are available on Nuget right now, and soon on our website.

Connector: Simple, zero friction Github –> AppHarbor integration

Recently to play with some new technology I came up with an idea to build an integration layer between Github and AppHarbor. What that means, is give you ability to work with your Github repository, reaping benefits of all of it’s VCS-centric features, and automatically, continuously deploy your code to AppHarbor.

The actual scenario I had in mind is to be able to use that for deployment of Open Source projects. AppHarbor is fantastic, no-headache deployment in the cloud, but Github is perfect for keeping and developing your code in the open, in social way. To have the cake and eat it too, Connector was born.

Connector

I hope you find it useful. it is free, use-at-your-own-risk-and-don’t-sue-me-if-something-breaks software. There’s still some work to be done, feature-wise and a whole lot of polishing but I decided to announce it early and get early feedback. If you have any suggestions, ideas or (gulp) bugs, let me know!

link: http://connector.apphb.com/

Hope that helps.

Windsor 3 beta 1 – dozen of Nuget packages and SymbolSource.org support

As promised, I released Nuget packages for beta 1 of Windsor 3. This is my first major rollout of Nuget packages, so please report any issues working with them.

Nuget and beta packages

Nuget is quickly evolving and getting more useful with each release. However one feature it’s missing right now is support for pre-release packages (this is coming in the next version).

davidebbo

This is not really a big deal, however it means there are a few things you should be aware of.

Recommended version

Since the new package is a pre-release, while I would really like for everyone to start using it immediately and report all issues they find, I quite understand that many people will rather prefer to stick to the last official version for the time being. To accommodate that the new packages are not made recommended versions, so your Nuget explorer will still point to the last stable (2.5.3) version if you search for Windsor, Castle.Core or any other pre-existing package.

nuget_explorer 

If you go to command line and install one of the packages without specifying version number, it will install the latest, that is beta 1 version.

nuget_commandline

SymbolSource.org and debugging into Windsor

Folks at SymbolSource.org added recently support for Nuget (and OpenWrap as well) and the new Castle packages take advantage of that. What it gives you, is you can now easily debug into Windsor’s code, just like .NET framework reference source (there’s a simple guide at SymbolSource on how to do it).

After you’re all set you can step into any of Castle methods in your debugger and watch the magic happen. Very cool thing, even if I say so myself.

windsor-source-debugging

 

List of packages

Here’s the full list of v3 beta 1 packages (notice those are not all Castle packages, just those that were published as v3 beta 1 rollout of Windsor):

 

I hope this will make it easier for everyone to test drive Windsor. And if you find any issues, have any suggestions or ideas, do not hesitate to bring them up, either on our google group, or issue tracker.

Simple guide to running Git server on Windows, in local network (kind of)

Last year I found myself in a sudden and quick need to set up working environment for a team of four, and as I like Git very much, I wanted to use it as our VCS. The problem was, we weren’t allowed to use any third party provider, so GitHub was off the table. As I searched the Internet there were a few guides to set up team Git environment on Windows, but they all seemed very complicated and time consuming. For our modest needs we experimented a little and came up with a solution that was very simple, didn’t require any additional software to be installed anywhere and worked like a charm.

Recently I used it again on my current engagement, and one of my colleagues suggested I should blog it, so here goes.

Ready, steady, go

The guide assumes you already have your local Git set up. For that, there are plenty of resources on the Internet, including my own blogpost about Windows Git tooling.

The entire tricks works like this – expose folder containing your shared Git repository as Windows network share.

Step one – bare git repository

There are two twists to the entire solution – one of them is – your shared repository needs to be initialized with –bare flag.

git_bare_repository

Step two – Windows share

Second step is to expose the folder with our newly created repository on the Windows share. You also use your standard Windows mechanisms to control and limit access to the folder (make sure you give the developers write access!).

Step three – Map the share as network drive

This step is perhaps not exactly necessary but I couldn’t get it to work otherwise, so here comes the second twist. In order for your developers to be able to access the shared folder via Git they need to map it as network drive.

sshot-10

Step four – Add remote repository in Git and code away

Last step is the standard Git procedure – every developer on your team needs to add the repository sitting under their newly created network drive as remote. Notice the use of “file:///” prefix in front of the mapped drive name.

sshot-11

Step five

That’s all. I hope you find it useful, and if you know a way to eliminate step three, let me know in the comments.