Using Fluent NHibernate in Spring.Net

In order to load the mappings you’ve written using Fluent NHibernate you need to call the extension method “AddMappingsFromAssembly” on the configuration. The “LocalSessionFactoryObject” defined in Spring.Net supports out of the box the loading of .hbm files from an assembly or a location in the file system. Luckily this class can be extended with ease. The code below is all you need to use Fluent NHibernate with Spring.Net, any suggestions for a better name are welcome.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Spring.Data.NHibernate;
using FluentNHibernate;
using System.Reflection;
using NHibernate.Cfg;
namespace SessionFactories
    public class FluentNhibernateLocalSessionFactoryObject
	: LocalSessionFactoryObject
        /// <summary>
        /// Sets the assemblies to load that contain fluent nhibernate mappings.
        /// </summary>
        /// <value>The mapping assemblies.</value>
        public string[] FluentNhibernateMappingAssemblies
        protected override void PostProcessConfiguration(Configuration config)
            if(FluentNhibernateMappingAssemblies != null)
                foreach(string assemblyName in FluentNhibernateMappingAssemblies)

Update 29 June: please check the comments since a new version brought some changes to this blog post.

iPhone Tech Talk Amsterdam

In October I read about the iPhone Tech Talk tour and immediately registered for the event. I’m still teaching myself Cocoa so I thought this could be helpful. Only a week before the actual start time people got their registration confirmations and I was one of the lucky few. While I can’t go into detail about the content of the event, since I’m bound by the NDA. Which is strange to say the least, wouldn’t you want people who take the time to go to your event to talk about it with others?

Anyway, the actual agenda varied from the one posted on the website. The presentations I saw were:

  • iPhone Development Overview
  • iPhone User Interface Design
  • iPhone Development Tools Overview and Programming Concepts
  • Introduction to Objective-C and Cocoa Touch
  • Developing iPhone Applications with UIKit
  • Maximizing Your Application’s Performance on iPhone
  • Submitting to the App Store using iTunes Connect

If you compare this with their original list, you see that there were a lot more sessions than originally planned and as a result the speaker had a lot of trouble fitting it all in his schedule. Which is disappointing, removing two or three topics would have been better especially since there was a lot of overlap between some of them. User Interface Design for instance explained all the different controls available and this was repeated again in the UIKit presentation. What would have been better was explaining the concepts behind it in the first session and then actually implementing a sample application using the UIKit. Model View Controller was also explained three times, why not explain it once and show code the second time. Knowing the theory behind it is good, but actually showing us why some things are in place would have been better.

Did all this make it a useless event? Certainly not, if there is one in the future I hope I will be able to attend again and because this was the first time Apple organized something like this they probably still have to learn what content fits and what not.

And ow yeah, catering was excellent! 😉


If you’re into and speak dutch, though it’s not really required, you might be interested in the dutch group. The plan is to have regular meetings “with like minded people to discuss and demonstrate the merits and drawbacks of different approaches in .net development”. For the next meeting we’re trying not to have an agenda, let’s see where that goes.

Adding transactions and exploring the BindingList

I stopped working on my todo sample after all the frameworks were playing nicely together and my todo list was displayed. Next up was adding edit capabilities.

At work I normally use Spring.Aop to inject an INotifyPropertyChanged implementation into the objects I pass to the view, but since I’m trying out new stuff here I turned to the default .Net BindingList to support change notification. I’m actually quite happy with the capabilities that are provided, for now at least. The BindingList has a ListChanged event which gets fired if either a property of an object in the list gets changed or the list itself is modified. For my basic sample here this is more then enough. Something I struggled with however, was how to turn off notifications while the list is being populated with data which improves responsiveness of the UI. After some googling I found that you had to call ResetBindings, strange that I didn’t find anything on MSDN that told me how to work in this scenario. I might need to pick up a book on Windows Forms development though, professionally I work with WinForms 99% of the time when I need to create a UI, who knows what other ‘goodies’ I’m missing out on.

public void SetDatasource(List<TodoDto> todos)
    todoDtoBindingSource.RaiseListChangedEvents = false;
    todoDtoBindingSource.DataSource = todos;
    todoDtoBindingSource.RaiseListChangedEvents = true;

With the UI now raising events when the user makes changes, the presenter that is listening had to keep track of the changes and forward them to the webservice when the user wants to save his work. The code I’ve written for that isn’t rocket science or hard to grasp. It boils down to what is transferred between the client and the server.

public enum ChangeType
    Added = 0,
public class TodoEditDto
    public virtual Guid EditId { get; set; }
    public virtual TodoDto EditedTodo { get; set; }
    public virtual ChangeType ChangeType { get; set; }

The ChangeType indicates what has happened, the item was added, changed or deleted. The TodoEditDto wraps the edited dto, adds a ChangeType and EditId property. The EditId is generated on the client and used to identify newly saved objects when the server sends back the Id’s that were generated when the todo was persisted. That way a new created todo can be edited right away after saving it.

// saved data to server
foreach (var persistedEdit in response.PersistedEdits)
    var foundEdit = (from edt in editedTodos
                     where edt.Value.EditId.Equals(persistedEdit.EditId)
                     select edt.Value).First();
    foundEdit.EditedTodo.Id = persistedEdit.EditedTodo.Id;

With some basic editing now in place, some work is still needed in the UI, let’s now add transactional support to our save method. Spring.Net allows you to add this capability declarative or programmatic and even within these two approaches there are several ways to achieve your result. At work I’ve always used the declarative way using AutoProxy and the [Transaction()] attribute. To make that work you need to add a reference to Spring.Data, add the attribute to the methods that need to be transactional and add the following object definitions to your configuration.

<object id="AutoProxyCreator" 
		type="Spring.Aop.Framework.AutoProxy.DefaultAdvisorAutoProxyCreator, Spring.Aop"/>
<object id="TransactionAdvisor"
		type="Spring.Transaction.Interceptor.TransactionAttributeSourceAdvisor, Spring.Data">
		<property name="TransactionInterceptor" ref="TransactionInterceptor"/>
<!-- Transaction Interceptor -->
<object id="TransactionInterceptor"
		type="Spring.Transaction.Interceptor.TransactionInterceptor, Spring.Data">
		<property name="TransactionManager" ref="TransactionManager"/>
		<property name="TransactionAttributeSource" ref="AttributeTransactionAttributeSource"/>
<object id="AttributeTransactionAttributeSource"
	type="Spring.Transaction.Interceptor.AttributesTransactionAttributeSource, Spring.Data">
public SaveEditedTodosResponse SaveTodos(SaveEditedTodosRequest request)
    // do stuff

At runtime, Spring.Net will create a proxy for each service that has the tranascation attribute declared on its methods and manage the transaction from in that generated class. Everything you’ve written will be transactional from that point until the method that is being called is completed. For now however, let’s use the TransactionProxyFactoryObject. To use this approach I only need to change my service definition. Through the transaction attributes property I can define which methods need to be transactional, in this case any method that starts with Save. The target property can be any object in your context.

<object id="TodoService" 
		type="Spring.Transaction.Interceptor.TransactionProxyFactoryObject, Spring.Data">
	<property name="PlatformTransactionManager" ref="TransactionManager"/>
	<property name="TransactionAttributes">
			<add key="Save*" value="PROPAGATION_REQUIRED"/>
	<property name="Target">
		<object type="TodoCore.AppService.TodoService, TodoCore">
			<property name="TodoRepository" ref="NhnTodoRepository"/>

With this in place we now have a basic application which is workable in a test environment. Speaking about tests, I really need to add them to the project. I’m not a very good TDD’er myself, though I’m convinced it is the way to go. I should start applying it.

SampleApplication04092008.rar (2.95 mb)

Using Spring.Net, SQLite and NHibernate

I was planning to put a quick spike together on putting single sign-on, using CardSpace, OpenID and Windows Live, into an application to test it out for a project at work. Maybe it was because of the weekend, but I was quite enthusiastic and added several technologies to the sample which I had never used before. Six hours later, there was still no single sign-on or even a fully working sample application to add the behaviour to. So instead of posting one post, I’ll have a mini series where SSO will actually be a side track.

Getting the database set up was one of the first things I wanted to do. I didn’t want to add a MS SQL database to the project since that would require anyone who downloaded this project to have the database engine running. On various other blogs and .Net sites I’ve read there was talk about a lightweight alternative in the form of Sqlite. The .net provider can be downloaded here and boy was I lucky, the day I wanted to try it out they released a new version. Their latest version includes designer support in Visual Studio. Halfway august the Spring.Net team had also released a new version (1.2 M1) so I grabbed that version and NHibernate went 2.0 GA as well.

Since the Spring.Net assemblies are strongly signed they expected SQLite 1.0.56 and not 1.0.58 which was the one I downloaded. To make use of the new dll’s I added this to my configuration.

<db:provider id="DbProvider" provider="SQLite-1.0.56" connectionString="${db.datasource}"/>

Spring.Net has several DbProviders already configured, one of them being for version 1.0.56. Normally you don’t want to configure the entire provider for a new version so I just reused the existing configuration and added an assembly redirect.

<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
    <assemblyIdentity name="System.Data.SQLite" culture="neutral" publicKeyToken="db937bc2d44ff139"/>
    <bindingRedirect oldVersion="" newVersion=""/>

This is all defined in the spring manual, but it actually took me quite some time to get it running. Only when adding the xml namespace the redirect was picked up when running the application. The NHibernate version I had was also newer so a redirect was necessary for those dll’s as well.

With this out of my way I still had to tell NHibernate to use SQLite. The official site gives this sample configuration:

<?xml version="1.0" encoding="utf-8"?>
  <hibernate-configuration  xmlns="urn:nhibernate-configuration-2.2" >
    <session-factory name="NHibernate.Test">
      <property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
      <property name="connection.driver_class">NHibernate.Driver.SQLiteDriver</property>
      <property name="connection.connection_string">
				Data Source=nhibernate.db;Version=3
      <property name="dialect">NHibernate.Dialect.SQLiteDialect</property>
      <property name="query.substitutions">true=1;false=0</property>

Which is almost correct, but not quite. Below you find the complete correct springified configuration, so extract the pieces you need when using plain NHibernate. The difference is in the driver class.

<object id="NHibernateSessionFactory" type="Spring.Data.NHibernate.LocalSessionFactoryObject, Spring.Data.NHibernate20">
  <property name="DbProvider" ref="DbProvider"/>
  <property name="MappingAssemblies">
  <property name="HibernateProperties">
      <entry key="connection.provider"
      <entry key="connection.driver_class" 
      <entry key="dialect" 
      <entry key="query.substitutions" 
  <property name="ExposeTransactionAwareSessionFactory" value="true" />

Great we’ve configured our data access! But the repository is giving me errors, it can’t find the database file. The project structure I have is illustrated below.

My first attempt was to use relative path names.

<add key="db.datasource" value="Data Source=~App_DataTodoDb.db;Version=3;"/>

But that just failed, to get this working I used the, for me, new |DataDirectory| variable which did cause the database to be found and used.

<add key="db.datasource" value="Data Source=|DataDirectory|TodoDb.db;Version=3;"/>

The data was now being retrieved, isn’t that wonderful, only took me maybe two or three hours. As front end I first added a WPF application, but if you see that Window1.xaml file for the first time you have a bit of a writer’s block. Even when you drag a button on it, you don’t get to see one and adding a grid to the window and then trying to add a column was quite overwhelming, there even seem more options available compared to the third party components I use at work. So for now just good old Winforms, but a WPF front end will definitely be added. I also played around with the bindinglist you can create when using a grid, I must admit I’ve never used it before. I’ve always used my own implementation, we’ll see where it goes when I add an edit mode to the application. So for now I can only give you a configured application which shows your todos, so basically the same setup as my last sample which illustrated the support for webservices.

SampleApplication.rar (2.74 mb)

And before anyone asks, yes tests should be added.

Initializing an array with arrayWithObjects

If you’re creating an array and adding objects to it at initialization, in Cocoa, don’t forget that the last element of the list needs to be nil, it’ll save you debugging time ;).

NSMutableArray *array = [NSMutableArray arrayWithObjects: @"one", @"two", @"three", @"four", nil];

Developer reference.

Cocoa Programming for Mac OS X (Ch 19-21)

After a little Cocoa break I’m back, while continuing through the book I seemed to have forgotten some stuff already, not good.

So, next up, Keyboard Events.

This chapter explains how the events are used for handling keystrokes as well as the first responder concept. The first responder being the active view element (button, text area,…) and there’s a whole mechanism working in the background when the first responder changes. Not a lot of ground breaking material here, probably the most important piece of code here is an example of how to code the fuzzy blue box around an active custom view.

Chapter 20, Drawing text with attributes.

Here we are taught how to show strings in various formats, not that interesting. One nice feature however is that all the drawing commands you write can be converted into PDF by the AppKit framework.

Chapter 21, Pasteboards and Nil-Targeted actions.

The clipboard in Windows, pasteboard in OS X. Different name, same concept, although I’ve never read about it in any .Net book I’ve seen but you know what it does :). What you need to remember from this chapter is that you can do a lazy paste. Meaning that you don’t have to put it in the clip errr pasteboard when the user presses the copy command. You can wait until he presses paste, very valuable if you’re working with large quantities of data.

Nil targeted actions are best explained with an example. You can set the selector (method signature for .net people) of a menu item to anything you want, say removeEmployee:, when the menu item’s target is nil and the menu item is invoked, it will traverse the responder tree until someone acts upon it.

Nothing fancy was covered in these past chapters, but you need to know about these things. I did spend quite some time on the applications, probably because there was a two week pause. For those interested I’ve attached all the source code.

As always, you can get the book here .

TypingTutor – Chapter (46.44 kb)

TypingTutor – Chapter (53.47 kb)

TypingTutor – Chapter 20 Challenge (53.73 kb)

TypingTutor – Chapter 20 Challenge (57.89 kb)

TypingTutor – Chapter (53.58 kb)

TypingTutor – Chapter 21 Challenge (53.75 kb)

RaiseMan – Chapter 21 Challenge (111.20 kb)

Developing .NET Software on a Mac

Followed some links and found this podcast on deep fried bytes. It’s interesting to hear, although the title is a bit misleading. They talk about .net development 25% of the time using virualization tools like VM Ware, the rest of the podcast is filled with general switchers info and some recommended applications.

Nothing about Mono though, too bad.

Breakpoints not being hit in Xcode

It appears that when you do a default install of Xcode debug symbols are loaded lazily, so when you want to debug your code your breakpoints are not being hit. This is rather frustrating if you don’t know about this option, you can disable it in the debugging tab under preferences of Xcode. I wanted to say this earlier, since I ran into this while going through chapter 2 of Cocoa Programming for Mac OS X , but it slipped my mind.

Xcode Preferences Debugging screenshot

Cocoa Programming for Mac OS X (Ch 17-18)

Euro 2008 and the challenge application on the end of chapter 18 have slowed me down, so only some notes about these two chapters this time.

Chapter 17, Custom Views.

This chapter deals about manipulating views (forms) manually. You can compare it with the .net System.Drawing namespace and subclassing the Control class to create your own controls. It also explains the alignment and docking of controls. Pretty basic stuff.

Chapter 18, Images and Mouse Events.

With the new knowledge on how to draw on views we now will allow the user to interact with the form and allow him to draw figures. This is done by handling mouse events. Also the file open dialog is introduced, but it’s called a NSOpenPanel here, to add images on the view.

The challenge application invites the reader to further customize the application, which draws rectangles when you complete the chapter, to draw ovals, adding undo redo capabilities and implementing archiving.

Most of the time I spend finding out how to hook up the document window to the custom view which handled the drawing of the ovals, as always key-value coding saved the day. You should also watch out that when a document is unarchived this is done before UI controls, I mean views :), are created. So don’t start assigning your saved ovals to a view that does not exist yet, like I did. It’ll save you time.

As always, you can get the book here .

ImageFun – Chapter (44.46 kb)

ImageFun – Chapter (46.78 kb)

TheOvalApp – Chapter 18 (65.73 kb)