Presentation: Introduction to Spring.Net

Last Thursday my boss and I gave a presentation on Spring.Net and dependency management in general. The audience mainly, if not only, consisted of students in their 2nd or 3rd year so they probably wondered what all the fuzz was about. I just hope that they will remember the concepts we introduced to them and understand that there’s more to software development than the typical three tier applications you develop in school.

If you were in the audience and have questions on the topic or presentation, feel free to contact me at: me[at]bennymichielsen[dot]be .

The first few slides are based on and contain images from a presentation by Bob Martin and is available on InfoQ. The sample which introduces AOP and has an implementation of INotifyPropertyChanged is based on a sample you find in the Examples directory when you install Spring.Net.

Keynote Presentation:

Introduction.key (730.08 kb)

PDF Version:

Introduction.pdf (1.37 mb)

Samples:

SpringSamples.zip (2.65 mb)

Windows 7 day 2

Came home, installed TortoiseSvn, rebooted, nothing. A reset didn’t help, still had a black screen saying “Starting Windows” but 15 minutes of starting time is more than enough I think.

Resetted the virtual machine again and followed the Startup Repair guide which does a system test. It asked if I wanted to go to a restore point, which I denied and did a complete checkup which stated that everything was ok and that it was probably a newly installed application that caused the problem. I rebooted the system again planning to use the restore option after all, but now, as by magic, the system booted without any problem.

Strange.

I also noticed that when using several instances of the same application, in my case Visual Studio, you no longer get all their window headers in your taskbar but they are all grouped under the same icon. Nice.

Add aspects at runtime without xml to your spring context

A user on the Spring.Net forum asked if it was possible to apply an interceptor at runtime to certain classes without resorting to xml. It turned out to be rather easy to accomplish this and encourages me to look deeper into enabling something like Fluent NHibernate for Spring.Net.

The key interface in this story is “IObjectPostProcessor”. It enables you to edit an object after it has been instantiated and populated by Spring.Net.

public interface IObjectPostProcessor
{
	object PostProcessAfterInitialization(object instance, string objectName);
 
	object PostProcessBeforeInitialization(object instance, string name);
}

The documentation states that the processors that populate entities via marker attributes should use the “PostProcessBeforeInitialization” where as postprocessors that wrap objects with proxies should use “PostProcessAfterInitialization”. In this case it’s clear that since we will create a proxy we need to implement the latter.

public object PostProcessAfterInitialization(object instance, string objectName)
{      
	if (InstanceShouldBeProxied(instance))
	{
		ProxyFactory factory = new ProxyFactory(instance);
		factory.AddAdvice(new WriteLineAspect());
		return factory.GetProxy();
	}
	return instance;
}

The implementation is rather straightforward. The postprocessor has a collection of all the types it should intercept and checks each instance it is handed. If there is a match it will create a proxyfactory, add the advice and create a proxy. Otherwise it just returns the instance.

The application context in Spring automatically picks up any processors it has and will hook it up for you. When deployed in an objectfactory however you need to explicitly register it.

The only thing left to add now is the configuration part for the postprocessor which is demonstrated in the sample below.

private static void RegisterPostProcessor(GenericApplicationContext context)
{
	MyPostProcessor postProcessor = new MyPostProcessor();
	postProcessor.InterceptInstancesOfInterface(typeof(ITaksService));
	context.ObjectFactory.AddObjectPostProcessor(postProcessor);
}

Full source code is available here: Program.cs (3.50 kb)

Yet another Windows 7 post

Like many others, I can report that Windows 7 is running successfully on my MacBook with VirtualBox. Ethernet and wifi started working after installing the Guest Additions of VirtualBox. Visual Studio 2008 is already installed and it seems to work.

WPF Application by Billy Hollis

I had seen presentations by Billy Hollis before (via InfoQ) and ran into this one today. If you aren’t convinced what WPF can do for you, as WinForm developer, go check it out.

If you’re not into WPF, the site has much more interesting .Net material.

Mapping a list of components with Fluent NHibernate

This took me some time to figure out since documentation for Fluent NHibernate is still a little scarce. Let’s say we have an entity “ActivityType” which has an icon and a name, but the name is stored for each language so we have a one to many relationship. This relationship is not only modelled in the entity “ActivityType” but also in several others. The translation is modelled in the “LocalizedEntity” class. As illustrated in the class diagram below:

The DB is illustrated in the next diagram, to make it easy the tables have a different name compared to the entity diagram :p.

The mapping for the “Language” entity is pretty straightforward. The mapping for the “ActivityType” and its localizations was a bigger challenge since I got lost in all the delegates after the Component method.

public class LanuageMapping
: ClassMap<Language>
{
	public LanuageMapping()
	{
		Id(x => x.Id);
		Map(x => x.Name);
		WithTable("[7de_Languages]");
	}
}
 
public class ActivityTypeMapping
: ClassMap<ActivityType>
{
	public ActivityTypeMapping()
	{
		WithTable("[7de_EventTypes]");
		Id(activityType => activityType.Id);
		Map(activityType => activityType.IconName);
		HasMany<LocalizedEntity>(activityType => activityType.Descriptions)
		.WithTableName("[7de_LocalizedEventTypes]")
		.Component(description => 
				   {
				   description.References<Language>(desc => desc.Language)
				   .CanNotBeNull();
				   description.Map(desc => desc.Localization)
				   .CanNotBeNull();
				   });
	}
}

Apple developing home media server

Last week, just when I thought I had looked into every option available for a home media server the rumor is posted that Apple might be creating one. Better just wait for the keynote which will be held Tuesday at 9 am PST or 18 CET.

Image from MacRumors forums.

Virtualisation with VirtualBox

Whenever you look around for virtualisation solutions on the Mac platform you get two answers: VMware Fusion and Parallels. One you don’t hear so much about however is VirtualBox from Sun. I haven’t used the first two since VirtualBox is open source and free of charge. I first installed it two months ago and although it worked it was extremely slow. This was not so much due to the software rather my machine only had 1 GB of RAM available and running two operating systems is rather intensive. A few weeks ago I upgraded to 4 GB and tried out VirtualBox again, I’ve been using it almost daily since then. It works great!

Most of the time I’m a .Net developer so I need Visual Studio and Windows to get my work done and apart from the fact that some keys don’t work, or I haven’t figured out how to get them working, like the function keys, I don’t feel any difference compared to working on a native Windows box. You don’t loose any responsiveness.

Copy Pasting text is supported, so I can copy text from i.e. Safari into Notepad. While skimming through the manual there was a mention on how to share files between the two operating systems but I haven’t really looked into that. It works with shared folders to achieve this functionality, the two other virtualisation options support drag and drop I think.

You can run VirtualBox as any other window but most of the time I run it in seamless mode. This means that the applications you start in Windows can be placed next to your running OS X applications, seamlessly. This is illustrated by the attached screenshots, the first one shows the Windows applications locked on the Windows desktop and the second one shows the same applications but now running in seamless mode.

I first used spaces to keep my OS X and Windows applications separated but found that not comfortably to work in. I would look something up in Safari then switch to Visual Studio and saw all the applications fly from left to right, a few minutes later I’d receive a mail and everything flew back again. If there would be one school example on why to use spaces I thought it would be virtualisation but now I’m not convinced of the entire idea any more. Why on earth would you use it except for adding more icons on your desktop.

So, to sum it up, if you need to run Windows on OS X and don’t want to reboot everytime for BootCamp, go download VirtualBox!

Since a video says so much more on how everything works, here is a movie I found on YouTube:

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
        {
            get;
            set;
        }
 
        protected override void PostProcessConfiguration(Configuration config)
        {
            base.PostProcessConfiguration(config);
            if(FluentNhibernateMappingAssemblies != null)
            {
                foreach(string assemblyName in FluentNhibernateMappingAssemblies)
                {
                    config.AddMappingsFromAssembly(Assembly.Load(assemblyName));
                }
            }
        }
    }
}

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

Blog Intentions for 2009

The last three months my activity here has dwindled down, but I’m going to try to pick up the pace again. Still need to get through the final chapters of Cocoa Programming for Mac OS X , talk about and implement single sign on in a desktop application, try out some new technology in the todo application, build a mediaserver,…

In the meanwhile, happy new year ;).