Tuesday, March 24, 2009

Rhino Mocks at Skills Matter: Sample Code

I had a great time talking about Rhino Mocks at Skills Matter last night with Abid Quereshi and Gojko Adzic. Thanks to everybody who came.

You can download the code here:

http://static.mikehadlow.com/Mike.RhinoMocksDemo.zip

Or get it straight from my Google code repository:

http://code.google.com/p/sutekicode/

Rhino Mocks can be downloaded here:

http://ayende.com/projects/rhino-mocks/downloads.aspx

The 3.5 documentation is here:

http://ayende.com/Wiki/Rhino+Mocks+3.5.ashx

The Rhino tools svn repository, which includes the source Rhino.Mocks is here:

https://rhino-tools.svn.sourceforge.net/svnroot/rhino-tools/trunk

The Rhino tools repository also contains the auto-mocking container:

https://rhino-tools.svn.sourceforge.net/svnroot/rhino-tools/trunk/testing

And lastly for Dylan, who asked about an auto-mocking container for Moq, it appears it's already been done. Daniel Cazzulino has a post about it here.

Friday, March 20, 2009

ALT.NET Brighton Beers. Tuesday 31st March

Iain Holder has organised the first Brighton ALT.NET Beers for Tuesday 31st March at the Prince Albert from 7pm.

If you're interested in going, leave a comment on Iain's blog post. It should be a great chance to meet up with other Brighton .NET developers. See you all there!

Wednesday, March 18, 2009

WCF / Windsor Integration: Adding Behaviours

Continuing my love fest with the Windsor WCF facility, today I'm going to show you how to add behaviours to your WCF service. Behaviours are the core extension point for WCF and allow you to do pretty much anything with your service. Here's a nice brief description by Mehran Nikoo (it was the first thing that popped up on google :)

The WCF Facility automatically discovers any registered WCF behaviours and adds them to the service. The really nice thing about this is that because the behaviours are also IoC hosted components, the container can automatically provide their dependencies just like any other component. If you need to use any of your services inside the behaviour, simply inject it through the constructor as normal.

Let's look at an example where we want to log the entry and exit from an operation. Here's a simple service:

[ServiceContract]
public interface IHelloService
{
    [OperationContract]
    string Hello(string name);
}
public class HelloService : IHelloService
{
    private readonly ILogger logger;
    public HelloService(ILogger logger)
    {
        this.logger = logger;
    }
    public string Hello(string name)
    {
        logger.WriteLine("In Hello()");
        return string.Format("Hello {0}", name);
    }
}

It has a single operation 'Hello' that takes a name and returns 'Hello <name>'. It also has a dependency on ILogger which it uses to log that the Hello operation has been invoked.

Now lets create a WCF behaviour:

public class TestEndpointBehaviour : IEndpointBehavior
{
    private readonly TestCallContextInitializer callContextInitializer;
    public TestEndpointBehaviour(TestCallContextInitializer callContextInitializer)
    {
        this.callContextInitializer = callContextInitializer;
    }
    public void Validate(ServiceEndpoint endpoint){}
    public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters){}
    public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime){}
    public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
    {
        foreach (var operation in endpointDispatcher.DispatchRuntime.Operations)
        {
            operation.CallContextInitializers.Add(callContextInitializer);
        }
    }
}

We want to write to the logger before and after every operation invocation, to do that we're creating an Endpoint behaviour. The Endpoint behaviour gives you an opportunity, the ApplyDispatchBehaviour method, to add a 'CallContextInitializer' that can intercept operation invocations.  Note that we resolve our CallContextInitializer from the IoC container by expecting it to be injected via a constructor parameter.

As an aside, I can't help feeling that the WCF behaviour API is overly complex, it hardly invites you in :) There's no way I would have worked out how to do this without looking at the documentation. Not at all the pit of success.

Rant over, here's our CallContextInitializer:

 

public class TestCallContextInitializer : ICallContextInitializer
{
    private readonly ILogger logger;
    public TestCallContextInitializer(ILogger logger)
    {
        this.logger = logger;
    }
    public object BeforeInvoke(InstanceContext instanceContext, IClientChannel channel, Message message)
    {
        logger.WriteLine("Before Invoke");
        return null;
    }
    public void AfterInvoke(object correlationState)
    {
        logger.WriteLine("After Invoke");
    }
}

The ICallContextInitializer interface has two methods: BeforeInvoke and AfterInvoke where which allow us to execute any actions before and after the operation is invoked. Here we're just using the logger to write some interesting stuff out. Note that because the TestCallContextInitializer is also an IoC component we can resolve any of our services as constructor arguments again. Here we using the same ILogger service that our HelloService uses.

Here's the configuration and a little test to show it all working:

[TestFixture]
public class WCFIntegration_Spikes
{
    private const string tcpEndpointAddress = "net.tcp://localhost:4321/HelloService";
    [SetUp]
    public void SetUp()
    {
    }
    [Test, Explicit]
    public void Simple_TCP_Service()
    {
        var container = new WindsorContainer()
            .AddFacility<WcfFacility>()
            .Register(
                Component.For<ILogger>().ImplementedBy<Logger>(),
                Component.For<TestCallContextInitializer>(),
                Component.For<TestEndpointBehaviour>(),
                Component.For<IHelloService>().ImplementedBy<HelloService>()
                    .ActAs(new DefaultServiceModel().AddEndpoints(
                        WcfEndpoint.BoundTo(new NetTcpBinding { PortSharingEnabled = false }).At(tcpEndpointAddress)
                    ))
            );
        var client = ChannelFactory<IHelloService>.CreateChannel(
            new NetTcpBinding { PortSharingEnabled = false }, new EndpointAddress(tcpEndpointAddress));
        Console.WriteLine(client.Hello("Mike"));
        container.Dispose();
    }                
}

We first register the WcfFacility as usual. Then we register our components. Note that we don't need to do any special configuration for our EndpointBehaviour, the WCF Facility takes care of this for us.

When we run the test we get this output to the console:

Before Invoke
In Hello()
After Invoke
Hello Mike

As expected our behaviour was installed and invoked.

Integrating WCF and Windsor like this provides a very slick way of doing web services. I'm very impressed with Craig Neuwirt's work, what a star. Shame he doesn't blog more about it.

Monday, March 09, 2009

Castle Windsor: Registering and resolving arrays of dependencies using the fluent registration API

The Castle Windsor fluent registration API is a powerful and beautiful thing, but it's very new and the documentation is still evolving. Mostly I find the best thing is just to read the code, especially the unit tests. Today I wanted to register an array of components that all implement the same interface, and then resolve them in a particular order for another component that expects an array of that interface in its constructor.

Here's how it's done. First lets define an interface and some types that implement it:

public interface IMyInterface { }
public class MyFirstThing : IMyInterface {}
public class MySecondThing : IMyInterface {}
public class MyThirdThing : IMyInterface {}

Then we have a component that has a dependency on IMyInterface:

public class HasArrayDependency
{
    private readonly IMyInterface[] myInterfaces;
    public HasArrayDependency(IMyInterface[] myInterfaces)
    {
        this.myInterfaces = myInterfaces;
    }
    public IMyInterface[] MyInterfaces
    {
        get { return myInterfaces; }
    }
}

Here's a test showing the registration:

[Test]
public void Demonstrate_fluent_registration_of_arrays()
{
    var container = new WindsorContainer()
        .Register(
            Component.For<HasArrayDependency>()
                .ServiceOverrides(
                    ServiceOverride.ForKey("myInterfaces").Eq(
                        "MyFirstThing",
                        "MySecondThing",
                        "MyThirdThing"
                    )
                ),
            AllTypes
                .FromAssembly(Assembly.GetExecutingAssembly())
                .BasedOn<IMyInterface>()
                    .WithService.FromInterface(typeof(IMyInterface))
                    .Configure(c => c.Named(c.Implementation.Name))
        );
    var hasArrayDependency = container.Resolve<HasArrayDependency>();
    Assert.That(hasArrayDependency.MyInterfaces[0].GetType().Name, Is.EqualTo("MyFirstThing"));
    Assert.That(hasArrayDependency.MyInterfaces[1].GetType().Name, Is.EqualTo("MySecondThing"));
    Assert.That(hasArrayDependency.MyInterfaces[2].GetType().Name, Is.EqualTo("MyThirdThing"));
}

There are a couple of things we need to do. If we simply register components like this:

var container = new WindsorContainer()
    .Register(
        AllTypes
            .FromAssembly(Assembly.GetExecutingAssembly())
    );

By default they will be named with their full type name rather than just the class name, so we have to use the Configure method with the lambda expression to change the component name to the class name.

Next we use the ServiceOverrides method to override the default dependency resolution. Here we are saying that for the constructor parameter named 'myInterfaces' we are going to supply the components named 'MyFirstThing', 'MySecondThing', and 'MyThirdThing'. Castle Windsor doesn't provide array parameters with any service of the array type by default, if you want that behaviour you need to use a custom sub dependency resolver as described here.

Thursday, March 05, 2009

Recursive LINQ with Y-combinator

I really enjoyed reading Wes Dyers blog post on the Y-combinator. He shows how you can write recursive lambdas in C#. It's pretty straightforward to use his techniques to write recursive LINQ statements which is great because it allows you to decompose the recursion into a series of extension methods. I was particularly inspired with this example, doing directory recursion, from Mauricio Scheffer.

Lets look at an example. Say we have an interface IComposite:

public interface IComposite<T>
{
    T Parent { get; }
    IList<T> Children { get; }
}

And a class that implements that interface, CompositeThing:

public class Thing : IComposite<Thing>
{
    public Thing(string name, Thing parent, bool isActive)
    {
        Name = name;
        Parent = parent;
        IsActive = isActive;
    }
    public string Name { get; private set; }
    public Thing Parent { get; private set; }
    public bool IsActive { get; private set; }
    private readonly IList<Thing> children = new List<Thing>();
    public IList<Thing> Children
    {
        get { return children; }
    }
}

Here's a method that creates a graph of CompositeThing:

private static CompositeThing BuildComposite()
{
    return new CompositeThing
    {
        Name = "Root",
        IsActive = true,
        Children =
            {
                new CompositeThing
                {
                    Name = "First Child",
                    IsActive = true,
                    Children =
                        {
                            new CompositeThing
                            {
                                Name = "First Grandchild",
                                IsActive = true
                            },
                            new CompositeThing
                            {
                                Name = "Second Grandchild",
                                IsActive = true
                            }
                        }
                },
                new CompositeThing
                {
                    Name = "Inactive Child",
                    IsActive = false
                },
                new CompositeThing
                {
                    Name = "Second Child",
                    IsActive = true,
                    Children =
                        {
                            new CompositeThing
                            {
                                Name = "Third Grandchild",
                                IsActive = true
                            }
                        }
                }
            }
    };
}

Now lets write an extension method that takes an IEnumerable<T>, returns the same and uses an HtmlTextWriter to write an unordered list:

public static IEnumerable<T> WriteHtmlLi<T>(this IEnumerable<T> composites, 
    HtmlTextWriter writer)
{
    writer.RenderBeginTag(HtmlTextWriterTag.Ul);
    foreach (var composite in composites)
    {
        writer.RenderBeginTag(HtmlTextWriterTag.Li);
        writer.Write(composite.ToString());
        yield return composite;
        writer.RenderEndTag();
    }
    writer.RenderEndTag();
}

Here's Wes Dyer's Y-combinator:

public class Functional
{
    private delegate Func<A, R> Recursive<A, R>(Recursive<A, R> r);
    public static Func<A, R> Y<A, R>(Func<Func<A, R>, Func<A, R>> f)
    {
        Recursive<A, R> rec = r => a => f(r(r))(a);
        return rec(rec);
    }
}

Now we can write nested lists of our CompositeThings:

 

public void DemonstrateWritingComposite()
{
    var root = BuildComposite();
    var htmlWriter = new HtmlTextWriter(Console.Out);
    var recurse = Functional.Y<CompositeThing, IEnumerable<CompositeThing>>(
        f => item => item.Children.Where(c => c.IsActive).WriteHtmlLi(htmlWriter).SelectMany(f));
    recurse(root).GetEnumerator().MoveNext();
}

It returns this HTML:

<ul>
	<li>First Child<ul>
		<li>First Grandchild<ul>
		</ul></li><li>Second Grandchild<ul>
		</ul></li>
	</ul></li><li>Second Child<ul>
		<li>Third Grandchild<ul>
		</ul></li>
	</ul></li>
</ul>

The great thing is that we can compose the recursion; in this case we're simply inserting a where clause to exclude non active things. The last line where we say recurse(root).GetEnumerator().MoveNext() is simply to trigger the recursion. There are actually zero elements in the resulting enumerable because the bottom of the recursion is reached when when the final SelectMany(f) calls item.Children and no children are returned.

Monday, March 02, 2009

What's the point of Value types?

Here's another post that started out as an answer to an excellent comment by Mike Boldischar:

"I'm reading through Domain Driven Design. One thing that bugs me is the idea of a "value" type. Why not just call those objects immutable entities? Maybe it's just a personal preference, but in my opinion, building "values" into the design adds little value. They only encapsulate a subset of entity values. Why not just specify immutable entities? Any thoughts?"

The (very) simple answer is that it's more about identity than immutability. Entities have an independent identity. You can ask for an individual entity by it's ID. Value types only exist in terms of their parent entities and have no separate identity. Think of a line (Entity) made up of some points (Value), or a contact (Entity) that has an address (Value).

A common anti-pattern is to have entities with large numbers of properties of basic types, such as int or string. Often they map 1-to-1 to a database table. Individual properties or groups of basic types usually have some meaning in terms of the business and should be factored into to value types. Take this 'contact' class for example:

public class Contact
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Address1 { get; set; }
    public string Address2 { get; set; }
    public string City { get; set; }
    public string Postcode { get; set; }
}

It's an entity, because has an Id, and has basic type properties that map directly to table columns. But looking at it, the properties naturally fall into two groups that have a real meaning in a business sense; name and address. It might make more sense to refactor it as:

public class Contact 
{
    public int Id { get; set; }
    public Name Name { get; set; }
    public Address Address { get; set; }
}
public class Name
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}
public class Address
{
    public string Address1 { get; set; }
    public string Address2 { get; set; }
    public string City { get; set; }
    public string Postcode { get; set; }
}

Here, Name and Address are value types, they don't have an Id. Why is this good? Because we're decoupling stuff to do with names from stuff to do with addresses. We can also reuse name and address in other entities. However, they make no sense as independent things and so don't need to have an identity. Note that the database table wouldn't change and a good ORM like NHibernate can easily manage this kind of mapping. The key is that we're breaking the 1-to-1 class-to-table link that's often the naive starting point for most object-relational mapping.