Monday, January 26, 2009

Traversing Many-To-Many mappings with NHibernate Query Generator

We've been using the NHQG for awhile now, and we've had great success with it.

It wasn't until today that I found that the standard mapping using a Matches:

return Where.Interview.Attendees.Matches(Get.PersonSummary.ID, 
Where.PersonSummary.ID == RraPerson.GetCurrent().ID);


So I have a collection of PersonSummaries, which are mapped using a link table shown by the mapping below:

<idbag name="Attendees" table="InterviewAttendee">
  <collection-id type="Int32" column="ID">
    <generator class="native"/>
  </collection-id>
  <key column="InterviewID" />
  <many-to-many class="Namespace.PersonSummary, Assembly" column="PersonID"  lazy="false" />
</idbag>


Unfortunately this was not working and throwing an NHibby exception:

threw an exception of type 'NHibernate.QueryException'
base {NHibernate.HibernateException}: {"could not resolve property: Attendees of: Namespace.PersonSummary"

After some struggling I stumbled upon this blog post from Ayende which demonstrates how to perform a query against a many-to-many mapped collection. So my query now looked like:

return Where.Interview.Attendees.With().ID == RraPerson.GetCurrent().ID;


Sweet! The With() method works very nicely and even neatens up the query.

Wednesday, January 14, 2009

Awesome code formatter

I wasn't able to get to get some of my code looking neat within wordpress, but luckily stumbled upon this nice web based code formatter: http://www.manoli.net/csharpformat/.

It format's: C#, XML, SQL, VB and gives you the ability to specify line numbers and alternate line colourings - Cool :)

I've noticed is outputs the same layout as Ayende and a few other coders use on their blogs.

Eager loading from a formula in NHibernate

A little while ago, our project started looking at optimizing some of our code. Just for some background the application is a windows based smart client using NHibernate, WCF, WPF and a custom built framework tying them together.

One of the problems I faced was the disparity between our relational model and object model, and so leveraging our ORM we use formulas and mappings to bridge the gap between the database and our entities. The next problem was that we mapped the ID's of disconnected entities onto the entity in question using formulas, meaning we had to lazy load (over WCF) the sub-entities mapping using a formula. In some cases this is perfectly fine, in others it proved a bottleneck and we wanted to get everything loaded in one network call and database hit.

At the time of writing (coding?) NHibernate did not support mapping a formula to an object. We would expect something such as:

<property name="Entity" formula="dbo.Formula(ID)" class="Namespaces.Foo, SampleAssembly" />

Unfortunately this doesn't work, so I had to create a custom user type for it. If you don't know about NHibernate UserTypes I suggest you read: Ayende: UserTypes.

So now the XML to eager load our entity looks as below :-

<property name="Call" formula="dbo.PersonCurrentCall(ID)">
  <type name="Namespace.EagerLoadingUserType, Assembly">
    <param name="entitytype">
      Entities.TypeOfEntityToEagerLoadFromID, Assembly
    </param>
  </type>
</property>

The code for the user type is below however the magic is really in the IParameterizedType interface. This effectively allows you to give your UserType arguments (in my case the fully qualified class name of the entity we wish to eager load. SetParameterValues is called when NHibernate is first loaded and reads the mapping data.

The NullSafeGet method contains some of our domain specific code which you will need to replace with your own. When NHibernate loads up the root entity (which our "TypeOfEntityToEagerLoadFromID" hangs off) it will attempt to populate the entities members, and will hit our NullSafeGet method with the ID for this member. This is the point which you will want to use your server-side container or framework to load this new entity from your datasource (probably using NHibernate) and return the object for NHibernate to insert into the root entity.

/// <summary>
/// Eager loads entities which are mapped using a SQL formula.
/// </summary>
public class EagerLoadingUserType  IUserType, IParameterizedType
{
    private Type _type;
    
    #region IParameterizedType Members
    
    /// <summary>
    /// Sets the parameter values. In this case the type of entity 
    /// we are eager loading.
    /// </summary>
    /// <param name="parameters">The parameters.</param>
    public void SetParameterValues(IDictionary parameters)
    {
        _type = Type.GetType((string)parameters["entitytype"]);
    }

    #endregion

    #region IUserType Members
    
    /// <summary>
    /// Gets the type and ID of the object load eager load from the 
    /// database.
    /// </summary>
    /// <param name="rs">The rs.</param>
    /// <param name="names">The names.</param>
    /// <param name="owner">The owner.</param>
    /// <returns></returns>
    public object NullSafeGet(IDataReader rs, string[] names, object owner)
    {
        object r = rs[names[0]];
        int? entityID = (int?) r;
        if(entityID.HasValue && _type.IsAssignableFrom(typeof(EntityBase)))
        {
            return FrameworkHelper.LoadEntity(_type, entityID);
        }

        return null;
    }

    #endregion
}

A large amount of this class has been omitted since it implements the interface based on the defaults outlined in Ayende's article.

I hope you have found this post useful, I've tried to explain as best I can and I may put together some working sample code in the future. This may also not be the best approach but it was the only one I could see that worked.

Alternative to Launchy

A while back I spotted a friend of mine using a launchy style application which made me go "Hey whats that?". He pointed me in the direction of enso. Much like launchy it's a capable quick application launcher, with quite a clean interface.

One thing I noticed is that it's noticably faster and more responsive in comparison to Launchy.

I would recommend to get the additional add-on packs:

These are the two main facilities that I use, however some of the other beta products may be useful for other people. Once installed you drive the application using the otherwise useless Caps-Lock button (which I haven't use in years).

zrclip-002p501bb3a2.png

Hitting Caps-Lock open (which auto-completes if you hit o) and then let go of Caps-Lock, an enso style launcher opens, with similar features to Launchy. However whats different to other application launchers is that you can perform a number of other commands with don't involve launching.

For example I can minimise the current window by hitting Caps-Lock and typing min which auto-completes to minimise:

zrclip-003n1b2cede5.png

The interface is transparent and is shown in the top-left of the screen which is nicely out of the way and looks pretty neat. You can grab text by selecting some text from an application and depending on the command enso will pull the selection and paste it as an argument to the relevant commands, such as the google or google-map commands. So you can select an address by highlighting it, run the google-map command, and it will do a search on the highlighted text, great :)

Given the amount of people in my work-place who now go "Oooh, whats that?" when they see me using enso, I figured I'd share it here. Unfortunately, as some of the plugins are beta, and the product is new there are some issues:

  • If you have some text highlighted, and run an enso command, it will pick it up. So if you didn't mean for this to happen and have an entire files contents selected, enso will take a fair while copying and pasting it as an argument (sometimes causes enso to crash).
  • There are some features which have not been implemented, for example it will only list 10 suggestions if you type something fairly generic and does not allow you to scroll and view more.
  • Clicking outside of the launcher box does not exit the launcher, you need to manually hit esc.

I would still recommend people give this application a go as I have found it very useful!

Monday, January 12, 2009

Configuring teamcity to build an msbuild solution

The next step for my team city build server was to get it building my project whenever changes have been checked in.

  1. Select your project.
  2. Select your build configuration (which I made here).
  3. Hit the "Edit Configuration Settings" button.
  4. Select build triggering.
  5. Check "Enable triggering when files are checked into VCS.

I then configured my Build Runner to build the correct solution file with MSBuild. My project structure is:

WhereAreYou\Solution

And my solution file is WhereAreYou.sln, so I configured to runner as shown below:

zrclip-002nc23bfc8.png

Pretty straightforward, and low and behold my build passed:

zrclip-003p5f6ad499.png

Next is to get my Continuous Build running Unit Tests...

Sunday, January 11, 2009

I can finally give up...

...fixing the build!

zrclip-002n71b233e4.png

LOL that really made me chuckle. I can see teams suffering from a fair bit of broken build delegation with this feature :-)

I like the addition none the less.

A look at TeamCity for Continuous Integration and Build Management

We currently use Cruise Control for our continuous integration and build management at work, and it works for us quite nicely. For the current project we have a few different builds and deployments for building, integration tests, reporting and migration.

We are using a slightly older version of cruise control so the web interface is lackluster, the cc-tray is reasonably low on features (although functional) and we've had some integration issues with TFS (which are normally able to get around). The newer version looks very nice and an improvement on the version we are currently using, however I wanted to try something altogether different, which brings me to TeamCity from JetBrains.

On paper it looks fantastic, with some highlights (as far as .NET is concerned):

  • Integration into visual studio.
  • Plugins for FxCop, NAnt and Windows tray.
  • Gated checkins (Don't need to wait for the new TFS).
  • A built in duplicates finder.
  • Distributed computing for faster builds!

So overall it really looks like a great tool which could rival CC.NET, and for Java TeamCity could well be a heavenly system for IntelliJ zealots!

zrclip-001ne227ba.png

Actual installation was a breeze (A bunch of nexts), TeamCity will actually deploy a Tomcat server (Only supplies a web interface) and you have the option to run it as a windows service (I picked yes). It does look like the application is slightly heavy on resources:

zrclip-002n69e3a768.png

The extra java.exe process is for the one build agent I have configured already, we'll get onto this in a bit. Given the functionality it offers we can forgive it's footprint, but I recall CC being slightly easier on resources especially when idle.

Let's take a look at the web interface where all the configuration and administration happens:

zrclip-003n30d5d8b5.png

Here's a project I've setup earlier, this is the first thing TeamCity will want you todo, setting up a project involves just giving it a name, however you will need to then create a build configuration.

A build configuration consists of:

  • General Settings (Build numbers, build fail conditions and hanging build detection (which is nice).
  • Version Control settings, of which it supports them all (except git).
  • Build Runner, I'll take a look at configuring this in the next post, first with MSBuild and then for NAnt when I get onto more complicated deployments.
  • Build triggering, such as trigger a build when someone checks in, but there are some other options.

The fail building scenario options are straightforward:

zrclip-005n2fd2a5f4.png

As I mentioned before, TeamCity will want some agents to be able to run the builds on. In my case I put an agent on the same machine as the TeamCity web server, however this is not necessary. Installing buld agents simply requires you to go to the Agents page, download the appropriate file for your O/S (MS Installer, Java Installer or a ZIP) and follow the instructions. I will attempt to add my quad core machine as a build agent and see how it all works in a future post.

zrclip-006p22670301.png

That was a really sketchy first look at TeamCity after getting it installed, future posts will hopefully be more useful :)

A great desktop blogging application

Clearly I'm new to this, but after some googling, and a lovely post comparing some desktop blogging applications I've arrived at w.blogger

Wordpress Desktop Blogging: 5 Tools Reviewed | CenterNetworks

Some of the features I like:

  • Ability to upload images directly to the wordpress media library and link to them.
  • Can either just post, or post and publish directly from the client.

It seems at the time of writing Zoundry did not perform to well compared to the competition, but after trying w.blogger, BlogJet (which doesn't seem to work on Windows Server 2008) and Zoundry Raven (Successor to the original Zoundry in the review) I've really shown a liking towards the latter.

zrclip-001p6f2dd680.png

Inserting images is a breeze (just paste them in), the WYSIWYG editor works great (feels similar to using outlook) and the interface is clean and simple. One annoyance is that it doesn't seem to have built in spell checking... but I'm willing to let that slide.

The HTML viewer is formatted nicely and syntax colouring is good and there is tag completion. Overall an impressive product which is donationware, head over to the website for a full list of features and download:

http://www.zoundryraven.com/

Saturday, January 10, 2009

A quick look at Mozilla Flock for blogging

Personally I hate doing any kind of serious work within a web form, the as good as Wordpress's WYSIWYG editor is, I find the user experience within a web form irritating.

So to try and get around this possibly illogical attitude, I'm giving the new mozilla 'browser' a go, which is called Flock. So far it's relatively interesting and seems to be firefox with some extravagent plugins to interface which a bunch of popular web services.

The current one of interest to me is the ability to use flocks own editor to publish directly to a multitude of blogging engines (even user hosted ones) which I do like the idea of.

Edit - Unfortunately, whilst Flock is able to upload pictures automatically to Flickr, it cannot upload to wordpress's media library, nor allow you to specify a custom ftp server for your blogs images - Nevermind :-(

Maybe when the product matures and such functionality is available it will be a more powerful platform for blogging, what I say so far was quite nice:

2009-01-10_183444.png

The configuration is painless as you only need t specify your blogs URL, username and password, and your good to go.

Givens Flocks a mozilla product, it might be worth attempting a plugin at some point to add custom uploading support. If you use Flickr, Facebook or some of the other gallery platforms Flock may well be for you!

Too lazy to use phpMyAdmin to back up a database on a remote server?

Heres a nice little command to backup all your database into a SQL file:

mysqldump -uusername -ppassword --all-databases --opt >/location/backup.sql

Together with a bit of cron and it should be nice a backup solution onto a remote server.

Part of the reason for this is that my MySql server is not accessible remotely and my VPS is accessible by SSH only.

Basis for this taken from, although the command posted there was missing the --all-databases flag:
http://www.pantz.org/software/mysql/mysqlcommands.html

Installing VMWare Server 2.0 on Ubuntu "Hardy Heron" woes

You may get a complaint to the effect of:

Your kernel was built with "gcc" version "4.2.3", while you are trying to use "/usr/bin/gcc" version "4.2.4".

But no worries, if you continue and force [yes] it should install fine and work normally.

However, my vmware refused to start with:

vmware is installed, but it has not been (correctly) configured for this system. To (re-)configure it, invoke the following command: /usr/bin/vmware-config.pl.

In order to get around the problem I attacked it randomly by:

sudo apt-get update

sudo apt-get update
sudo apt-get upgrade
sudo apt-get install build-essentials
sudo apt-get install linux-headers-`uname -r`

And re-ran:

sudo vmware-config.pl

Say [yes] to compiling with the incorrect version and hopefully your's will then work as mine did...

A really inspirational project

Personally I have never been strong at communication, and as a demographic programmers probably share this as a failing.

Recently I was rolled of a project which I was part of for a year, where I learned just how important communication and knowledge sharing is between peers, a big enough lesson for me to attempt to maintain a blog (three previous failed attempts).

Our medium for knowledge sharing was rather retro: emails. But we've learned is that what works - works. Theres no point trying to setup a forum or Wiki if no-one has the patience to use it, with real importance given to activity and participation. The atmosphere and attitude in the email threads we're motivating, inspiring and copious amounts of fun :-)

There's a satisfaction in sharing knowledge, helping others, and hopefully for having a platform to receive feedback from others, so:

My reasons for this blog?

  • Personal dumping ground of information I would like to archive.
  • Keep my peers better updated in what I'm doing.
  • Give Google a chance to index some potential useful information for other coders.
  • Satisfaction in contributing to the blogging community.

It is true that I could maintain a personal Wiki to dump my own useful information and use emails to keep peers updated, but I'm far too lazy (I'm sure you understand) to have to deal with more than one medium.

Why did I write this post? Mainly so I know why I'm maintaining this blog...