Nant working directory

Splitting out your build file into smaller manageable chunks is a good practice to keeping them maintainable. Incorporating existing build files into your main one can sometimes be tricky, particularly when dealing with targets that depend on paths. Where you assumed you were executing one build file in a certain directory, suddenly you need to be able to run it from the root directory as well.

To maintain backwards compatibility (able to run it from the existing directory and a higher, root directory), I make use of nant’s ability to override property values (not supported by ant). Here’s the snippet of code I used:

<include buildfile="differentDirectory\deepdown\nested.build"/>
<property name="nested.build.root" value="differentDirectory\deepdown"/>
<if test="${file::exists('nested.build')}">
  <property name="nested.build.root" value="."/>
</if>
<echo message="Running nested build from ${nested.build.root}"/>

Visual Studio 2008 – The Anti Region Shortcut

If you happen to be unfortunate enough to stumble across “region”-ised C# code, use the following short cut keys to expand all in a file:

CTRL-M + CTRL-L

Give it a go! Or better yet, disable all code folding by default:

Text Editor -> C# -> Advanced. Uncheck “Enter outlining mode when files

Go to Text Editor->C#->Advanced. Under the “Outlining” section, uncheck the option labelled “Enter outlining mode when files open”.

A more usable Visual Studio 2008

All of the tips I wrote a long time ago for speeding up Visual Studio 2005 still apply. I’ve found that the preferred replacement for Cool Commands is the Power Commands plugin that Microsoft now provides.

Coding styles leads to (or prevents) certain classes of bugs

I fixed a bug yesterday caused by a loop that terminated too early. It took me a while to understand the fact that it was terminating too early, and I realised that I’ve never written this type of bug because of the way that I tend to write code. Basically, the method looked like this:

public void someMethod() {
   for ( String key : keys ) {
       if (someCondition()) {
         return;
       }
       doSomeProcessingForThe(key);
   }
}

As you can see, the innocent looking return statement breaks out of the entire method, and what they really wanted was a continue statement instead. Note that TDD had been applied to this codebase, and it’s just another reminder that driving your code with tests isn’t enough (you also want to think of ensuring you write more comprehensive tests, particularly for loops).

I’m writing this post because I though it’s interesting that I realised a certain coding style removes (and possibly adds) a whole class of bugs. Had I been writing the code to start with, I probably would have avoided the use of the return (and/or continue) statement resulting in the following code:

public void someMethod() {
   for ( String key : keys ) {
       if (!someCondition()) {
         doSomeProcessingForThe(key);
       }
   }
}

Prevention is easy with tools like checkstyle, PMD or findbugs (and maybe some of them already check for this). If not, I think it’d be easy to add.

Treat your App.config like a global variable

I remember looking at a few codebases in C# and it surprised me how many people encapsulate some of their system well, yet treat their application configuration as a different thing. Many times I’ve seen code that looks like: ConfigurationSettings.AppSettings["DatabaseConnectionString"]; alongside the thing that is using it. In fact, I often see this code repeated in various parts of the system wherever anyone needs to draw on application configuration.

Global variables are bad
Most good programmers seem to realise that most global variables are bad, yet this is exactly what I think accessing the application configuration is like. If you want to change the way your configuration is loaded (i.e. programmatically or from a database) think of how many places you now need to change it, let alone how it effects the order in which you instantiate objects.

My advice: Separate the use of configuration from where it declared
I try to follow the pattern isolating the configuration into a single class depending on the access method, such as:

  • DatabaseBackedConfiguration
  • FileBackedConfiguration
  • DefaultInMemoryBackedConfiguration

Each of these classes them implement several roles depending on what configuration they might provide such as:

  • HibernateConfiguration
  • ApplicationConfiguration
  • ArchivingConfiguration

Having smaller roles makes it clearer what sort of configuration is really needed for a particular consumer, and it allows me to change the decision about how that configuration is now provided to it. It enables me to do things like specify different environment configurations and do so in the method that I prefer.

Losing my London .Net Users Group virginity

About 60 people (only of which three or four were female) crammed into a tiny room near Red Lion Square last night for the London DotNet Users Group meeting. I have no idea what the normal turnout rate is, though I guess the topic (TDD) probably drew quite a lot of people. Three people presented and the meeting ran for a total of three hours until 9:30pm at which point, we left for the pub and stayed until closing.

The three presenters for the evening and the topics included:

  • Zi Makki: TDD and the Data Access Layer
  • Sebastien Lambla: The MVP pattern
  • Ian Cooper: Best Practices for TDD

The first presenter covered some techniques for dealing with integration points with a database. I noticed that he used Coderush (all those bright colours and arrows hurts my eyes!) instead of Resharper though I think he was using VS2008. It seems that Coderush also lacks a way of extracting a class into a file for a different assembly or at least it wasn’t used. I’m pleased the presenter used BDD styled should as I’ve found these help focus the person writing the test. He finished with some very useful tips though I was worried by one of his final statements, “Avoid Integration Tests”. I think as a principle, fine. For someone in the early stages of learning TDD (think of the Shu in the Shu Ha Ri), it’s a dangerous blanket statement they may follow as integration tests can be useful points of feedback as well.

The second presenter talked about the Model View Presenter Pattern although after seeing his implementation, and I think it is probably more an example of both the Supervising Controller and the Presentation Model. I find it interesting to see how far Sebastien pushed the databinding features of ASP.Net. It’s given me some thought about how I might actually give databinding another real chance. I’m really interested to see how this works in an update mode in this same world. I also learned here that the Macbook Air isn’t great for doing presentations where you need to write code (the buttons are too small!)

The final presenter, Ian Cooper talked over lots of best practices around Test Driven Development. Ian has plenty of great things to say and one of my only issues was that there was probably far too much content on the slides to cover in just an hour.

One of the other topics that wasn’t covered and I think is important for newbies to TDD is understanding when to or when not to use it. As I wrote in a previous post, if you’re doing TDD all the time, you’re doing something wrong.

I really enjoyed talking to other people who went along and I’ll definitely be back again sometime.

Some notes on C# 3.0

I’ve been playing around with some of the new features of C#3.0. I installed VS2008 and the new Resharper 4.0 EAP available here. I expect most of the Jetbrains EAP stuff to be pretty buggy and I’ve already had it crash on me more than five times today. Still, being able to refactor and navigate around files is worth the buggy trial.

Out of the box support for the new language features looks interesting as well as some of the new tools and refactorings in place. Interestingly, default settings suggests constant use of the new var keyword replacing the class declaration you should be using. I’m a little uncomfortable with this as the default setting though it could be because I’m not used to seeing C# code like that.

I started playing around with extension methods, trying to convert the ReflectUtil I wrote back in this post. After a rewrite, some of the APIs looked a bit better although at the cost of making some private inner classes and delegates public. I’m not sure if I like it yet and still trying to think of some guidelines for when to use it. I think definitely having all the extension methods grouped together would help – either in one big Extension class (if you don’t have too many) or in a [Class]Extension class so they’re much easier to locate. If you find youreself writing StringUtil classes, consider converting them to Extension classes. Right now, extension methods only work on instances, so if you want to be able to add static methods, vote on the topic here. I’m not yet convinced it’s that useful just yet though.

Lambda expressions look especially nice although now it’s just plain confusing how you have three ways to do something and there’s really little benefit out of the two more verbose ways. Use this to replace anonymous delegates with a less verbose method.

UK November Away Day

I’ve been lucky enough to attend two of Thoughtworks‘ Away Days over the last month. Most recently I attended the UK Away Day this weekend that provided a great opportunity to catch up with some people and generate some new ideas. I’d write up more about the Indian Away Day I’d attended two weeks prior, but running a two week training course almost immediately has taken away my time to reflect and my memory’s a little foggy these days.

Here’s an overview of the sessions that I attended:

  • A Lessons Learned session applying Ruby on Rails – An interesting session presented by Paul Ingles and George Malamadis about their approach to building a fully functional website with some of the pitfalls. I love these sorts of sessions as you get the insight into the decision making processes with talk about the constraints and thinking that pushed patterns into the direction of the end result. Really nice and a great topic to start leading into the Meta Programming session later than evening.
  • The Space Within – Hosted by the very calm Manoj Ramachadran who ran through a number of exercises to help improve the “quiet” times in our lives and give us an ability to become more effective. I found this interesting as it gave me insights into other methods to try.
  • Features of C#3.0 – Presented by Troy Gould and a great statement opening it along the lines of C#3.0 is included in .Net 3.5. How confusing is that? An interesting code example comparison by comparison of features new to C#3.0 introduced to support Linq. I think pretty much everyone was thinking how these features could be used effectively, and where they would be more likely (ab)used.
  • Case Study of a Consulting only session – An ever excitable and interesting co-presentation with Luke Barrett and one of our clients where the focus wasn’t directly about delivering working software, but focusing on delivering value even earlier by clarifying a business case and helping evaluate its feasibility. I enjoyed hearing the application of the same lo-fi techniques and methods bringing value in a different space for once.
  • Meta Programming – A fun session running through features of Meta Programming in Ruby by Farooq Ali and Julie Yaunches. I really enjoyed this session, and glad I could attend this since I’ve had the pleasure of working in the same room with both of these people and they’re passion for Ruby really shone throughout the presentation. They reminded me of the power language gives, and definitely helped me refine some thoughts I’d been having about the environment or approach needed to pull this off successfully.

I had a great time catching up with loads of people and had plenty of fun after the conference gathering at Sway.

Events, Reflection and how they don’t work in C#

Although the .Net reflection APIs make some tasks easier, we’ve found recently that those related to events and their delegates have been fairly poorly designed. Our task was very simple: dynamically manipulate the event handlers attached to a set of events.

It’s easy enough to get a declaration about an event of some sort using code like:

EventInfo infoAboutEvent = someObject.GetType().GetEvent("MyEvent"); 

Given your EventInfo class it’s easy to add an a new event handler. Unfortunately going the other way around ended up much harder. Unlike things like FieldInfo that give you direct access to get the field instance from the object using GetValue(owner), finding the event field isn’t as easy. First we had to look at all the fields, and filtered out things that looked like a Delegate so we could do some useful things with them, like finding out what subscribers were hooked up to our event.

Our ultimate goal of being able to dynamically remove EventHandlers at runtime further ran into problems when we were trying to unhook methods from private events. The result of trying to unhook a handler from a private event via the EventInfo.RemoveEventHandler method results in an InvalidOperationException with a message of “Cannot remove the event handler since no public remove method exists for the event.”

One more simple use of reflection and soon we were able to automatically unhook a variety of delegates from our events regardless of their access mechanism (although using code that wasn’t as nice as we wanted). A few refactorings later and we ended up with something actually quite useful in the end.

ReflectUtil.RemoveEventHandlersFrom(
 delegate(Delegate subject) { return subject.Method.Name.StartsWith("On"); },
  objectWithEvent);

And here’s the class that we ended up with. Although I can’t recommend people use reflection lightly, if you need to delve into the world of reflection with events, I hope you find this example useful.

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Reflection;

public sealed class ReflectUtil
{
  private static BindingFlags PrivatePublicStaticInstance
    = BindingFlags.NonPublic | BindingFlags.Public |
      BindingFlags.Instance | BindingFlags.Static;

  public delegate bool MatchesOnDelegate(Delegate subject);

  public static void RemoveEventHandlersFrom(
    MatchesOnDelegate matchesOnDelegate, params object[] objectsWithEvents)
  {
    foreach (object owningObject in objectsWithEvents)
    {
      foreach (DelegateInfo eventFromOwningObject in GetDelegates(owningObject))
      {
        foreach (Delegate subscriber in eventFromOwningObject.GetInvocationList())
        {
          if (matchesOnDelegate(subscriber))
          {
            EventInfo theEvent = eventFromOwningObject.GetEventInfo();
            RemoveSubscriberEvenIfItsPrivate(theEvent, owningObject, subscriber);
          }
        }
      }
    }
  }

  // You can use eventInfo.RemoveEventHandler(owningObject, subscriber)
  // unless it's a private delegate
  private static void RemoveSubscriberEvenIfItsPrivate(
    EventInfo eventInfo, object owningObject, Delegate subscriber)
  {
    MethodInfo privateRemoveMethod = eventInfo.GetRemoveMethod(true);
    privateRemoveMethod.Invoke(owningObject,
                               PrivatePublicStaticInstance, null,
                               new object[] {subscriber}, CultureInfo.CurrentCulture);
  }

  private static DelegateInfo[] GetDelegates(object owningObject)
  {
    List delegates = new List();
    FieldInfo[] allPotentialEvents = owningObject.GetType()
      .GetFields(PrivatePublicStaticInstance);
    foreach (FieldInfo privateFieldInfo in allPotentialEvents)
    {
      Delegate eventFromOwningObject = privateFieldInfo.GetValue(owningObject)
        as Delegate;
      if (eventFromOwningObject != null)
      {
        delegates.Add(new DelegateInfo(eventFromOwningObject, privateFieldInfo,
          owningObject));
      }
    }
    return delegates.ToArray();
  }

  private class DelegateInfo
  {
    private readonly Delegate delegateInformation;
    private readonly FieldInfo fieldInfo;
    private readonly object owningObject;

    public DelegateInfo(Delegate delegateInformation, FieldInfo fieldInfo,
      object owningObject)
    {
      this.delegateInformation = delegateInformation;
      this.fieldInfo = fieldInfo;
      this.owningObject = owningObject;
    }

    public Delegate[] GetInvocationList()
    {
      return delegateInformation.GetInvocationList();
    }

    public EventInfo GetEventInfo()
    {
      return owningObject.GetType().GetEvent(fieldInfo.Name,
        PrivatePublicStaticInstance);
    }
  }
}

Upgrading from NHibernate 1.0.2 to 1.2.0.GA Experience Report

We recently upgraded to the latest version of NHibernate to make use of many of its new features. There are plenty of good reasons to upgrade including proper support of .Net 2.0, bug fixes, multi queries, new database dialects (including SQL Server 2005) and the ability to use generic types. We anticipated a few issues upgrading NHibernate, and though not the hardest upgrade ever, we did end up with a few more issues than expected. Here’s our experience upgrading to the latest version.

Things they warned you about

The NHibernate guys did a fantastic job writing their migration guide. They warned us that it wasn’t just simply a drop-in replacement and included a number of breaking API changes. Things that we found easy and had been documented included:

  • Updating our XML files from urn:nhibernate-mapping-2.0 to urn:nhibernate-mapping-2.2
  • Replacing outer-join="true" to fetch="join" and outer-join="false" to fetch="select"
  • Adding default-lazy="false" to each mapping file to deal with the change in default lazy loading behaviour
  • The HSQL count had been upgraded from an int type to a long type and our code had to cast it to the correct types
  • Deprecation of the CreateSQLQuery with parameters changed to ISQLQuery(String)

Things not on the label

  • Strange behaviour around the nosetter.camelcase access strategy – We had a property exposing a primitive type (string) of a more complex type, given the same field name and we kept getting a null result. It looked like it was trying to set the field using the type of the get property, even though the set should have been using the more complex user type. We fixed this by changing our mappings to field.camelcase instead of using the nosetter.camelcase.
  • SQL statement logging has changed – Our application listens very carefully to the Log4Net output that NHibernate generates, capturing each SQL statement and its parameters. Previous versions of NHibernate used to log their parameter values separately from their SQL statements, instead they are now logged on the single line. Thankfully our change was contained to two very small classes.
  • Replacing IClassPersister with IEntityPersister – We had to add a different constructor to our custom user types (also different from the current documentation), with a signature of PersistentClass model, ICacheConcurrencyStrategy cache, ISessionFactory required, IMapping mapping. Additionally we had to implement the new property Factory that came along with this interface. Now I had no idea where ISessionFactoryImplementor came from. Looking at the code, they had cast ISessionFactory in their constructor, and then returned that when the property Factory was called. It is a small inconsistency in their API that we ended up having to duplicate. This would be a problem if you ended up writing your own ISessionFactory but thankfully we haven’t done that ourselves. There were plenty more methods that we had to implement though none of them were actually very insteresting for the things that we had to do. Our solution: Cast ISessionFactory to ISessionFactoryImplementor and store it in the constructor just to be returned in the property.
  • IUserType Classes Disappearing – They had warned you that IUserType had moved into another namespace though I wasn’t quite clear what you had to do if you were using one of the old versions. In the end new Int16SqlType() is replaced by SqlTypeFactory.Int16, new Int32SqlType() by SqlTypeFactory.Int32, new Int64SqlType() by SqlTypeFactory.Int64, and new GuidSqlType() by SqlTypeFactory.Guid. I’m guessing it would be the same for any other IUserTypes you may be using.
  • IUserType New Methods – Four new methods appeared on the interface, GetHashCode, Replace, Assemble, Disassemble. Implementing GetHashCode we ended up delegating to our object, replace we delegated to using disassmemble then assemble, and implemented assemble and disassemble using DeepCopy, emulating what NHibernate Types do. It wasn’t really clear to me from documentation or upgrade guides what it should be
  • NHibernate.HibernateException : Could not instantiate cache implementation – It look like second level caching was now enabled by default and we hadn’t added configuration for it. We kept getting “Second-level cache is not enabled” messages. We disabled it and fixed this problem by explicitly turning it off. The property key is hibernate.cache.use_second_level_cache and turn it off by using the value false.

For the most part, considering how much of the core hibernate functionality had changed, we haven’t had too many issues although it’s still early days. We are noticing slightly different behaviour in the way that the flush semantics seem to be working (maybe auto flush mode is on by default now) though everything is still working quite pleasantly.

Next Page »