.NET Naming Conventions – VB.NET version

Not so long ago a colleague of mine, Josh Twist, did a post on .NET naming conventions using C# code to serve as an example. These are based on the .NET naming guidelines published on MSDN. Well, I happen to be doing a code review right now, but it’s in VB.NET. So I thought I’d do a VB.NET version and post it here for everyone’s reference. I’m sure that Eric Nelson will be very happy!

Option Explicit On
Option Strict On

Imports System

' Namespaces are PascalCased
Namespace Example.NamingConventions

    ' Class names are PascalCased
    Public Class ExampleClass

        ' All public fields, including constants are PascalCased
        Public Const PiAsAString As String = "3.14"

        ' All private fields are camelCased with an underscore prefix
        Private ReadOnly _privateMember As String

        ' All protected members are PascalCased
        Protected ProtectedField As Integer = 12

        ' All friend members are PascalCased
        Friend InternalField As Integer = 13

        ' All private methods are PascalCased
        ' *** NOTE - All parameters are camelCased
        Private Function Multiply(ByVal valueA As Double, ByVal valueB As Double) As Double
            ' local variables (scoped within a method) are camelCased (no underscore)
            Dim result As Double = valueA * valueB
            Return result
        End Function

        ' All private Properties are PascalCased
        ' *** NOTE - Acronyms of 2 characters are UPPERCASED (e.g. UI, IO)
        Private ReadOnly Property UIElementName() As String
            Get
                Throw New NotImplementedException()
            End Get
        End Property

        ' All (public and private) properties are PascalCased
        ' *** NOTE - Acronyms longer than 2 characters are PascalCased (e.g. Html, Xml)
        Public Property HtmlLength() As Integer
            Get
                Throw New NotImplementedException()
            End Get
            Set(ByVal value As Integer)
                Throw New NotImplementedException()
            End Set
        End Property

        ' All public methods are PascalCased
        ' *** NOTE - All parameters are camelCased
        ' *** NOTE - Abbreviations are not treated as Acronyms (so "Id" is Id, not ID).
        Public Sub AlignObjectById(ByVal id As String, ByVal alignment As Alignment)
            Throw New NotImplementedException()
        End Sub

        ' Nested classes are PascalCased, even private ones
        Private Class NestedClass
            Implements IDisposable

            Public Sub Dispose() Implements IDisposable.Dispose
                Throw New NotImplementedException()
            End Sub

        End Class
    End Class

    ' Enums are PascalCased and not plural (unless marked with <Flags> in which case the name should be plural)
    Public Enum Alignment
        ' Enum members are PascalCased
        Top
        Bottom
        Left
        Right
    End Enum

End Namespace

BizTalk WCF Adapter Stack

For a while now I’ve been thinking about writing a post that documents all the gritty details of how the BizTalk messaging engine hooks into the WCF stack in the various WCF adapters. Now I don’t have to as Paolo Salvatori has done a stunning job:

http://blogs.msdn.com/paolos/archive/2009/11/17/customizing-and-extending-the-biztalk-wcf-adapters.aspx

Well done mate. This is by far the best explanation of how the BizTalk WCF adapter stack actually works. It should be in the documentation!

Visual Studio Theme Generator

I’ve just discovered this and it’s awesome. If you like tweaking your Visual Studio theme, but can’t be bothered with going through the huge number of different settings that Visual Studio presents you with, then this makes it miles easier:

http://frickinsweet.com/tools/Theme.mvc.aspx

Visual Studio Theme Generator

Select a background, foreground and main colour, tweak the contrast, hit refresh to preview your selections, and then when you’re finished, click create to generate a vssettings file you can import directly into Visual Studio.

As the site says, frinkin’ sweet!

Check your INI file encoding

Last week I was assisting a customer with a production problem that appeared to be caused by the CLR JIT compiler inlining certain properties and methods. One of the quick workarounds we tried was to temporarily turn off JIT optimizations to see if it was indeed the inlining causing the problem. We did this using the .NET Framework Debugging Control INI file.

I got out Visual Studio, created a new text file, called it the same name as our EXE, but with an INI extension, and added the following to the file:

[.NET Framework Debugging Control]
GenerateTrackingInfo=1
AllowOptimize=0

Then I saved the file and copied it to the same directory as our EXE, and restarted the application.

The strange thing was that it had no effect whatsoever! Still our problem was there, and we were convinced by this point that it was the JIT inlining. I even went to the lengths of putting together a quick sample application that reproduced our problem and still this INI file wasn’t working.

After over an hour banging our heads on our collective desks I started getting paranoid about the precise text in the INI file, and that’s when it dawned on me. The default encoding of text files in Visual Studio is UTF-8 with a signature. A quick check of the advanced save options confirmed this:

Advanced Save Options

Flipping this over to Windows codepage 1252 and resaving the file solved the problem. No more JIT optimizations and our problem disappears, finally confirming our suspicions.

So it would seem that GetPrivateProfileString doesn’t like Unicode byte order mark signatures!

Unity and the Factory Method Pattern

I’ve been playing around with Unity recently, and in particular I’ve been trying to get Unity to resolve dependencies from factory methods, and more specifically manage the lifetime of those dependencies. If you’re not familiar with the factory method pattern then check out Wikipedia.

Out of the box, Unity does support the ability to register a type that is created by a factory method using the StaticFactoryExtension class. This extension allows you to specify a delegate that creates the type, and that delegate can then call a static factory method, or even resolve another type from the container and call it’s factory method. I’m not going to cover the specifics of how to use the StaticFactoryExtension here, but pop on over to David Hayden’s blog for an example.

However, there’s a big drawback with the StaticFactoryExtension. It doesn’t allow you to specify any LifetimeManager, nor any InjectionMembers. This means that every time the factory method type is needed by a dependency, the factory method delegate is called. So you’re either forced to make your factory method manage object lifetimes, which isn’t nice, or put up with always having a new instance for every dependency. The lack of InjectionMembers also means that the factory method has to provide precisely the correctly configured object. This isn’t much of an issue for most factory methods, but it does provide more flexibility.

So, what’s the solution? Well, I was pretty sure that it was going to require me to write some kind of Unity extension, and whilst I’m comfortable with using Unity, I’d not tried writing an extension before, other than a LifetimeManager. Unfortunately for me this requires you to know a bit about how ObjectBuilder works, and that’s not a particularly well documented bit of Unity. So, armed with the Unity source I started digging. What follows is the result.

One of the first things I realized is that all I really need to do is modify the way that Unity builds objects at the stage where a specific constructor is called, and instead call a delegate to get the object instance. Everything else should stay the same. After a bit of digging I came across the UnityDefaultStrategiesExtension class, and in it’s Initialize method are the lines:

Context.BuildPlanStrategies.AddNew<DynamicMethodConstructorStrategy>(
    UnityBuildStage.Creation);
Context.BuildPlanStrategies.AddNew<DynamicMethodPropertySetterStrategy>(
    UnityBuildStage.Initialization);
Context.BuildPlanStrategies.AddNew<DynamicMethodCallStrategy>(
    UnityBuildStage.Initialization);

The bit that caught my eye was the DynamicMethodConstructorStrategy class. Looking in more detail at this class confirmed that it was responsible for generating part of a dynamic method that would actually call a constructor. This was the class I had to intercept and modify its behaviour. With this knowledge I started building my new extension, using the StaticFactoryExtension as an example.

First I defined how I wanted to configure the extension in an interface. This interface has the same method signatures that you see on IUnityContainer for the generic versions of RegisterType, just naming them RegisterFactory and excluding the ones that take a TTo type parameter. You could quite easily add the non-generic versions too, but I didn’t bother.

public delegate object FactoryMethodDelegate(IUnityContainer container);

public interface IFactoryMethodConfiguration : IUnityContainerExtensionConfigurator
{
    IFactoryMethodConfiguration RegisterFactory<T>(FactoryMethodDelegate factoryMethodDelegate,
                                                   params InjectionMember[] injectionMembers);

    IFactoryMethodConfiguration RegisterFactory<T>(FactoryMethodDelegate factoryMethodDelegate,
                                                   string name,
                                                   params InjectionMember[] injectionMembers);

    IFactoryMethodConfiguration RegisterFactory<T>(FactoryMethodDelegate factoryMethodDelegate,
                                                   LifetimeManager lifetimeManager,
                                                   params InjectionMember[] injectionMembers);

    IFactoryMethodConfiguration RegisterFactory<T>(FactoryMethodDelegate factoryMethodDelegate,
                                                   string name,
                                                   LifetimeManager lifetimeManager,
                                                   params InjectionMember[] injectionMembers);
}

Next, I defined the extension class by deriving from UnityContainerExtension and implementing the configuration interface.

public class FactoryMethodExtension : UnityContainerExtension, IFactoryMethodConfiguration
{
    public IFactoryMethodConfiguration RegisterFactory<T>(FactoryMethodDelegate factoryMethodDelegate,
                                                          params InjectionMember[] injectionMembers)
    {
        return RegisterFactory<T>(factoryMethodDelegate, null, null, injectionMembers);
    }

    public IFactoryMethodConfiguration RegisterFactory<T>(FactoryMethodDelegate factoryMethodDelegate,
                                                          string name,
                                                          params InjectionMember[] injectionMembers)
    {
        return RegisterFactory<T>(factoryMethodDelegate, name, null, injectionMembers);
    }

    public IFactoryMethodConfiguration RegisterFactory<T>(FactoryMethodDelegate factoryMethodDelegate,
                                                          LifetimeManager lifetimeManager,
                                                          params InjectionMember[] injectionMembers)
    {
        return RegisterFactory<T>(factoryMethodDelegate, null, lifetimeManager, injectionMembers);
    }

    public IFactoryMethodConfiguration RegisterFactory<T>(FactoryMethodDelegate factoryMethodDelegate,
                                                          string name,
                                                          LifetimeManager lifetimeManager,
                                                          params InjectionMember[] injectionMembers)
    {
        Container.RegisterType<T>(name, lifetimeManager, injectionMembers);
        Context.Policies.Set<IFactoryMethodPolicy>(new FactoryMethodPolicy(() => factoryMethodDelegate(Container)),
                                                   NamedTypeBuildKey.Make<T>(name));
        return this;
    }

    protected override void Initialize()
    {
        Context.BuildPlanStrategies.Clear();
        Context.BuildPlanStrategies.AddNew<FactoryMethodConstructorStrategy>(UnityBuildStage.Creation);
        Context.BuildPlanStrategies.AddNew<DynamicMethodPropertySetterStrategy>(UnityBuildStage.Initialization);
        Context.BuildPlanStrategies.AddNew<DynamicMethodCallStrategy>(UnityBuildStage.Initialization);
    }
}

The two important pieces here are the Initialize method and the last RegisterFactory method. In Initialize I’m getting rid of the default BuildPlanStrategies and replacing them for my own. Actually, the only difference between these and the defaults defined in UnityDefaultStrategiesExtension is the FactoryMethodConstructorStrategy used in the creation stage, but I’ll come to that later.

In the last RegisterFactory method I register the from type as normal with the container, passing the LifetimeManager and InjectionMembers, but I also set an additional policy, IFactoryMethodPolicy, on the context. This wraps up the factory method delegate with the container into a more simple delegate that just returns an object, and is keyed using the same key that identifies the from type. This policy is used later when I need to call the factory delegate as part of building up the object. The FactoryMethodPolicy class is quite simple and just wraps the simplified delegate.

public delegate object FactoryMethodPolicyDelegate();

public interface IFactoryMethodPolicy : IBuilderPolicy
{
    FactoryMethodPolicyDelegate FactoryMethodPolicyDelegate { get; }
}

public class FactoryMethodPolicy : IFactoryMethodPolicy
{
    private readonly FactoryMethodPolicyDelegate factoryMethodPolicyDelegate;

    public FactoryMethodPolicy(FactoryMethodPolicyDelegate factoryMethodPolicyDelegate)
    {
        this.factoryMethodPolicyDelegate = factoryMethodPolicyDelegate;
    }

    public FactoryMethodPolicyDelegate FactoryMethodPolicyDelegate
    {
        get { return factoryMethodPolicyDelegate; }
    }
}

The final link in the chain is the FactoryMethodConstructorStrategy class.

public class FactoryMethodConstructorStrategy : DynamicMethodConstructorStrategy
{
    private static readonly MethodInfo FactoryMethodPolicyDelegateInvoke =
        typeof(FactoryMethodPolicyDelegate).GetMethod("Invoke");

    private static readonly MethodInfo GetFactoryMethodPolicyDelegateMethodInfo =
        typeof(FactoryMethodConstructorStrategy).GetMethod("GetFactoryMethodPolicyDelegate");

    public override void PreBuildUp(IBuilderContext context)
    {
        Guard.ArgumentNotNull(context, "context");
        if (GetFactoryMethodPolicyDelegate(context) == null)
        {
            base.PreBuildUp(context);
            return;
        }
        var buildContext = (DynamicBuildPlanGenerationContext)context.Existing;
        Label existingObjectNotNull = buildContext.IL.DefineLabel();
        buildContext.EmitLoadExisting();
        buildContext.IL.Emit(OpCodes.Brtrue, existingObjectNotNull);
        buildContext.EmitLoadContext();
        buildContext.IL.EmitCall(OpCodes.Call, GetFactoryMethodPolicyDelegateMethodInfo, null);
        buildContext.IL.EmitCall(OpCodes.Callvirt, FactoryMethodPolicyDelegateInvoke, null);
        buildContext.EmitStoreExisting();
        buildContext.IL.MarkLabel(existingObjectNotNull);
    }

    public static FactoryMethodPolicyDelegate GetFactoryMethodPolicyDelegate(IBuilderContext context)
    {
        var factoryMethodPolicy = context.Policies.Get<IFactoryMethodPolicy>(context.BuildKey);
        return factoryMethodPolicy == null ? null : factoryMethodPolicy.FactoryMethodPolicyDelegate;
    }
}
This class derives from the original DynamicMethodConstructorStrategy class whose behaviour I want to modify. I override the PreBuildUp method and check to see if there is an IFactoryMethodPolicy with a delegate defined for the build key in the context. If there isn’t I simply call the base implementation of PreBuildUp that will generate the dynamic method bits to call a constructor. However, if there is a delegate defined then I generate the dynamic method bits that call this delegate.

And once it’s all put together, that’s it! For good measure I’ve included the tests I used below. I’m certainly finding this useful in my projects, and if you do too I’d really like to hear about your experiences. Please feel free to comment on this post, even if it’s a bug you find!

 [TestFixture]
 public class FactoryMethodExtensionTests
 {
     public class TestStringFactory
     {
         private readonly string factory;

         public TestStringFactory(string factory)
         {
             this.factory = factory;
         }

         public string GetString()
         {
             return factory;
         }
     }

     public class TestStringDependency
     {
         private readonly string dependency;

         public TestStringDependency(string dependency)
         {
             this.dependency = dependency;
         }

         public string Dependency
         {
             get { return dependency; }
         }
     }

     [Test]
     public void FactoryMethodCanBeUsedToResolveTypeDependency()
     {
         var container = new UnityContainer();
         container.AddNewExtension<FactoryMethodExtension>();
         container.Configure<IFactoryMethodConfiguration>()
             .RegisterFactory<string>(c => "FactoryString");
         container.RegisterType<TestStringDependency>();

         var resolve = container.Resolve<TestStringDependency>();

         Assert.AreEqual("FactoryString", resolve.Dependency);
     }

     [Test]
     public void FactoryMethodCanUseContainerToResolveTypeToGetFactoryMethodUsedInDependency()
     {
         var container = new UnityContainer();
         container.AddNewExtension<FactoryMethodExtension>();
         container.RegisterInstance(new TestStringFactory("FactoryString"));
         container.Configure<IFactoryMethodConfiguration>()
             .RegisterFactory<string>(c => c.Resolve<TestStringFactory>().GetString());
         container.RegisterType<TestStringDependency>();

         var resolve = container.Resolve<TestStringDependency>();

         Assert.AreEqual("FactoryString", resolve.Dependency);
     }

     [Test]
     public void FactoryMethodExtensionLoadedStillResolvesNormally()
     {
         var container = new UnityContainer();
         container.AddNewExtension<FactoryMethodExtension>();
         container.RegisterType<object>();

         var resolve = container.Resolve<object>();

         Assert.NotNull(resolve);
     }

     [Test]
     public void FactoryMethodExtensionWithContainerLifetimeResolvesSameInstances()
     {
         var container = new UnityContainer();
         container.AddNewExtension<FactoryMethodExtension>();
         container.Configure<IFactoryMethodConfiguration>()
             .RegisterFactory<object>(c => new object(), new ContainerControlledLifetimeManager());

         var first = container.Resolve<object>();
         var second = container.Resolve<object>();

         Assert.AreSame(first, second);
     }

     [Test]
     public void FactoryMethodExtensionWithDefaultLifetimeResolvesDifferentInstances()
     {
         var container = new UnityContainer();
         container.AddNewExtension<FactoryMethodExtension>();
         container.Configure<IFactoryMethodConfiguration>()
             .RegisterFactory<object>(c => new object());

         var first = container.Resolve<object>();
         var second = container.Resolve<object>();

         Assert.AreNotSame(first, second);
     }

     [Test]
     public void FactoryMethodExtensionWithTransientLifetimeResolvesDifferentInstances()
     {
         var container = new UnityContainer();
         container.AddNewExtension<FactoryMethodExtension>();
         container.Configure<IFactoryMethodConfiguration>()
             .RegisterFactory<object>(c => new object(), new TransientLifetimeManager());

         var first = container.Resolve<object>();
         var second = container.Resolve<object>();

         Assert.AreNotSame(first, second);
     }
}

Feature Jealousy

What’s got LINQ, but doesn’t have a yield keyword and no Action or multiline lambdas? What’s supposed to be an easy to learn language, but supports exception filters when other supposedly more complex languages don’t?

The answer, VB.NET.

“Co-evolution” has been announced for VB.NET 10.0 and C# 4.0. However, VB.NET doesn’t appear to be getting yield, and C# won’t be getting XML literals (which I personally think is a good thing).

I think VB.NET shed the “Beginners” bit from BASIC a long time ago. What do you think?

Oh, and whilst I’m at it, who’s up for an __il keyword in C# so you can have inline blocks of IL?

Be afraid?

According to the BBC this morning, the UK government is proposing to monitor social networking sites like Facebook, Bebo and MySpace. This comes the day after a report called for the government to scrap a quarter of all their databases as they are illegal and should be redesigned. Included in this list of databases is the Communications Database which plans to centralise details of all phone calls made and websites visited, and is open to 510 public authorities. Just imagine what you could find out about people with a bit of clever data mining across these databases. What about joining up other sources of information on the internet? What sort of information would you look up about yourself, friends or family? How would that differ from the sort of information that government departments or security services would want to look up? People are always curious about what other people are interested in.

Flexible Enumerations

Sometimes enumerations in .NET just don’t cut it. In the end they’re just a numeric value to which a piece of string metadata is attached to some of the values. Consider the following enumerations:

public enum OfficeLocationNames
{
    London,
    Edinburgh,
    Redmond
}

public enum OfficeLocationCodes
{
    LON,
    EDI,
    RED
}

What are these enumerations actually trying to say? I see these and think that there are three office locations, London, Edinburgh and Redmond, and each has a name and a three letter code, i.e. one type of thing, an office location, with two pieces of descriptive information about that thing, name and code. But using enumerations has forced us to define two things, when it’s really one. So what solutions are there?

Here’s one solution I like. I’m sure there are more, so feel free to suggest variations or completely different patterns in the comments. First off I define an interface, IOfficeLocation, to specify what makes up an office location:

public interface IOfficeLocation
{
    string Code { get; }
    string Name { get; }
    double Latitude { get; }
    double Longitude { get; }
}

I’ve taken the liberty of adding two more pieces of descriptive information to the office location too, latitude and longitude, just to prove the point. Note that this is immutable, i.e. you can’t change the values once they’ve been created.

Next, I define the OfficeLocations static class that will be our container for the three possible office locations. Inside this class I define the OfficeLocation class, which is a concrete implementation of the IOfficeLocation interface. Again, this class is immutable, and importantly it’s a private class to the OfficeLocations static class. This ensures that only the OfficeLocations class can construct instances of the OfficeLocation class. Finally I define the three office locations as static read-only fields of the OfficeLocations class, all using the IOfficeLocation interface, but constructed from the private OfficeLocation class.

public static class OfficeLocations
{
    private class OfficeLocation : IOfficeLocation
    {
        private readonly string code;

        public OfficeLocation(string code, string name, double latitude, double longitude)
        {
            this.code = code;
            this.name = name;
            this.latitude = latitude;
            this.longitude = longitude;
        }

        private readonly string name;

        private readonly double latitude;

        private readonly double longitude;

        public string Code
        {
            get { return code; }
        }

        public string Name
        {
            get { return name; }
        }

        public double Latitude
        {
            get { return latitude; }
        }

        public double Longitude
        {
            get { return longitude; }
        }
    }

    public static readonly IOfficeLocation London = new OfficeLocation("LON", "London", 0d, 0d);
    public static readonly IOfficeLocation Edinburgh = new OfficeLocation("EDI", "Edinburgh", 0d, 0d);
    public static readonly IOfficeLocation Redmond = new OfficeLocation("MAN", "Manchester", 0d, 0d);
}

Using the OfficeLocations class is very similar to an enumeration, and because there is only ever one instance of London, Edinburgh and Redmond I can test for equality without needing to override the Equals method in the OfficeLocation class. I also like the fact that I cannot do more than or less than comparisons against office locations. It doesn’t make sense, to see if London is more than Edinburgh, does it? However, if it did I could implement IComparable on OfficeLocation and then I could make those comparisons.

public bool IsInUnitedKingdom(IOfficeLocation location)
{
    return (location == OfficeLocations.London) || (location == OfficeLocations.Edinburgh);
}

So, as usual, comments are always welcome. Are there any variations on this theme? Or perhaps issues with this implementation? Surely not!

Snow Fun

Well it won’t have escaped many readers from the UK (assuming I have readers outside the UK!) that it’s been snowing here, quite a bit more than it would normally for this time of year! So Joanne and I took Isaac out for his first experience of snow. He, of course, slept through the whole walk through Lily Hill Park, but here’s the photos for posterity.

Joanne and Isaac  Joanne and IsaacIsaac in his parm

And just for good measure, here’s a couple of shots I took this morning waiting for a train from Martins Heron into London. I think the pink hue is due to the fact that cameras in mobile phones don’t have UV filters!

Martins Heron train station in the snowMartins Heron train station in the snow

The train, by the way, did turn up on time, but arrived quite a bit late and was rammed full of people quite quickly. Obviously the wrong kind of snow.

And Can It Be…

With apologies to Charles Wesley.

My chain fell off,
My bike ran free,
Rolled down the hill into that tree.
My chain fell off,
My bike ran free,
Rolled down the hill into that tree.