Skip to content

2008

Please remove your hardware to start installation!

Today I tried out installing Windows Server 2008 on my cube server. When I reached the dialog to choose on which partition I want to install to, I always received the following warning "windows is unable to find a system volume that meets its criteria for installation". The partition had enough room space (40GB), formatted in NTFS, marked as primary and boot, etc.

After some research I ended up to the following article (KB927520). I tried a lot in the BIOS and partition settings but nothing helped. On the TechNet forum I saw the following thread with the same error and most of them solved the problem by physically unplugging all additional drives! On my cube I have an Areca RAID controller and a separated drive for booting the system. Unplugging my raid controller was the solution, duh!

AOP in Action - Dirty Tracking using Unity Interception

In most enterprise applications, you end up by having a lot of cross-cutting concerns throughout your application. Most of the time, you have, for example, infrastructure code for doing logging, dirty tracking, lazy loading, caching, etc. Often infrastructure code is scattered over a number of modules making it harder to maintain and understand. Aspect-oriented programming (AOP) solves this problem by allowing the programmer to express cross-cutting concerns in stand-alone modules called aspects.

When you apply domain-driven design, you often have the need for dirty tracking, check on a business entity whether the entity has changed (is dirty) or not. There are a lot of different implementations for dirty tracking, but in this article we are doing it by using an interface called IDirty that contains a property called IsDirty and the setter properties of your entity object calls the IsDirty if the value has changed.

public interface IDirty
{
   bool IsDirty { get; set; }
}

public class Customer : IDirty
{
   private string _firstName;
   private string _lastName;

   public bool IsDirty { get; set; }

   public string FirstName
   {
      get { return _firstName; }
      set
      {
         if (value != _firstName)
            IsDirty = true;
         _firstName = value;
      }
   }

   public string LastName
   {
      get { return _lastName; }
      set
      {
         if (value != _lastName)
        IsDirty = true;

            _lastName = value;
      }
   }
}

As you can see from the example, if you have a lot of properties, you end up by having a lot of infrastructure code and repeated code in each setter. What we want to achieve, is to annotate the setter property through an attribute called DirtyAttribute and that the dirty logic is centralized in one module.

[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class DirtyAttribute : System.Attribute
{
}

public interface IDirty
{
   bool IsDirty { get; set; }
}

public class Customer : IDirty
{
   public bool IsDirty { get; set; }

   public virtual string FirstName { get; [Dirty] set; }
   public virtual string LastName { get; [Dirty] set; }
}

Note that these are the only dependencies needed inside your domain model project. Now we need to make clear to Unity that we need to intercept the DirtyAttribute and execute some logic. With unity we denote a policy, a policy contains a set of matching rules and a set of call handlers. A matching rule will denote on which point the handler must be executed and the handler is the logic. In AOP this is called respectively a pointcut and an advice, the combination of the two is called an aspect. First, we are going to create our DirtyHandler by implementing the ICallHandler that resides in the Microsoft.Unity.Interception assembly.

public class DirtyHandler : ICallHandler
{
   public int Order { get; set; }

   public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
   {
      Advise(input.Target, input.MethodBase, input.Arguments[0]);
      return getNext()(input, getNext);
   }

   private void Advise(object target, MemberInfo methodInfo, object value)
   {
      string propertyName = methodInfo.Name.Substring("set_".Length);
      PropertyInfo info = target.GetType().GetProperty(propertyName);

      if (info != null)
      {
         object oldValue = info.GetValue(target, null);

         if (!IsEqual(value, oldValue))
            ((IDirty)target).IsDirty = true;
      }
   }

   private bool IsEqual(object valueX, object valueY)
   {
      if (valueX == null && valueY != null)
         return false;

      if (valueX != null && valueY == null)
         return false;

      if (valueX == null && valueY == null)
         return true;

      return valueX.Equals(valueY);
   }
}

Note that in the DirtyHandler we did not specify when the dirty logic is executed, this is done by a set of matching rules that implement the IMatchingRule interface. In our case we have three criterias, first that it can only be applied to a setter property, secondly that the setter property must be annotated with the DirtyAttribute and finally that the class must implement the IDirty interface. In Unity we have predefined rules that we can use, in our case we can use the PropertyMatchingRule and the CustomAttributeMatchingRule. To detect that a particular instance implements a given type, I created the InstanceOfMatchingRule.

public class InstanceOfMatchingRule : IMatchingRule
{
   private readonly Type _type;

   public InstanceOfMatchingRule(Type type)
   {
      _type = type;
   }

   public bool Matches(System.Reflection.MethodBase member)
   {
      return _type.IsAssignableFrom(member.DeclaringType);
   }
}

Now we are ready to configure our container for interception. Note that the interception mechanism inside Unity is implemented as an extension to the Unity block. Below we configure a policy named "DirtyPolicy" that executes the handler named "DirtyHandler" if it matches all three matching rules (PropertyMatchingRule, CustomAttributeMatchingRule and InstanceOfMatchingRule). In this example, we denote that the type Customer is configured with the VirtualMethodInterceptor. Note that this type of interception only works if your methods/properties are marked as virtual, which is the case for our Customer type (see Customer.cs).

// Start Configuration
IUnityContainer container = new UnityContainer()
   .AddNewExtension<Interception>()
   .RegisterInstance<ICallHandler>("DirtyHandler", new DirtyHandler());

container.Configure<Interception>()
   .SetInterceptorFor<Customer>(new VirtualMethodInterceptor())
   .AddPolicy("DirtyPolicy")
      .AddMatchingRule(new PropertyMatchingRule("*", PropertyMatchingOption.Set))
      .AddMatchingRule(new CustomAttributeMatchingRule(typeof(DirtyAttribute), true))
      .AddMatchingRule(new InstanceOfMatchingRule(typeof(IDirty)))
      .AddCallHandler("DirtyHandler");
// End Configuration

var customer = container.Resolve<Customer>();

var firstname = customer.FirstName;
Debug.Assert(!customer.IsDirty);
customer.FirstName = "Piet";
Debug.Assert(customer.IsDirty);

The configuration part can also be done through a configuration file. Unfortunately, there is no schema available, this means that there is no validation and intellisense inside your Visual Studio! Especially to describe the matching rules through xml, I had to introduce some extra converters that implement the TypeConverter class. This enables you to convert to any kind of object started from a string. I introduced the PropertyMatchingOptionConverter and GetTypeConverter.

public class PropertyMatchingOptionConverter : System.ComponentModel.TypeConverter
{
   public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
   {
      return (PropertyMatchingOption)Enum.Parse(typeof(PropertyMatchingOption), value.ToString());
   }
}

public class GetTypeConverter : System.ComponentModel.TypeConverter
{
   public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
   {
      return Type.GetType(value.ToString());
   }
}

Below you find how you use Unity with a configuration file and you find also the resulting xml file that does exactly the same as the above-mentioned version.

IUnityContainer container = new UnityContainer();
UnityConfigurationSection section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");
section.Containers["Default"].Configure(container);

var customer = container.Resolve<Customer>();
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
<section name="unity" type="....UnityConfigurationSection, ..."/>
  </configSections>
  <unity>
    <typeAliases>

      <typeAlias alias="bool"     type="System.Boolean, mscorlib" />
      <typeAlias alias="string"   type="System.String, mscorlib" />
      <typeAlias alias="int"      type="System.Int32, mscorlib" />
      <typeAlias alias="Type"     type="System.Type, mscorlib" />

      <typeAlias alias="GetTypeConverter" type="..."/>
      <typeAlias alias="PropertyMatchingOptionConverter" type="..."/>
      <typeAlias alias="InstanceOfMatchingRule" type="..."/>
      <typeAlias alias="DirtyHandler" type="..."/>
      <typeAlias alias="VirtualMethodInterceptor" type="..."/>
      <typeAlias alias="CustomAttributeMatchingRule" type="..."/>
      <typeAlias alias="PropertyMatchingRule" type="..."/>
      <typeAlias alias="PropertyMatchingOption" type="..."/>
      <typeAlias alias="DirtyAttribute" type="..."/>
      <typeAlias alias="IDirty" type="..."/>
      <typeAlias alias="Customer" type="..."/>

    </typeAliases>
    <containers>
      <container name="Default">
        <extensions>
          <add type="....Interception, ..."/>
        </extensions>
        <extensionConfig>
          <add name="interception" type="....InterceptionConfigurationElement, ...">
            <policies>
              <policy name="DirtyPolicy">
                <matchingRules>
                  <matchingRule name="SetPropertyRule" type="PropertyMatchingRule">
                    <injection>
                      <constructor>
                        <param name="propertyName" parameterType="string">
                          <value value="*"/>
                        </param>
                        <param name="option" parameterType="PropertyMatchingOption">
                          <value value="Set" type="PropertyMatchingOption" typeConverter="PropertyMatchingOptionConverter"/>
                        </param>
                      </constructor>
                    </injection>
                  </matchingRule>
                  <matchingRule name="DirtyAttributeRule" type="CustomAttributeMatchingRule">
                    <injection>
                      <constructor>
                        <param name="attributeType" parameterType="Type">
                          <value value="...DirtyAttribute, ..." type="Type" typeConverter="GetTypeConverter"/>
                        </param>
                        <param name="inherited" parameterType="bool">
                          <value value="true" type="bool"/>
                        </param>
                      </constructor>
                    </injection>
                  </matchingRule>
                  <matchingRule name="InstanceOfIDirtyRule" type="InstanceOfMatchingRule">
                    <injection>
                      <constructor>
                        <param name="type" parameterType="Type">
                          <value value="...IDirty, ..." type="Type" typeConverter="GetTypeConverter"/>
                        </param>
                      </constructor>
                    </injection>
                  </matchingRule>
                </matchingRules>
                <callHandlers>
                  <callHandler name="DirtyHandler" type="DirtyHandler"/>
                </callHandlers>
              </policy>
            </policies>
            <interceptors>
              <interceptor type="VirtualMethodInterceptor">
                <key type="Customer"/>
              </interceptor>
            </interceptors>
          </add>
        </extensionConfig>
      </container>
    </containers>
  </unity>
</configuration>

The source code of this article can be downloaded here

How to make your Windows Live Writer portable

I am using Windows Live Writer for posting items to my blog. One thing that I don’t like in general, is that applications store resources in the MyDocuments folder and that you cannot specify another location. I’m a huge fan of portable applications, which means that they don’t need any registry settings and/or dependencies, so that you can simply xcopy deploy to another location. Certainly if you are using an external HD, USB flash drive, etc.

Windows Live Writer (WLW) stores by default the drafts in the MyDocuments\My Weblog Posts\Drafts folder. I am using the latest beta (v14.0.5025.904) of WLW and didn’t find any settings through the application that enables you to customize folder paths.

I decided to dig into the assemblies of WLW via reflector to see how it is implemented. After some investigation I found that there is a class called ApplicationEnvironment that reside in the WindowsLive.Writer.CoreServices assembly. The Initialize method looks like this

ReflectorWLW

Apparently WLW has built-in functionality that enables you to run the application with the settings carried around with the software. WLW checks if there is a folder called ‘UserData’ in the installation folder and uses that folder to store all settings, drafts, etc. This is really great, you simply copy all contents of your WLW directory to for example your external drive and you simply create a folder called UserData. If you start WLW again it will create all the necessary subfolders and settings.

ExplorerWLW

I think it’s a feature of WLW beta that has not been documented yet ;-)

Organize your NHibernate mapping files inside Visual Studio

NHibernate uses an xml file to describe the mapping. Typically it is embedded as a resource file inside your project and it has a consistent filename convention, namely .hbm.xml. Typically an NHibernate project has the following structure

NHibernate01

Would it not be nice if we can organize it in the following way? I found it always handy that related classes, like designer classes and resource files are grouped together.

NHibernate02

To achieve this structure we can start from the first structure and nest the xml file trough a macro that I’ve written.

The second step, is to make clear to NHibernate where the mapping files reside. Note that resources that are nested to a class are compiled differently and thus NHibernate will not recognize the mapping files anymore. Therefore we need to traverse manually the assembly and try each embedded resource file. Below you find the resulting code

var domainAssembly = typeof(MyDomain.Order).Assembly;
NHibernate.Cfg.Configuration cfg = new NHibernate.Cfg.Configuration();

foreach (var resourceName in domainAssembly.GetManifestResourceNames())
{
   try
   {
      cfg.AddResource(resourceName, domainAssembly);
   }
   catch (NHibernate.MappingException)
   {
      //ignore
   }
}

Running MSTest without Visual Studio – Gallio to the rescue

In some cases it can be useful to quickly run your Microsoft unit tests on a machine where Visual Studio is not installed. For example on an end-user machine and/or during acceptance testing. Microsoft unit tests have a great integration with Visual Studio and Team Foundation Server, but unfortunately the unit tests cannot be run as a standalone application.

I saw there was an open-source adapter for NUnit, called Microsoft Team System NUnit Adapter from Exact Magic Software that can run Microsoft unit tests inside NAnt. For my unit tests I had some problems with the ExpectedException attribute. Then I noticed there is a project called Gallio and it worked like a charm and it can do a lot more! I noticed that today a new version has been released, namely Gallio v3.0.4.

Gallio is a extensible , open and neutral test automation platform. It provides tools and services needed to run and manipulate tests written using a wide range of other frameworks. Gallio can run tests from

and it can integrate with the following tools

To run the the tests there is a command-line runner, called ‘Echo’ and a graphical user-interface, called ‘Icarus’.

Gallio

Introduction to the Unity Application Block

The unity application block is a dependency injection container with support for constructor, property and method call injection. It simplifies the Inversion of Control (IoC) pattern and the Dependency Injection (DI) pattern. The Unity application block can be found on CodePlex.

The unity application block has two important methods for registering types and mappings into the container, namely RegisterType and RegisterInstance.

Method Default Lifetime Explanation
RegisterType Transient Lifetime Container will create a new instance on each call to Resolve
RegisterInstance Container-controller lifetime Instance has the lifetime of the container

Below you find an example where we map the ILogger interface to ConsoleLogger (implements ILogger).

UnityContainer container = new UnityContainer();
container.RegisterType<ILogger, ConsoleLogger>();
ILogger logger = container.Resolve<ILogger>();

Assume you have the following class that contains a dependency to ILogger as a parameter on the constructor.

public class MyClass
{
   ILogger _logger;

   public MyClass(ILogger logger)
   {
      _logger = logger;
   }
}

If we use the Resolve method of UnityContainer it will automatically inject the ILogger (ConsoleLogger) object. This is called constructor injection.

UnityContainer container = new UnityContainer();
container.RegisterType<ILogger, ConsoleLogger>();
MyClass myClass = container.Resolve<MyClass>();

You can also map multiple types for the same interface. In that case you can use a key as a parameter.

UnityContainer container = new UnityContainer();
container.RegisterType<ILogger, ConsoleLogger>("console");
container.RegisterType<ILogger, EventLogger>("event");

If you now try to resolve MyClass you will get an exception, because it cannot resolve which type (ConsoleLogger or EventLogger) to use. Therefore you can use the Dependency attribute where you can denote a key. For example:

public class MyClass
{
   ILogger _logger;

   public MyClass([Dependency("console")] ILogger logger)
   {
      _logger = logger;
   }
}

Below you find an example of property injection:

public class AnotherClass
{
   ILogger _consoleLogger;
   ILogger _eventLogger;

   [Dependency("console")]
   public ILogger ConsoleLogger
   {
      get { return _consoleLogger; }
      set { _consoleLogger = value; }
   }

   [Dependency("event")]
   public ILogger EventLogger
   {
      get { return _eventLogger; }
      set { _eventLogger = value; }
   }
}

Note that you can also map and register your types through a configuration file.

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
<section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration" />
  </configSections>
  <unity>
    <containers>
      <container>
        <types>
          <type name="console" type="IStaySharp.UnitySample.ILogger, IStaySharp.UnitySample" mapTo="IStaySharp.UnitySample.ConsoleLogger, IStaySharp.UnitySample" />
          <type name="event" type="IStaySharp.UnitySample.ILogger, IStaySharp.UnitySample" mapTo="IStaySharp.UnitySample.EventLogger, IStaySharp.UnitySample" />
        </types>
      </container>
  </containers>
  </unity>
</configuration>

The following code shows you how to use a configuration file with UnityContainer.

UnityContainer container = new UnityContainer();
UnityConfigurationSection section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");
section.Containers.Default.GetConfigCommand().Configure(container);

ILogger logger = container.Resolve<ILogger>("console");