Posted by: Stephen Oakman | August 15, 2009

Asus Eee PC 1005HA

I’ve just received my new netbook and I must admit I’m impressed so far. I got this with the intention of blogging more and so far the keyboard on it feels quite comfortable. The battery life has a reported 10 hours which is amazing and I’m looking forward to seeing how long it lasts at user groups and conferences.

I’m going to upgrade it to 2Gb when the memory arrives and will then put Windows 7 on it as using XP feels a little strange these days (I’m spoilt). I’m refraining from putting visual studio on it but I may eventually so I can see what it’s like.

Well, this is the first post from it. Now I can start work on the series of posts that have been bouncing around in my mind since the altnetuk conference. Time to spend time with family now though :)

Posted by: Stephen Oakman | August 1, 2009

Enjoyed last nights AltNetBeers

We attended the AltNetBeers last night as part of the AltNetUk conference weekend. It was a thoroughly enjoyable evening involving far too much drink but the discussion was good. I even managed to sit on the ‘park bench’ at one point and give my views on Given When Then tests and how they can structured etc.

So today is the open space code day which I am seriously looking forward too (but hopefully with less drinking involved).

If anyone is reading this and is also going today (or to the actual altnetuk conference tomorrow) then please say hi. For anyone at the altnetbeers last night – we were the one’s playing 9 ball :)

Posted by: Stephen Oakman | July 27, 2009

Refining the removal of strings from WPF dependency properties

Following on from the previous post regarding removing the strings when registering Dependency Properties I wanted to fine tune it so we could remove the need for specifying the type we are defining the dependency properties on.

The way to do this is to cache a static instance of the DependencyPropertyHelper class in our class like so:

private static readonly DependencyPropertyHelper DependencyProperty = new DepenencyPropertyHelper<WorldViewModel>();

Now we can change our dependency property registrations from this:

public static readonly DependencyProperty CameraLookDirectionProperty =
    DependencyPropertyHelper<WorldViewModel>.Register(x => x.CameraLookDirection); 

To this:

public static readonly DependencyProperty CameraLookDirectionProperty =
    DependencyProperty.Register(x => x.CameraLookDirection); 
Posted by: Stephen Oakman | July 14, 2009

Removing the strings when registering Dependency Properties

We’ve just been doing some multi-touch WPF work. Well, when I say ‘we’ I really mean everyone else apart from me as it got into what I consider to be serious math of which I have very little (zero) knowledge. Anyway, I digress.

One of the things that has bugged me with WPF are the Dependency Properties, or at least the ugliness of them. An example is

public static readonly DependencyProperty CameraPostionProperty =
    DependencyProperty.Register("CameraPosition", typeof(Point3D), typeof(WorldViewModel));

What bug’s me most is the Register method. I don’t like the magic string which can get lost during a refactor and it would be far too easy to get the order of the type parameters the wrong way round. Just a misspelling of the string is enough for it to not work (which happens far more often than it should).

A much preferable syntax would be the following:

public static readonly DependencyProperty CameraLookDirectionProperty =
    DependencyPropertyHelper<WorldViewModel>.Register(x => x.CameraLookDirection);

With this syntax theirs no magic strings and no types to get mixed up.

This syntax is achieved with the code below:

public static class DependencyPropertyHelper<T>
{
    public static DependencyProperty Register<TR>(Expression<Func<T, TR>> action)
    {
        var member = (MemberExpression)action.Body;
        return DependencyProperty.Register(member.Member.Name, typeof(TR), typeof(T));
    }
}

Now we are taking the string from the member name itself and the order of the types is picked up correctly.

The Castle Windsor 2.0 release contains the auto registration that was previously only available on the trunk (as opposed to the previous 1.0 RC 3 release). The two main auto registration methods we use are the following:

container.Register(
    AllTypes
    .Of<IController>()
    .FromAssembly(Assembly.GetExecutingAssembly())
    );

container.Register(
    AllTypes
    .Pick()
    .FromAssembly(Assembly.GetExecutingAssembly())
    .WithService
    .FirstInterface()
    );

The first one registers all ASP.NET MVC controllers into the container, whilst the second one register’s all other classes using the first interface as the service to register against. So if you have a class ServiceImplementation that implements IService then container.Resolve<IService>() will return an instance of ServiceImplementation.

Their is currently an issue with this second mechanism though in regards to derived classes. To help explain, consider the following:

public interface IFirstServiceOnBase 
{
    // …

public interface IFirstServiceOnDerived : IFirstServiceOnBase 
{
    // …

public class BaseService : IFirstServiceOnBase 
{
    // …

public class DerivedService : BaseService, IFirstServiceOnDerived
{
    // …
}

In this example we have BaseService which implements IFirstServiceOnBase. We then have DerivedService which inherits from BaseService and also implements IFirstServiceOnDerived.

What we want to happen is that when the previous auto registration reflects on our types we expect a call to container.Resolve<IFirstServiceOnBase>() to resolve to BaseService and for container.Resolve<IFirstServiceOnDerived>() to resolve to DerivedService.

However, we find that the second resolve on the container for IFirstServiceOnDerived actually throws an exception as it wasn’t registered.

So, why is this?

The answer is that interfaces are listed in the order of lowest base class first up to derived classes next. So the WithService.FirstInterface() call tries to register DerivedService against IFirstServiceOnBase as opposed to IFirstServiceOnDerived, and finds that this service interface has already been registered against BaseService.

Our fix for this is a new extension method:

public static class WindsorExtensions
{
    public static BasedOnDescriptor FirstInterfaceOnType(this ServiceDescriptor serviceDescriptor)
    {
        return serviceDescriptor.Select((type, baseType) =>
        {
            var interfaces  = type.GetInterfaces().Except(type.BaseType.GetInterfaces());
            if (interfaces.Count() == 0)
                return null;
            return new [] {interfaces.First()};
        });
    }
}

The FirstInterfaceOnType extension method filters out the base interfaces and will now correctly register DerivedService against IFirstServiceOnDerived as we expect.

This changes our second auto registration call to the following:

container.Register( 
    AllTypes 
    .Pick() 
    .FromAssembly(Assembly.GetExecutingAssembly()) 
    .WithService 
    .FirstInterfaceOnType() 
    );
Posted by: Stephen Oakman | June 9, 2009

Using schemas with SQLite for in-memory NHibernate tests

We have been using NHibernate and using SQLite for in-memory tests which has worked very well for us but hit an issue when using schemas.

We wanted to separate out the tables used by our services through the use of schemas as schemas provides a very nice clean logical separation. However, although NHibernate supports schemas through the schema attribute on your class mappings, our SQLite tests fail as SQLite doesn’t support schemas.

We looked into ways around this. Our first port of call was to look at whether their is a way of managing this through our own NHibernate dialect class but our investigations led us to a dead end – although we plan on revisiting this later.

So we switched to looking at the SQLite ADO.NET provider. We figured that if we wrapped this then we could intercept the calls to it and override the “schema.table” requests into “schema_table”.

To achieve this we provide our own implementations of the following:

  • IDbCommand
  • IDbConnection
  • DbParameter
  • DbParameterCollection
  • IDbTransaction

Within each of these implementations we wrap the underlying System.Data.SQLite versions of these to delegate down to. Within the command itself we parse the provided CommandText and detect if a schema is used, overriding this when necessary.

The final piece of the puzzle is to provide our own NHibernate driver which will tell NHibenate to use our implementation of IDbCommand. We couldn’t just inherit from the SQLite20Driver class so we had to copy its implementation as provided below:

using NHibernate.Driver;

namespace TheAgileWorkshop.SQLiteWithSchemaSupport
{
    public class SQLiteDriver : ReflectionBasedDriver
    {
        public SQLiteDriver()
            : base(
              "TheAgileWorkshop.SQLiteWithSchemaSupport",
              "TheAgileWorkshop.SQLiteWithSchemaSupport.SQLiteWithSchemaConnection",
              "TheAgileWorkshop.SQLiteWithSchemaSupport.SQLiteWithSchemaCommand")
        {
        }

        public override bool UseNamedPrefixInSql
        {
            get { return true; }
        }

        public override bool UseNamedPrefixInParameter
        {
            get { return true; }
        }

        public override string NamedPrefix
        {
            get { return "@"; }
        }

        public override bool SupportsMultipleOpenReaders
        {
            get { return false; }
        }

        public override bool SupportsMultipleQueries
        {
            get { return true; }
        }
    }
}

 

Now to use schemas with NHibernate and keep your in-memory SQLite tests passing, reference the TheAgileWorkshop.SQLiteWithSchemaSupport.dll and specify this driver class (TheAgileWorkshop.SQLiteWithSchemaSupport.SQLiteDriver) in place of the SQLite20Driver class that exists at the moment.

To use this, you can get the source or grab a copy of a release build of the dll directly.

I hope this helps others. If there are any issues then please don’t hesitate to let me know.

UPDATE: We have updated the release build dll link with a version that supports ‘.’ in the parameter values (such as a decimal property) based on MacX’s comments.

Posted by: ronniebarker | March 24, 2009

Stubs in Moq

I had a discussion today regarding Moq and how to make a quick stub of a property so that a mock object could be thrown into somewhere and have the properties work as simple properties. The simple answer weas to use an expectation:

image

But that felt ugly – and not as useful as it could be.

After playing around for a while I found the Moq.Stub namespace. After placing a using to this namespace at the top you can do something along the lines of personMock.Stub( p => p.Name ):

image

or to mock out all of the properties use personMock.StubAll():

image

As you can see – if no expectation is needed stubbing properties is quite simple in Moq.

Posted by: ronniebarker | February 1, 2009

Microsoft ASP.NET MVC RC1 is out!

The usual post from Scott GU is at: http://weblogs.asp.net/scottgu/archive/2009/01/27/asp-net-mvc-1-0-release-candidate-now-available.aspx

I have had some issues though – it seems that Visual Studio wants to keep hold of a reference to the old DLLs. Even after uninstalling the old, reinstalling the new and using direct file references, I still had some issues with Visual Studio just crashing witrhout any warning and leaving some cryptic error in the event log.

It seems to happen when opening .aspx files so I would certainly recommend closing all of the files in the solution before upgrading – otherwise one gets stuck never being able to open the solution. Deleting all of the compiled bin and obj folders seemed to help a little and I think clearing the resharper cache was useful too.

The problem seems to have just gone away for the moment so I haven’t really got to the bottom of it. I think it is more a problem with VS than MVC.

There look to be some small updates that look nice according to Scott. I certainly have some base classes and extension methods that do a couple of them already. The best looking update at the moment is, in my opinion, the ability to have a view without a code-behind even when having a strongly typed viewmodel – looking forward to using that one!

Posted by: ronniebarker | December 10, 2008

MethodChaining

I was recently part of a small talk with a selection of the dev team at Elateral about fluent interfaces. I was introducing the concept of method chaining with an example based upon Martin Fowler’s post that I had worked on when discussing some best practices with some of the guys at DisplayLink.

I had a small slide deck that really served only as a prompter for me to introduce the concepts and worked through the example. I promised to upload them all somewhere for general access so here it is.

All the files should be accessible here – they are as follows (individual links):

Slide deck
C# “ComputerBuilder” example
C++ “ComputerBuilder” example

I have already started using the C# example to further investigation into nBehave. I now have an acceptance test that reads something like:

story
        .AsA( Computer )
        .IWant( "to be configured" )
        .SoThat( "I work" );

story
        .WithScenario( "Martin Fowler's example" )
        .Given( "a new computer builder", () => chain = Computer.New )

        .When( "I give it two cores", () => chain = chain.WithCores( 2 ) )
        .And( "set it to be an i386", () => chain = chain.OfType( Processor.i486 ) )
        .And( "add a 150GB disk", () => chain = chain.WithDisk.OfSize( 150 ) )
        .And( "add a 7200rpm 75GB SATA disk ", () => chain = chain.WithDisk.IsSata.OfSpeed( 7200 ).OfSize( 75 ) )

        .Then( "I expect to get a Computer out", () => ( computer = chain ).ShouldBeInstanceOf<Computer>() )
        .And( "I expect to have a computer with $expectedCores cores", 2, expectedCores => computer.NumberOfCores.ShouldEqual( expectedCores ) )
        .And( "an $expectedProcessor processor", Processor.i486, expectedProcessor => computer.Processor.ShouldEqual( expectedProcessor ) )
        .And( "$expectedDiskCount disks", 2, expectedDisks => computer.Disks.Count.ShouldEqual( expectedDisks ) )
        .And( "the first disk should have a size of $expectedSize GB", 150, expectedSize => computer.Disks[ 0 ].Size.ShouldEqual( expectedSize ) )
        .And( "the second disk should have a size of $expectedSize GB", 75, expectedSize => computer.Disks[ 1 ].Size.ShouldEqual( expectedSize ) )
        .And( "the second disk should be SATA", () => computer.Disks[ 1 ].Sata.ShouldBeTrue() )
        .And( "the second disk should have a speed of $expectedSpeed rpm", 7200, expectedSpeed => computer.Disks[ 1 ].Speed.ShouldEqual( 7200 ) )
        ;

I am also using this example as part of a continuous integration experiment and hope to refactor to use interfaces and a single builder – more on these things later…

Posted by: ronniebarker | September 30, 2008

Why is iTunes so bad?

I don’t understand why iTunes is so bad. Is it because I am using it under Vista or is it just because Apple doesn’t actually care much past selling the hardware?

I have a simple set of requirements for iTunes – I don’t use it for managing a music library – I use it because it is the only piece of software that does a half decent job of putting podcasts onto my iPod shuffle. I say ‘half-decent job’ – because that’s all it seems to do really – half a job. Basically – without it I can’t really use the iPod. But which one is free and which one is crap?

So I have some ‘functional’ issues:

If it fails or loses an episode of some podcast (which can happen frequently!) it puts a little explanation mark next to it helpfully telling me it doesn’t know where the audio is. IS THERE A BUTTON TO RE-DOWNLOAD? NO! One has to delete the entry, collapse the menu, re-open the menu with pressed which not only restores the one I just deleted but ALL of the deleted ones – so I have to remember which ones I haven’t listened to – and then I can re-download. Argh!

It seems to forget which podcasts go on the iPod (I want ALL of them) – and if I choose the podcast and select ‘add to Ronnie’s iPod’ I get duplicates of the ones already there (admittedly this has only happened recently since v8 – things getting better?). Argh!

Most of the time it works out which ones I have played and deletes them – but I would like to be able to set a threshold for how much I have to listen to so that I don’t have to listen to all of the credits at the end of the podcasts just so that it automatically gets deleted – this is about the most reliable feature at the moment - when I first started using the shuffle it was the worst – so there are improvements…

My biggest beef (and only because I have to do far too much clicking about in the UI – if it just sync’d up my podcasts without touching like it ought to then this wouldn’t be an issue) is the complete sluggishness of the UI. I have never seen a piece of software that takes so looooooong for something to happen when I click the mouse button – is iTunes this crap on a mac? I hope not! I put this one down to Apple just not caring too much about the PC market.

But for some reason I still love walking around the Apple store – they do make some sexy stuff! Just go fix bloody iTunes – I don’t actually care how sexy the UI is – I just want podcasts on my iPod – how hard can that be?

« Newer Posts - Older Posts »

Categories