Wednesday, March 25, 2009

Boo

With Ayende's DSL book on the horizon i thought i would fire of some links and some background on Boo and DSLs as a couple of people have been asking about them of late.
Firstly Boo:
Boo is a Python-like language that sits on top of the CLI. It is pretty old (over 4 yrs old) so was written well before the DLR which mean it impresses me that much more! Its basically a scripty language that gives you the benefits of such languages. Unfortunately it does not have VS support, but you can download VS add-ins or SharpDeveloper, whcih is a Free IDE for C#, VB.Net and of course Boo. On a side note #Dev is also a good option as an auxiliary IDE (eg for you laptop) if you don't want to shell out for an additional VS licence.

Right, so what is a DSL?
A DSL is a Domain Specific Language which, to me, means a language that is tailored to a specific purposes. Now every person I speak to has a different opinion on what a DSL is, in fact we had a near on religious debate about this in one of the London .Net Beers when Ayende graced us with his presence. To be honest you have to be a little pragmatic and take in to context the situation. You could consider SQL a DSL as it is a language that is VERY specific to a given domain; that is interaction with Relational Databases. Although that may be valid in the context of me talking to another developer, I tend to assume that we are talking about something a little more business focused, like a rules engine or workflow. Personally I don't really like the notion that stems from Microsoft that by default a DSL is graphical; it works for some things reasonably well (eg Workflow) but it can quickly fall down when complexity increases or extensibility is required.
This is where the likes of Ruby and Boo shine. Ruby as we all know is the new "all singing, all dancing king of the coding world" in which one of the very cool things about it is that you can relatively easily create your own DSL. For a great intro to Ruby which covers briefly its DSL capabilities check out The Ruby Programming Language. Ruby may also be a good place to do back ground research on DSL as it has a larger community.
Boo, being Dynamic-ish, allows you to take some of these concepts and create DSLs in asimilar fashion.
Have ever done this?
No.
My Dynamic coding skills suck and i really need to get better, unfortunately Power shell, Java/Android and COD4 tend to get in the way. Luckily for us there are people waaaay smarter than me that can show the way, such as Ayende thru is blog and forthcoming book.
Ayende, for starters, blazes the trail by providing no less than 2 real world DSLs that YOU, a .Net developer, can use:
Bindsor- A boo based DSL theat allows you to configure your Castle Windsor IoC container from a .boo script file, allowing for dynamic changes, but in code. Binsor is available in Ayendes Rhino Commons
&
Bake - a boo based build system that is inspired by the Ruby build system "Rake", see what they have done there ;)

For some tutorials involving Binsor check out http://ruprict.wordpress.com/category/castle/
or flick through Ayende's blog, he covers a tonne of stuff there.

As a side note, I was speaking Fowler* and he mentioned that he was working on a DSL book but at the time (Mar 08) was thinking of flagging it... i am not sure if it will be reborn, but keep an eye out.

*yesssss awesome name dropping skillz!... sorry :)

"Not" Specification

I am currently spiking out a DDD based solution that will have a significant amount of rules associated. I am currently making heavy use of the Specification pattern as there is a tonne of reuse from these and potentially a more readable API. One problem I have and have always had with the typical Specification pattern is the Not() method; It is a bit ugly and when used in method chaining is somewhat confusing as the Not is a suffix, unlike the other methods in the fluent interface (And and Or).

I have made a slight change to my base specification class by adding an AndNot(x) method as I quite frequently am finding the need for it and it is so much more readable than And(x).Not().

This is simply an addition of the signature on the interface:

public interface ISpecification
{
bool IsSatisfiedBy(T candidate);

ISpecification And(ISpecification other);

ISpecification AndNot(ISpecification other);//NEW!!!

ISpecification Or(ISpecification other);

ISpecification Not();
}

and the implemented code is just:

public ISpecification AndNot(ISpecification other)
{
return new AndSpecification(this, new NotSpecification(other));
}


I don't see a need to remove the Not() as it is still useful in defining reusable not specs.

HTH
Rhys

Holidays are good

I have just had a 12 day holiday catching up with family and friends in Sydney (Aus) and Auckland, Hamilton and Whangarei (NZ). Was a lovely trip, nice to see all the new additions to the family, kids husbands and wives etc!

Back to work now, but i feel good, well relaxed. hoping to get right back into the fun stuff.. coding!

FYI there looks to be a Coding Dojo being organised by Mike (Alt.Net Perth) which i may be contributing, so keep april the 8th earmarked if you are a perth local. For those unfamilir it is a way of cross polinating skill by actually coding with others, not just watching. The theme will be TDD.

Wednesday, March 11, 2009

Ain't That the Truth!

A man in a hot air balloon, realizing he was lost, reduced altitude
And spotted a woman below. He descended further and shouted to the lady
"Excuse me, can you help me? I promised a friend I would meet him an
hour ago, but I don't know where I am"

The woman below replied, "You're in a hot air balloon, hovering
approximately 30 feet above the ground. You're between 40 and 41
degrees north latitude and between 59 and 60 degrees west longitude."

"You must be in IT," said the balloonist.

"Actually I am," replied the woman, "How did you know?"

"Well," answered the balloonist, "everything you have told me is
technically correct but I've no idea what to make of your information
and the fact is I'm still lost. Frankly, you've not been much help at
all. If anything, you've delayed my trip."

The woman below responded, "You must be in Management."

"I am," replied the balloonist, "but how did you know?"

"Well," said the woman, "you don't know where you are or where you're
going. You have risen to where you are due to a large quantity of hot
air. You made a promise, which you've no idea how to keep, and you
expect people beneath you to solve your problems. The fact is you are
in exactly the same position you were in before we met, but now, somehow,
it's my f***ing fault..."

Yeah, an oldie but a goodie...

Monday, March 9, 2009

Castle: We Still XML The Old Way

Post 4 in a 101 series on the Castle IOC project called Windsor. See part one for background

XML Config Based Registration

Although demoware may show us the inline registration of components is good it may not prove to be the best thing for your application. The previous posts have shown registration of types in C#, this means we must recompile if we are making changes to any parts of our registration. This may be considered a bad thing, it may also be considered a bad thing that the assembly that you are performing all of this registration in knows about (and has references to)  a lot of possibly inappropriate libraries and projects. One way around all of this is by using the XML configuration.

Using our same basic console app I add an app.config file and put the following in it:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="castle"
type="Castle.Windsor.Configuration.AppDomain.CastleSectionHandler, Castle.Windsor" />
</configSections>
<castle>
<components>
<component lifestyle="transient"
id="Writer"
service="CastleIocConsole.IWriter, CastleIocConsole"
type="CastleIocConsole.HelloWriter, CastleIocConsole" />
<component
id="Gday"
service="CastleIocConsole.IWriter, CastleIocConsole"
type="CastleIocConsole.GdayWriter, CastleIocConsole" />
<component
id="List"
service="CastleIocConsole.IWriter, CastleIocConsole"
type="CastleIocConsole.ListWriter, CastleIocConsole" />
<component
id="MessageService"
service="CastleIocConsole.IMessageService, CastleIocConsole"
type="CastleIocConsole.GuidMessageService, CastleIocConsole" />
</components>
</castle>
</configuration>

Several things to note:



  • You should specify the fully qualified name any time you are declaring types in XML, that is - Full.NameSpace.Type, Assembly

  • All components have an id

  • You don't need to specify a service, if the type has no interface or is the base calls you can just declare the type.

  • you can declare lifestyles (the transient lifestyle specified is not important in this example, its just there to show it can be done)


In addition to this you can specify which concrete dependencies you want, assign component properties and declare interceptors for AOP style run time inject of code blocks (more on this to come)


Using this code we could do some thing like this:


using System;
using Castle.Core.Resource;
using Castle.Windsor;
using Castle.Windsor.Configuration.Interpreters;

namespace CastleIocConsole
{
class Program
{
static void Main(string[] args)
{
IWindsorContainer container =
new WindsorContainer(
new XmlInterpreter(
new ConfigResource("castle")));
var writer1 = container.Resolve<IWriter>();
writer1.Write();
var writer2 = container.Resolve<IWriter>("List");
writer2.Write();
Console.ReadKey();
}
}
}

which would give the output of (see previous post for component definitions):


Hello World
122eb0e3-0812-4611-a580-7cf976039a89
5a916589-f7a5-4121-9fb6-a51cf24a6f43
977ec6f9-8110-4074-b537-047f21e6a70f
a136ae03-0caf-49fb-8511-92e3f2d39446
3aa1db17-78c8-438f-84a9-91ef14753ca7

As with any XML there seems to be a few catches so here are some gotchas that may help:



  • All components need an ID

  • First in best dressed: The first component registered is the default for that service (interface)

  • Standard .net XML config notation applies eg no line breaks in definitions, generics marked up with back tick notation etc

  • There is no official XSD schema but there are user defined ones, find one and put it is  the VS schema folder eg : C:\Program Files\Microsoft Visual Studio 9.0\Xml\Schemas to give you intellisense


That is the last in the 101 series for now. Soon I would like to cover



  • Interception and how you can use AOP with the Castle framework

  • Run time Config with out XML (Binsor)


Rhys


Back to Post 3

Castle: Control Your Dependents!

Post 3 in a 101 series on the Castle IOC project called Windsor. See part one for background

What About the Dependencies?

An Ioc Container is pretty much no use if it does not resolve a components dependencies, so we will show you how this can work.

We introduce a new component, the ListWriter which use constructor based dependency injection to provider a IMessageService. This dependency is used when writing our message:

class ListWriter : IWriter
{
private readonly IMessageService messageService;
public ListWriter(IMessageService messageService)
{
this.messageService = messageService;
}
public void Write()
{
foreach (var message in messageService.GetMessages())
Console.WriteLine(message);
}
}
interface IMessageService
{
IEnumerable<string> GetMessages();
}
class GuidMessageService : IMessageService
{
public IEnumerable<string> GetMessages()
{
for (int i = 0; i < 5; i++)
{
yield return Guid.NewGuid().ToString();
}
}
}

Because we have established a obvious dependency by exposing a constructor parameter the container is smart enough to know that it is going to have to find a registered component that fits that service. This means we also have to register this new service that we are dependent on:


class Program
{
static void Main(string[] args)
{
var container = new WindsorContainer();
container.AddComponent<IWriter, ListWriter>();
container.AddComponent<IMessageService, GuidMessageService>();
var writer1 = container.Resolve<IWriter>();
writer1.Write();
Console.ReadKey();
}
}

Which when run will now resolve the IWriter service as the LiveWriter component, realise the component can not yet be constructed as it has a dependency on the IMeassgeService, so will resolve that (as the Guid Writer Component we registered on the third line of the method), inject it into the LiveWriter component and then call Write() giving the output expected; 5 random GUID in their string representation:


122eb0e3-0812-4611-a580-7cf976039a89
5a916589-f7a5-4121-9fb6-a51cf24a6f43
977ec6f9-8110-4074-b537-047f21e6a70f
a136ae03-0caf-49fb-8511-92e3f2d39446
3aa1db17-78c8-438f-84a9-91ef14753ca7

This shows that the Container can now worry about creating object with complex dependencies and deep object graphs, allowing you to have a loosely coupled application, ready for any change that may come your way.


Next up : Using XML configuration


Back to Post 2

Castle: Pick Your Lifestyle

Post 2 in a 101 series on the Castle IOC project called Windsor. See part one for background

Lifestyle Management

Often you will want to control the lifestyle of the object you create, eg a common but over used lifestyle is the singleton. Using an IoC container means you do not have to manage this in your code, which means other dependencies don't have to implicitly know they are dealing with a singleton (or whatever lifestyle is being implemented). This is good and drastically cleans up production code and makes it a lot easier to test.

So lets have a look at a new implementation we have here the MultiGreeter; a concrete implementation (or component) that tells you how often this instance has greeted you.

class MultiWriter : IWriter
{
private int timesGreeted = 0;
public void Write()
{
Console.WriteLine("I have greeted you " + timesGreeted + " time(s) before");
timesGreeted++;
}
}

We change the program class so we register our new component and resolve the service a couple of times to see the output:


using System;
using Castle.Windsor;

namespace CastleIocConsole
{
class Program
{
static void Main(string[] args)
{
var container = new WindsorContainer();
container.AddComponent<IWriter, MultiWriter>();
var writer1 = container.Resolve<IWriter>();
writer1.Write();
var writer2 = container.Resolve<IWriter>();
writer2.Write();
var writer3 = container.Resolve<IWriter>();
writer3.Write();
Console.ReadKey();
}
}
}

The output is somewhat unexpected for new comers:


I have greeted you 0 time(s) before
I have greeted you 1 time(s) before
I have greeted you 2 time(s) before

Even though we have resolved the service each time to a new variable the count is incrementing. This is because Castle will resolve types as singletons by default. What we can do, if this lifestyle is inappropriate, is specify that we want the type to be of a differing type,transient for example, which would give the same behaviour associated with calling the constructor of the component each time we resolve the service (ie var writer = new MultiWriter()). This requires are slightly different way of registering our components by using the AddComponentWithLifestyle method and use the Castle.Core.LifeStyleType enumeration to select our desired lifestyle.


using System;
using Castle.Windsor;
using Castle.Core;

namespace CastleIocConsole
{
class Program
{
static void Main(string[] args)
{
var container = new WindsorContainer();
container.AddComponentWithLifestyle<IWriter, MultiWriter>(LifestyleType.Transient);
var writer1 = container.Resolve<IWriter>();
writer1.Write();
var writer2 = container.Resolve<IWriter>();
writer2.Write();
var writer3 = container.Resolve<IWriter>();
writer3.Write();
Console.ReadKey();
}
}
}

The output is now the expected:


I have greeted you 0 time(s) before
I have greeted you 0 time(s) before
I have greeted you 0 time(s) before

This is because each time we resolve a brand new instance is created. The other Lifestyle I like is PerWebRequest (for obvious reasons).


Next we control our dependencies


Back to Post 1

Castle: The .Net framework of choice

Post 1 in a 101 series on the Castle IOC project called Windsor

I have long been an advocate of the Castle stack, stemming from my days at Change Corp. At the time we were using Spring.Net for our IoC container but also were using NHibernate. I noticed that we had castle DLL's in the bin and realised that NHibernate was using them for object creation. I looked into the Castle project and despite is lack lustre documentation was able to get IoC working pretty quickly. One of the things I personally like is that you did not NEED to use XML for you container registration (i.e.  defining which concrete type to use for which abstract request). On top of this the Monorail  project (the original MCV framework for ASP.Net) and Active Record The AR pattern sitting on top of NH) struck a chord as being particularly handy tools.

Years later the stack remains pretty much the same. There are some off shoot developments but by and large the same stuff I went to castle for is why I still like to use it.... well at least I thought.

Yesterday when writing the DI blog post I realised I had not directly used Castle in over a year. I have a wrapper that I use to abstract my interaction with the container and the OSS libraries that I use/play with hide the details too (MassTransit, SutekiShop etc). So I have decide to give a crash course for myself and the rest of the world on how to set up and exploit some of the more basic but super handy Castle features.

Castle, IoC And You: The set up

First and foremost you need to download the latest castle libraries. Currently these are RC3 and last updated in sep 07. Get them here.

Install the binaries, these will be jammed in the GAC for safe keeping. You can also use the straight DLLs if you need to for source control etc, just make to reference everything you need (i.e. secondary dependencies)

Right, with that sorted we are able to do the world silliest IOC demo.

Create a console application and include references to  Castle.Core.dll, Castle.MicroKernel.dll, Castle.Windsor.dll & Castle.DynamicProxy.dll.

I have create a very basic interface called IWriter which has one method: void Write()

I have two instances that implement it: HelloWriter and GdayWriter. It is probably a good time to note that in the castle world a "service" is generally referring to the interface or abstract type that you are calling and the "component" is the concrete implementations. So the IWriter would be our service and the HelloWriter and GdayWriter are considered components.

interface IWriter
{
void Write();
}
class HelloWriter : IWriter
{
public void Write()
{
Console.WriteLine("Hello World");
}
}
class GdayWriter : IWriter
{
public void Write()
{
Console.WriteLine("G'day world!");
}
}

Right, there are not the most useful of classes but they will help show you how to use Castle to control creation of dependencies next. In our Program class place the following:


using System;
using Castle.Windsor;

namespace CastleIocConsole
{
class Program
{
static void Main(string[] args)
{
var container = new WindsorContainer();
container.AddComponent<IWriter, HelloWriter>();
var writer = container.Resolve<IWriter>();
writer.Write();
Console.ReadKey();
}
}
}


Hit F5 to debug and see that


Hello world 

was output as the HelloWorld class was resolved and its implementation of Write was called on the second to last line before Console.ReadKey().


Next up we show how to get Named instances of concrete types. Say for example you have a default type, but in the odd occasion you need a different type; well instead of breaking the notion of DI and using concrete dependencies, you can call for implementation by a key. In this example we register 2 concrete types to the same interface, however one has a key specified.


static void Main(string[] args) 
{
var container = new WindsorContainer();
container.AddComponent<IWriter, HelloWriter>();
container.AddComponent<IWriter, GdayWriter>("gday");
var writer1 = container.Resolve<IWriter>();
var writer2 = container.Resolve<IWriter>("gday");
Console.Write("writer1 output: ");
writer1.Write();
Console.Write("writer2 output: ");
writer2.Write();
Console.ReadKey();
}

The output is:


writer1 output: Hello world 
writer2 output: G'day world!

I find that most of the time I expect a default implementation so do not explicitly set a key at registration time, but its nice to know its there when you need it.


Next we manage LifeStyle...

Sunday, March 8, 2009

Real World Dependency Injection

On Thursday I gave a talk on Real World TDD at the Perth .Net Community of Practices. I'm not sure what people were expecting but the turn out was incredible, standing room only.. Hopefully I gave the punters what they were hoping for. A lot of secondary topics were raised, one being the notion of design and allowing TDD to help shape good design by following the SOLID principles. Dependency Injection was probably the most notable and for some people this may have been somewhat unusual. This article hopes to explain why we use DI and how we can use it in the real world.

What is Dependency Injection

Dependency Injection or dependency inversion is the idea that we depend on abstractions not concrete implementations. The example I gave in the talk was a trivial one using a logger as an example. Most of us use some sort of logging in our code so a lot of our code has a concrete dependency to a logging class eg:

public void DoSomething()
{
Logger.Log("Entering Do Something");
//Do the thing you wanted
Logger.Log("Exiting Do Something");
}


Why do we use it



In the example above, if we wanted to change the logger we used we would have to go into this code and change it, in fact we would most likely have to change it in every method call for something as prolific as logging. That is a lot of changes. Not only this but the reuse of this code without DI is limited and you will have to pass around the concrete logger as a reference to anything that wants to use it. This is not a big deal for logging but what if you had some potentially reusable components? Those concrete dependency will be come painful, reducing reusability very quickly. An example that parallels DI that many .Net developer will be familiar with is the Plug In pattern. Asp.Net membership is an example of this, in which we specify what type of provider we are going to using for membership. Our code doesn't change all we need to do is change the config in one place and the implementation is changed.



When do we use it



I will use DI anywhere that I have a dependency that is not static. (This may not be the best rule of thumb but it is how I do it, the number of static helper classes I have are minimal so this is not a big deal for me.)



Take for example we are using the MVP pattern; the presenter has a dependency on a view and on the model. The view however does not have a dependency on the presenter (despite what many coding samples out there may say) and the model does not have a dependency on the presenter but may do on other models data access components or services etc. Assume we have decided that the presenter is not in a valid state without these dependencies; We therefore decide that these should be injected as constructor items.



public class FooPresenter
{
private readonly IFooView view;
private readonly IFooModel model;

public FooPresenter(IFooView view, IFooModel model)
{
//DBC checks eg null checks etc
this.view = view;
this.model = model;
}
//rest of the presenter
}


Note: by stipulating the dependencies are read only they must be assigned by the end of the constructor. To me, this helps clarify the intention and I tend to use this over private properties eg



//I dont like this for constructor dependencies, 
//but it is valid
public IFooView View { get; private set; }




The presenter is now only dependent on the interfaces of the view and model. we can change From Winforms to WPF without any dramas, we can move from a web service based model to an EF model... we don't care about how the dependencies do their job,, they just have to adhere to the contract that is the interface.



To me this is critical part of TDD. This allows me to focus on the task at hand, eg writing the presenter, without having to worry about coding the model and view at the same time; all I have to do is create the interfaces that they have to adhere to while I create the presenter. This is typically done all at the same pace. I may decide I need to raise an event from the view, say "AddFooRequest". I create a test to listen for that event in the presenter test, create the event on the view interface, create a handler for the event in the presenter and wire it up. I have not done any concrete code in the view, just view interface, concrete presenter and its test fixture. This to me is already a huge benefit of DI.



How do  use it



The first problem people run into when using DI is when they try and plug pieces together. Basically we have stated that the object should not know about its concrete dependency, but something has to! Is it the object that is calling it? It would be silly if presenter A did not know about its dependencies but when navigating to presenter B it new about those dependencies so it could construct presenter B... we there are 2 realistic ways around it, "Poor Mans DI" and "Inversion of Control" containers.



Poor mans DI is a way of saying "I don't want to code to implementations, but I will anyway". Its actually a pretty good place to start when DI is still a relatively new concept. You basically have defaults in your class and allow for them to be overridden eg:



public class FooPresenter
{
private readonly IFooView view;
private readonly IFooModel model;

//Poor mans DI
public FooPresenter()
:this(new FooView(), new FooModel())
{}

//Complete ctor allowing for DI
public FooPresenter(IFooView view, IFooModel model)
{
//DBC checks eg null checks etc
this.view = view;
this.model = model;
}
//rest of the presenter
}


The problem with this is that if you are using DI everywhere then (in this example) the presenter will have to know how to create the model or the model will have to have poor mans DI too.



A better option is to have one place that knows how to construct things, like a big object factory. This is called your Inversion of Control container and a usually third party API's that become a critical part of you framework. Such containers are godsends in large projects and allow for quickly changing dependencies for whole solutions very quickly and cleanly. The common containers are StructureMap, Castle (Windsor) , Spring.net, Unity, Ninject etc. You will most likely at first use a tiny portion of these container capabilities, generally resolve and setting the concrete type to construct for a given abstraction. eg



//set a default for the whole application
Container.AddComponent<IFooModel, FooNhibernateRepository>();
Container.AddComponent<IFooView, FooWinFormView>();
Container.AddComponent<IFooPresenter, FooPresenter>();

//Retrive a concrete instance from the container
var presenter = Container.Resolve<IFooPresenter>();


The Container.Resolve call on the last line asks for the concrete instance of IFooPresenter. We have defined that above as been the concrete FooPresenter. We know that the FooPresenter has dependencies on IFooView and IFooService so the container will look for registered components too and try to instantiate them. We have specified that we want the container to create a FooNhibernateRepository any time we ask for an IFooModel and a FooWinFormView any time we ask for an IFooView. Most IoC containers will tend to take the greediest constructor (the one with the most parameters) so you can even migrate from poor mans DI to an IoC implementation quite smoothly.



NB: This is a generic wrapper that I use as I tend to use a different container depending on the employer/contract I work on, so I use an adapter pattern to isolate me from the varying syntax. If this approach appeals then check out the Common Service Locator at CodePlex



I hope this helps people move towards better designed software and an easier to use and looser, decoupled API.



Rhys