Sunday, June 27, 2010

Is Microsoft the IBM of the 2010’s?

I’d like to take you back 15 years to when I was just starting out on my career in IT. Windows 95 has just been released, the internet was beginning to escape from academia and the buzz was all about client-server. The small consulting company that I worked for was very excited about getting into VB and SQL Server, but when I asked about the internet it was dismissed as a ‘fad’.

In those days Microsoft generated huge excitement and fear in the IT industry and our little company did very well from exploiting that. I remember many conversations with more senior members of the profession who told me that client-server systems could never replace their beloved AS400s, and how VB was a toy compared to Cobol. Of course they were wrong. Microsoft was rapidly taking over business computing, and before long Windows and Office became ubiquitous.

Microsoft’s business model stemmed from Bill Gates’ thought experiment: ‘what if hardware were free?’ If hardware was free, or at least a commodity, the owner of the operating system would own the IT market. Microsoft’s entire business has been based on this premise. It made Gates the world’s richest man and Microsoft the richest company. But sitting on a monopoly can make you complacent. What if someone comes along and asks the question, ‘what if software were free?’ If software were free, Microsoft’s whole foundation would be in question. The problem for Microsoft is that a lot of people have been asking that question.

Microsoft is being relentlessly squeezed from two directions.

The cloud is starting to provide a viable alternative for small and medium sized organisations. Instead of a rack of Windows 2008 servers, why not simply sign up for Google Apps for Domains? No more installing, managing, backing up of file servers and exchange, no more hunting around for users who have lost their word documents. Of course the functionality is nowhere near what Microsoft server products plus Office can provide, but lots of people don’t need all those bells and whistles. Microsoft began in the server space by replacing Oracle and Sun and IBM in smaller organisations and now Google is doing the same thing.

At the other extreme, Linux is the OS of choice if you are huge. It simply doesn’t make sense to run a server farm of Windows machines - from both a technical and a financial point of view. If all the biggest players are running Linux, it’s an easy sell for a typical medium sized company’s CTO to suggest that they should do the same. Microsoft still pretty much owns the small and medium sized server space, but it’s really now because of inertia rather than because they are a better choice.

Far more scary for Microsoft is the mobile market. This is where the action is in 2010. Two titans, Apple and Google, are locked in a struggle. Google will win, for the same reason that Microsoft won against Apple the first time around: Apple is still a hardware company. In this war Microsoft is a bystander, even though Phone 7 is undoubtedly a good product it is still a niche one. Microsoft cannot compete because their business model of selling operating system licences ties their hands before they can even get off the start line.

For now Android runs on Mobile phones, but soon there will be tablets and TV top-set boxes. Windows will be relentlessly pushed out of the consumer market. For many businesses, the temptation will be to move from Office to Google Apps and give each desk an appliance. The cost savings in both licences and support will be huge. Microsoft’s hold over both the office desktop and applications will be under threat.

The Microsoft of 2010 is looking like the IBM of the 90’s, an incumbent giant without an answer for the changing landscape around it. In the same way, I would not expect Microsoft to disappear (although that is a possibility), but they will gradually become irrelevant to the future of IT.

So what does this mean for .NET developers like you and me? Well, we could just keep doing the same old thing, but the opportunities for work will slowly wither away, much like the Cobol guys found in the 90’s. So what should we do? I personally think Objective C and iPhone development is a dead end. Google will win the mobile OS war. I’m just waiting for Nokia to give up on MeGo, accept the inevitable, and start making Android phones. HTC is looking like becoming the Dell of the 2010s.

So Android will be the new Windows. Any Linux skills will be a good thing. Java skills will help too. Server side code will run on Linux, so once again: Linux skills are good. Being able to interface with Google Apps will be an excellent skill to have, so being comfortable with the Google APIs will pay dividends. Everyone should try to build a non-trivial Android app.

What about programming languages? Here the future is less clear. I would love it if Mono took off and allowed me to take my C# and .NET skills to Linux based OSs, but I really don’t think it’s likely. The CLR is now almost ten years old and is beginning to show its age. There’s not really a compelling reason to adopt it over the JVM. I think there has to be progress in programming languages. I’m learning Haskell simply because it seems to be where all the good ideas in language development are coming from (just look at C# 3.0), but the dynamic trio of Javascript, Ruby and Python are also very exciting these days. On the browser, standards always win in the end, and the future belongs to HTML5, not to Flash, and even less to Silverlight.

One thing is pretty certain, I won’t be making any attempt to learn the plethora of Microsoft server solutions; Sharepoint, Dynamics etc. They are the final indication that MS really is becoming IBM. There’s plenty of money to be made as a reseller doing customisations for these products, but it’s no place for a geek.

So thanks Microsoft, it’s been great, but now it’s time to move on.

Friday, May 28, 2010

Brighton ALT.NET Beers. 7pm Tuesday 1st June at The Skiff

The next Brighton ALT.NET Beers will be held at the co-working venue ‘The Skiff’ at 7.00 pm on Tuesday 1st June. I’ll be hosting again.

The address is: The Skiff, 49 Cheltenham Place, Brighton, BN1 4AB


View Larger Map

The format will be the same as usual, a quick round of suggestions for topics, voting and then an evening of beer and geekery.

What better way to recover from the rigours of the bank holiday weekend?

Saturday, May 15, 2010

Skillsmatter Progressive .NET Tutorials May 12-14th 2010

This week I had the pleasure of talking at the second Progressive .NET Tutorials organised by Skillsmatter in London. I presented a four hour workshop on advanced Castle Windsor. You can watch the videos here:
Part 1
Part 2
Part 3

You can get the code from my Google Code repository here.

To be honest, I’ve been getting quite bored of being ‘windsor-man’ in the UK alt-net community and after the last time I presented my ‘introduction to IoC’ talk, I vowed I would never do it again. But doing this workshop was a lot of fun. Having four hours to get to grips with some more advanced topics was really nice. It helped that I had a very keen audience who asked some great questions and really got involved. It was also interesting to see some of the common misconceptions and problems people have with IoC containers. It seems that most confusion comes from deciding what should come out of a container and what should not. This often manifests itself in questions about factories and how you should resolve things like domain entities, or how you should do resolution within them. The simple answer is you don’t, but it’s difficult to explain what is an appropriate ‘service’ and what is not. It’s something I’m still struggling with.

I only attended the Wednesday session. I had intended to attend on Friday as well, but my teeth decided otherwise and I spent the morning in my dentist’s chair instead. So the only other session I got to see was Robert Pickering’s introduction to F# and even though I saw him do a similar talk last year, I still found it very interesting and learnt a whole load of stuff about F# that I didn’t know before.

Wendy, Skillsmatter’s boss, took all the speakers out to dinner and I had a great evening chewing things over with Dave Laribee, Scott Cowan, Toby Henderson, Ayende and Ian Cooper. But probably the most significant revelation of the day was that I finally discovered the true identity of prolific tweeter @Daneel3001 :)

Monday, May 03, 2010

10 Advanced Windsor Tricks – 13. Use SubContainers to replace dependencies on context

Here’s part thirteen of (slightly more than) 10 Advanced Windsor Tricks.

Say you have a multi-tenanted application and you want to have different components provided for different customers. One way of doing this is to create an IHandlerSelector which allows you to choose which components get provided depending on some context. It’s the technique I use for Suteki Shop’s multi-tenancy and I’ve written about it several times in the past: here and here.

An alternative approach is to use a SubContainer. SubContainers are a way to provide separate scoping and resolution, independent of your main container. In this scenario (described here by Bill Pierce) you provide a SubContainer for each tenant, and simply register the components that that tenant needs that are different from the default.

Here’s a simple demonstration:

public void SubContainer_should_get_components_of_parent()
{
    var parentContainer = new WindsorContainer()
        .Register(
            Component.For<Root>().LifeStyle.Transient,
            Component.For<ChildNode>().LifeStyle.Transient,
            Component.For<IGrandChild>().ImplementedBy<GrandChild>().LifeStyle.Transient
        );

    var subContainer1 = new WindsorContainer()
        .Register(
            Component.For<IGrandChild>().ImplementedBy<FirstGrandChild>().LifeStyle.Transient
        );

    var subContainer2 = new WindsorContainer()
        .Register(
            Component.For<IGrandChild>().ImplementedBy<SecondGrandChild>().LifeStyle.Transient
        );


    parentContainer.AddChildContainer(subContainer1);
    parentContainer.AddChildContainer(subContainer2);

    var parentRoot = parentContainer.Resolve<Root>();
    parentRoot.Accept(node => Console.WriteLine("Resolved from parent container: {0}", node.GetType().Name));

    var child1Root = subContainer1.Resolve<Root>();
    child1Root.Accept(node => Console.WriteLine("Resolved from subContainer1: {0}", node.GetType().Name));

    var child2Root = subContainer2.Resolve<Root>();
    child2Root.Accept(node => Console.WriteLine("Resolved from subContainer2: {0}", node.GetType().Name));
}

Which outputs:

Resolved from parent container: Root
Resolved from parent container: ChildNode
Resolved from parent container: GrandChild
Resolved from subContainer1: Root
Resolved from subContainer1: ChildNode
Resolved from subContainer1: FirstGrandChild
Resolved from subContainer2: Root
Resolved from subContainer2: ChildNode
Resolved from subContainer2: SecondGrandChild

I’m creating a parent container and registering three components, Root, ChildNode and IGrandChild. Root depends on ChildNode and ChildNode depends on IGrandChild. I then create two subContainers and register alternative IGrandChild components for each.

I’ve got a little visitor pattern thing going to run some function over each object in the graph so that I output the component types.

When I resolve Root from the parent container, I simply get an object graph with IGrandChild implemented by GrandChild. So my default implementation works as expected.

The really cool stuff happens when I resolve Root from the sub containers. Root is not registered with the sub containers, so they resolve it from their parent (parentContainer). The same goes for ChildNode. But the IGrandChild dependency is satisfied by the sub container’s registration. With this technique you can surgically replace specific dependencies.

Thursday, April 29, 2010

Brighton ALT.NET Beers. 7pm Tuesday 4th May at The Skiff

The next Brighton ALT.NET Beers will be held at the co-working venue ‘The Skiff’ at 7.00 pm on Tuesday 4th May. I’ll be hosting again.

The address is: The Skiff, 49 Cheltenham Place, Brighton, BN1 4AB


View Larger Map

The format will be the same as usual, a quick round of suggestions for topics, voting and then an evening of beer and geekery.

See you there!

Monday, April 26, 2010

Currying vs Partial Function Application

There’s a lot of confusion over these two terms. By myself included. But I’m pretty happy now that I understand the difference and wanted to share my newfound knowledge with you, dear reader.

First let’s understand the arrow (->), it’ll make the discussion much easier. This operator (->) is used in F#, Haskell and other functional programming languages to define function types. If you’ve got an ‘add’ function that takes two int arguments and returns an int, you would write that function’s type like this (in F#):

int * int –> int

Which says, the function takes a tuple of two int values and returns an int. Remember F# functions only ever have one argument and one return value. Now take a look at this type:

int –> int –> int

This function takes an int value and returns a function. The function it returns takes an int value and returns an int value. Turning the first example into the second example is ‘currying’. So currying is the process of taking a function with multiple arguments and turning it into a function that takes only one argument and returns a new function that takes the second argument and returns a value (or a further function which takes the third argument and returns a value or…. you get the picture).

Partial application is when you actually use a such a curried function. So in our add example above, if we have defined a curried add (in F#) as:

> let add a b = a + b;;

val add : int -> int -> int

Isn’t that neat, we don’t actually need to ‘curry’ add, F# provides curried functions by default. Now we use the add function like this:

> let add5 = add 5;;

val add5 : (int -> int)

F# is now telling us that add5 is a function that takes an int and returns an int. We’ve partially applied add. Now we can use add5 like any other function:

> add5 2;;
val it : int = 7
> add5 7;;
val it : int = 12

Having curried functions by default is very cool indeed. It means we can use partial application to compose functions in the same way that we use dependency injection to compose classes in object-oriented languages.

Friday, April 16, 2010

NHibernate Get<T> vs Load<T> and sub types

Here’s some interesting NHibernate behaviour that’s been tripping me up. Say we have a base class ‘Content’ and a sub class ‘Menu’, the following tests pass:

[Test]
public void Get_returns_a_proxy_of_the_correct_type()
{
    InSession(session =>
    {
        var content = session.Get<Content>(menu1Id);
        var menu = content as Menu;
        menu.ShouldNotBeNull("menu is null");
    });
}

[Test]
public void Load_does_not_get_return_a_proxy_of_the_correct_type()
{
    InSession(session =>
    {
        var content = session.Load<Content>(menu1Id);
        var menu = content as Menu;
        menu.ShouldBeNull();
    });
}

That’s right, don’t expect ‘as’ to work on lazily loaded entities.

Get eagerly loads, so it runs some SQL against the database:

SELECT 
    content0_.ContentId as ContentId15_0_, 
    content0_.Name as Name15_0_, 
    content0_.Position as Position15_0_, 
    content0_.IsActive as IsActive15_0_, 
    content0_.UrlName as UrlName15_0_, 
    content0_.ParentContentId as ParentCo7_15_0_, 
    content0_.ContentTypeId as ContentT8_15_0_, 
    content0_.Controller as Controller15_0_, 
    content0_.Action as Action15_0_, 
    content0_.Text as Text15_0_, 
    content0_.ContentType as ContentT2_15_0_ 
FROM "Content" content0_ 
WHERE content0_.ContentId=@p0;@p0 = 1 [Type: Int32 (0)]

This includes the discriminator column, ContentType, so NHibernate knows that this item should be created as a menu.

Load, lazy loads, so for this example no SQL is run against the database. The only thing NHibernate knows about this entity is that we’ve asked for ‘Content’ via the type parameter of the Load method, so it returns a proxy class that inherits from Content. When we use the ‘as’ operator to cast it to a menu it fails (returns null).

Interestingly, the type is still incorrect after we examine some properties so that the proxy is populated with a call to the db:

[Test]
public void Type_is_not_correct_after_the_entity_loaded()
{
    InSession(session =>
    {
        var content = session.Load<Content>(menu1Id);
        Console.WriteLine(content.Name);
        var menu = content as Menu;
        menu.ShouldBeNull();
    });
}

Event though this test causes the select statement to be executed against the DB to populate the entity, the proxy is still of type Content.

So rather than using the ‘as’ operator, I’ve implemented my own CastAs<T> extension method that understands NHibernate proxies:

public static class CastExtensions
{
    public static T CastAs<T>(this object source) where T : class
    {
        if(source is INHibernateProxy)
        {
            var type = NHibernateUtil.GetClass(source);
            if (type != typeof (T))
            {
                throw new ApplicationException(string.Format("Cannot cast {0} to {1}", type.Name, typeof (T).Name));
            }

            return ((INHibernateProxy) source).HibernateLazyInitializer.GetImplementation() as T;
        }
        return source as T;
    }
}

Now the we get the correct sub type:

[Test]
public void Use_CastAs_to_cast_lazy_loaded_entities()
{
    InSession(session =>
    {
        var content = session.Load<Content>(menu1Id);
        Console.WriteLine(content.GetType().Name);
        var menu = content.CastAs<Menu>();
        menu.ShouldNotBeNull();
    });
}

Update

As Mookid pointed out in the comments, doing this kind of casting, especially of domain classes, is a code smell. What I should be doing instead is using polymorphism or the visitor pattern. Please read his post below which is a very cool alternative take on the problem:

http://mookid.dk/oncode/archives/991

Moving Suteki Shop from Linq-to-SQL to NHibernate

I’ve finished getting the basic features of Suteki Shop running with NHibernate. Anyone who’s been following this project knows that it was originally written with Linq-to-SQL. Linq-to-SQL worked fine for the initial iterations of Suteki Shop, but there are lots of things I wanted to do with the project that would have been hard or impossible to do without the move.

Linq-to-SQL not a true ORM in the sense that it doesn’t support persistence ignorance, it’s more a object based projection of a relational database. Each class directly represents a table row, including foreign keys. One of the main pain points in the transition was removing all the application code that referenced these foreign keys and replacing them with object references instead. So for example, instead of changing the int value of Contact.CountryId I would change the actual referenced entity, Contact.Country.

The other place where I had to do lots of work was in my Linq queries. The NHibernate trunk now has a native Linq provider written by Steve Strong, so you can write:

var customer = session.Query<Customer>().Where(c => c.Name == "Fred").FirstOrDefault();

The main difference between the Linq-to-SQL provider and the NHiberante one is in the way they treat expressions that they don’t understand. Linq-to-SQL will translate as much of the expression that it can to SQL, get the result, and then allow Linq-to-objects to do the rest. The NHibernate provider will throw an exception saying that it doesn’t understand the expression. There are pros and cons to both approaches. Linq-to-SQL will always give you what you want, but maybe in an inefficient way you weren’t expecting, whereas NHibernate will force you to think about how you structure your queries. There are no surprises, but it’s a mark against persistence ignorance. Right now, I’m liking the NHibernate no surprises approach.

Whilst doing the conversion I ran into a problem with the OfType<T>() Linq extension method. I was using it in several places but NHibernate complained that it didn’t support it. I tweeted about it and almost immediately Steve Strong replied that it should be easy to implement. The next day he committed it to the NHibernate trunk and my queries all worked.

steve-strong

Steve Strong, you are an awesome open source hero!

One of my major regrets with the way that I originally wrote Suteki Shop is binding views to entities, rather than using a view model. At first this can seem like an easy-win, but doing this work showed how can soon lead to all sorts of difficulties. Displaying the view model in the view is not so much of a problem - except in entity loading overhead. The problems mostly manifest themselves at the binding stage. I extended the ASP.NET MVC DefaultModelBinder to work with NHibernate entities, and it mostly works, but I spent far too much time resolving tricky binding issues with complex object graphs. I would have made my life much easier by binding to a nice flat view model and then manually mapping that to my entities.

Persistence ignorance is a dream, a nirvana, where we’d love to be, but no ORM will give you true persistence ignorance. NHibernate is far better in this regard than Linq-to-SQL, but you still have to do things the NHibernate way. Your ORM will hugely influence the way you build your application and although the persistence ignorance ideal should mean you can swap them with little difficulty, moving from Linq-to-SQL to NHibernate was a major piece of work, far more than I expected.

Tuesday, April 06, 2010

A Custom ASP.NET MVC Model Binder for Repositories

How do you take the values posted by an HTML form and turn them into a populated domain entity? One popular technique is to bind the POST values to a view-model and then map the view-model values to an entity. Since your action method’s argument is the view-model, it allows you to decide in the controller code if the view-model is a new entity or an existing one that should be retrieved from the database. If the view-model represents a new entity you can directly create the entity from the view-model values and then call your repository in order to save it.  In the update case, you can directly call your repository to get a specific entity and then update the entity from the values in the view-model.

However, this method is somewhat tedious for simple cases. Is a view-model always necessary? Wouldn’t it be simpler to have a model binder that simply created the entity for you directly? Here’s my attempt at such a binder:

updated to fix bug when a child entity is changed

public class EntityModelBinder : DefaultModelBinder, IAcceptsAttribute
{
    readonly IRepositoryResolver repositoryResolver;
    EntityBindAttribute declaringAttribute;

    public EntityModelBinder(IRepositoryResolver repositoryResolver)
    {
        this.repositoryResolver = repositoryResolver;
    }

    protected override object CreateModel(
        ControllerContext controllerContext, 
        ModelBindingContext bindingContext, 
        Type modelType)
    {
        if (modelType.IsEntity() && FetchFromRepository)
        {
            var id = GetIdFromValueProvider(bindingContext, modelType);
            if (id.HasValue && id.Value != 0)
            {
                var repository = repositoryResolver.GetRepository(modelType);
                object entity;
                try
                {
                    entity = repository.GetById(id.Value);
                }
                finally
                {
                    repositoryResolver.Release(repository);
                }
                return entity;
            }
        }

        // Fall back to default model creation if the target is not an existing entity
        return base.CreateModel(controllerContext, bindingContext, modelType);
    }

    protected override object GetPropertyValue(
        ControllerContext controllerContext, 
        ModelBindingContext bindingContext, 
        System.ComponentModel.PropertyDescriptor propertyDescriptor, 
        IModelBinder propertyBinder)
    {
        // any child entity property which has been changed, needs to be retrieved by calling CreateModel, 
        // we can force BindComplexModel (in DefaultModelBinder) do this by
        // setting the bindingContext.ModelMetadata.Model to null
        var entity = bindingContext.ModelMetadata.Model as IEntity;
        if (entity != null)
        {
            var id = GetIdFromValueProvider(bindingContext, bindingContext.ModelType);
            if (id.HasValue && id.Value != entity.Id)
            {
                bindingContext.ModelMetadata.Model = null;
            }
        }
        return base.GetPropertyValue(controllerContext, bindingContext, propertyDescriptor, propertyBinder);
    }


    private static int? GetIdFromValueProvider(ModelBindingContext bindingContext, Type modelType)
    {
        var fullPropertyKey = CreateSubPropertyName(bindingContext.ModelName, modelType.GetPrimaryKey().Name);
        if (!bindingContext.ValueProvider.ContainsPrefix(fullPropertyKey))
        {
            return null;
        }

        var result = bindingContext.ValueProvider.GetValue(fullPropertyKey);
        if (result == null) return null;
        var idAsObject = result.ConvertTo(typeof (Int32));
        if (idAsObject == null) return null;
        return (int) idAsObject;
    }

    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        bindingContext.ModelMetadata.ConvertEmptyStringToNull = false;
        var model = base.BindModel(controllerContext, bindingContext);
        ValidateEntity(bindingContext, controllerContext, model);
        return model;
    }

    protected virtual void ValidateEntity(
        ModelBindingContext bindingContext, 
        ControllerContext controllerContext, 
        object entity)
    {
        // override to provide additional validation.
    }

    private bool FetchFromRepository
    {
        get
        {
            // by default we always fetch any model that implements IEntity
            return declaringAttribute == null ? true : declaringAttribute.Fetch;
        }
    }

    public virtual void Accept(Attribute attribute)
    {
        declaringAttribute = (EntityBindAttribute)attribute;    
    }

    // For unit tests
    public void SetModelBinderDictionary(ModelBinderDictionary modelBinderDictionary)
    {
        Binders = modelBinderDictionary;
    }
}

I’ve simply inherited ASP.NET MVC’s DefaultModelBinder and overriden the CreateModel method. This allows me to check if the type being bound is one of my entities and then grabs its repository and gets it from the database if it is.

Now, I’m most definitely not doing correct Domain Driven Development here despite my use of terms like ‘entity’ and ‘repository’. It’s generally frowned on to have table-row like settable properties and generic repositories. If you want to do DDD, you are much better off only binding view-models to your views.

Monday, April 05, 2010

Microsoft TechDays – Open Source on .NET. April 14th, Shepherd’s Bush.

Register here: http://techdays-oss.eventbrite.com/

Sebastien Lambla (oh how I want to spell his surname Lambda, that would be so cool) who is the giant brain behind the awesome web framework OpenRasta, has organised an open source evening as part of Microsoft TechDays. There are going to be 6 talks. The current line up looks like this:

  • OpenRasta - A web application framework for .net

  • An introduction to IoC with Castle Windsor <- ME!

  • FluentValidation, doing your validation in code

  • CouchDB, NoSQL: designing document databases

  • Testing your asp.net applications with IronRuby

  • Building a data-driven app in 15 minutes with FluentNHibernate

There’s also going to be free food and drink – what is there not to like?

See you there.