Migrating from ‘asmx’ webservices to WCF with Spring.Net

Building webservices with Spring.Net is a piece of cake. The framework supported a single programming model long before WCF was available, exposing your service was just a different entry in your configuration. If you’re interested how you need to do this, please read my previous blog entries.

WCF introduced this same concepts to the main .Net Framework but also provides a lot of other functionality out of the box. Security, logging, … just change some xml tag and you’re done.

I make it sound a bit too easy here 🙂 figuring out what is wrong in your service section of the app/web.config is frustrating even with all the tools that are available.

So what do we need to change in our application to switch from ‘old’ webservices to the WCF counterpart?

Well if you’ve been following some best practices then your service is already behind an interface, and that means the only thing you have to change is the way Spring injects this service in your application.

public class OrderPresenter
	: IOrderPresenter
{
	public IOrderService OrderService { get; set; }
	public IOrderView View { get; set; }
}

With the code example above the presenter expects an instance which implements the IOrderService interface, it doesn’t care if it’s WCF, ‘asmx’ webservice or just a local object.

To add a WCF client object you do not need to change anything in your existing codebase, only the way Spring can find the Service you’re connecting to as illustrated below.

<object id="OrderService" type="ServiceContract.IOrderService, ServiceContract"
		factory-object="OrderServiceChannelFactory"
		factory-method="CreateChannel" />
 
<object id="OrderServiceChannelFactory"
	type="System.ServiceModel.ChannelFactory&lt;ServiceContract.IOrderService>, System.ServiceModel">
	<constructor-arg name="endpointConfigurationName" value="OrderServiceEndpoint" />
</object>

The OrderService above will be used by my presenter, and is created via the OrderServiceChannelFactory. Anyone who has some experience with WCF sees that this is just the same as you would do in code when using channels.

So we’re done!

No, not really. There is one, rather big, caveat.

In the ‘old’ days my client service reference would still function if there had been an exception. For example if the network cable was unplugged and I called a method on the server I’d get an exception. If I’d plug the cable back in and call the method again, my client service reference would still function and call the server successfully.

This is not the case with WCF channels, if there is an exception, either communication wise, like the unplugged network cable, or the server throws an exception my client channel will transition in a ‘faulted’ state. Any calls I make on this instance will fail, I need a new instance from the channelfactory to get my application going again.

I could change my presenter to check the service reference, but that would mean I need to couple my presenter to WCF and need to add new behaviour. This is not something you’d want to do. I can’t get around this problem by ‘normal’ AOP techniques. I can’t let the channel check it’s own status and have it magically change it’s own memory reference to a new instance.

Wouldn’t it be great if that boilerplate code (checking the state, creating new channels,….) was automagically done when calling a method on my client service reference?

Well using the Spring framework I’ve been able to accomplish this. You won’t need to change or add any code as long as your service is exposed with an interface. At runtime a new subclass of my ChannelManager class is created which implements the service interface. All calls are forwarded to the ExecuteInChannel method, which creates a channel, calls the method you originally wanted to execute, returns the result and closes the channel. You can also subclass the ChannelManager class to change the way you want to manage your channels.

Over the next few days I hope to add some more functionality, like channel pooling and test it a bit better. Source code will be available.

Series:

Reduce PDF file size

When you’re busy in Pages and adding pictures to your document the file size increases dramatically, this is also reflected in the size of the PDF when you export it. There is however a very easy way to reduce the amount of MB by using the ColorSync Utility.

Just start that program, select ‘File’, ‘Open’. Choose your PDF, then select ‘File’, ‘Export’. In the dialog you now get choose as Quartz Filter ‘Reduce File Size’, hit save. You now have a PDF the fraction of the size of the original without any noticeable quality loss (depending on the original file).

I’ve been able to create a 1 MB PDF from an original of 60, while the pages document was 100 MB.

This week on my screen #2

A lot of WCF, since that’s what I’m doing at work for the moment. Still looking for a good book on it, if anyone has suggestions please let me know.

Oh yeah, I started tweeting. How fashionable.

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();
				   });
	}
}