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.

Tuesday, February 24, 2009

An evening of mockery at Skills Matter on the 23 of March

Abid Quereshi and I will be talking about mocking frameworks at Skills Matter on the 23 March. The details are here.

Abid's going to be talking about Moq:

"Introduction to Moq: Pronounced "Mock-You", Moq is a simple yet powerful .NET Mocking library. Moq makes use of .NET lambda expressions, reducing the amount of test code you will need to write. This presentation will demonstrate Moq and highlight some main differences with other mock object frameworks."

I will cover Rhino Mocks, especially looking at the new 3.5 features and also taking a look at Automocking. It should be a great evening.

Monday, February 16, 2009

WCF / Windsor Integration: Using the perWebRequest lifestyle

I briefly introduced Windsor WCF Integration a while back. I've been using it successfully in one of my current projects, but we had an issue recently with enabling the 'perWebRequest' lifestyle. Our project also uses the Windsor NHibernate Facility which automatically provides 'session per request' that we wanted to reuse with our WCF services. Both require a reference to the current HttpContext, but by default WCF does not integrate with the ASP.NET pipeline. This is by design, because it is intended that you should be able to host your WCF service with diverse protocols/hosts, not just HTTP/IIS/ASP.NET. But if you are simply using WCF to host services alongside an existing ASP.NET application and you want to reuse the same Windsor configuration for both it would be useful if WCF could gain access to the ASP.NET pipeline.

And voila! There is indeed a way of configuring WCF to integrate, simply set the serviceHostingEnvironment aspNetCompatibilityEnabled property to 'true' like this:

  <system.serviceModel>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
  </system.serviceModel>

You also need attribute your service class to require/allow integration:

[AspNetCompatibilityRequirements(
    RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
public class MyService : IMyContract
{
    ....
}

Now HttpContext.Current returns the current HttpContext as expected and both the 'perWebRequest' lifestyle and the NHibernate Facility work as expected. It also means that your service can participate in your application's security settings, session state and impersonation if that's what floats your boat. Of course it doesn't help you if you want to host your service outside of IIS. In that case you'd probably want to either implement your own custom lifestyle that works with the OperationContext (WCF's equivalent to HttpContext) or implement an IEndpointBehavior. There's an example of how to do the latter in the WCF Facility's unit tests. Check out the UnitOfworkEndPointBehavior class.

More detail on the ASP.NET compatibility settings can be found in this excellent blog post by Wenlong Dong.

Friday, February 06, 2009

VBug London 10th Feb: Why to I need an Inversion of Control Container?

I'm going to be giving my IoC container talk at VBug London next Tuesday (10th February). It's going to be at Anteo Group, 8-9 Hayne Street, London, EC1A 9HH (see map below). Arrive at 6.30pm for a 7pm start. It's being organised by Sam Morrison who assures me that there will be plenty of time for socialising after the talk.

 


View Larger Map

Friday, January 30, 2009

Further Reading on IoC Containers

Eric Nelson was kind enough to invite me to contribute to the MSDN Flash newsletter. It should be published next Wednesday. The article was limited to 500 words, only enough for a very brief introduction to IoC containers, so for those who want to explore this exciting topic further, here are some links:

Oren Eini's (AKA Ayende) MSDN article: Inversion of Control and Dependency Injection: Working with Windsor Container:

http://msdn.microsoft.com/en-us/library/aa973811.aspx

Hamilton Verissimo's Code Project article: Introducing Castle - Part 1:

http://www.codeproject.com/KB/architecture/introducingcastle.aspx

The first chapter of Dhanji R. Prasanna's new book on Dependency Injection:

http://www.manning.com/prasanna/prasanna_meapch1.pdf

 

Some popular IoC containers for .NET:

Castle Windsor. This one is probably the most popular, I'm biased though since it's the one I use. It was originally written by Hamilton Verissimo (who now works on the MEF team) and maintained is by Ayende.

StructureMap. Also very highly regarded. It's author, Jeremy Miller, has an excellent blog.

Spring.NET. A port of the popular Java Spring container.

Ninject and Autofac are both interesting newcomers.

Unity is from the Microsoft Patterns and Practices group.

Glen Block will kill me, but MEF is also an IoC container, although one that's specifically targeted at developing plug-in application architectures.

Thursday, January 22, 2009

Tonight’s talk: Implementing the Repository Pattern

I’m going to be talking at this evening’s Open Source .NET Exchange at Skills Matter. It’s just around the corner from Farringdon station and is ably organised by Gojko Adzic. I think there are still some places left. It’s free, but you need to register in advance. It should be great evening with some excellent speakers. I’ll be there too :)

You can download the slides for my talk here:

http://static.mikehadlow.com/Implementing the Repository Pattern.pptx

See you there!