Unit Of Work Pattern

I’ve done some research on the Unit Of Work pattern and this post will show you what I’ve learned.

Definition

A short version of the official definition of the term “Unit Of Work” can be found on Martin Fowler’s website. A longer version can be found here.

Implementation
A small proof of concept type of implementation can be found at Code Insanity: The Unit of Work Pattern. He continuous in his post Implementing a persistence ignorant Unit of Work framework.

Looking around the internet for information you will often find remarks about the Unit Of Work pattern in conjunction with multiple threads. The article over at InfoQ named Confusing unit-of-work with threads gives a good overview on the caveats lurking there.

Now, how do we use this Unit Of Work?

Usage in ASP.NET applications

There is a great deal of concensus on how to apply the unit of work pattern in web applications in general and in ASP.NET in particular.

In general, in web applications the Unit Of Work per Request implementation is used. You can find a sample implementation in the article Using the unit of work-per-request pattern in ASP.NET MVC and using NHibernate in NHibernate Best Practices with ASP.NET
An alternative is the Unit Of Work per Conversation. The Transactions and Units of Work in Web-Applications article gives a good general introduction and the post What are the benefits of session-per-conversation? compares the two approaches.

Usage in Windows Foms applications

Windows Forms applications are a completely different beast. In a web application there is a natural boundary of a request. There is however no such thing in a winforms application. So finding guidance is difficult. The abone mentioned post Transactions and Units of Work in Web-Applications is a good start.

Conclusion

The Unit Of Work pattern is a basic pattern to streamline data access in applications. It provides a means to keep track of changes to your business objects and apply the changes as a single unit of work to your database,

I hope you found the links illumminating and if you have any yourself, please leave a comment.

Links
Definition:
P of EAA: Unit of Work
IS Architecture Pattern: Unit of Work

Implementation:
Code Insanity: The Unit of Work Pattern
Code Insanity: Implementing a persistence ignorant Unit of Work framework
InfoQ: Confusing unit-of-work with threads

General usage:
Transactions and Units of Work in Web-Applications

In ASP.NET:
Using the unit of work-per-request pattern in ASP.NET MVC
NHibernate Best Practices with ASP.NET, 1.2nd Ed.
Appling Unit Of Work pattern
ASP.NET MVC, DataContext and The Unit of Work Pattern

Advertisements

What did we learn this week? Week of 19 januari 2009

Links for this week:

Global namespaces
I wanted to name a namespace “CompanyName.System” which turned out to be a bad idea: it gave me the unfortunate compiler error “The type or namespace name ‘SomeClassName’ could not be found”. The solution is easy according to the MSDN article How to: Use the Namespace Alias Qualifier (C# Programming Guide) but unfortunately the error happened in the designer file of a Windows.Form and there is no point in changing any code there. I suppose Microsoft should use the global:: identifier in generated code but they don’t. Or is there a solution I’m overlooking?

WCF Service hosting and Client access in a Windows Forms application
Actually, I came across this one too late. Last week I made a test application which was I simple Windows Forms application whome hosted a WCF service and connected to that same WCF service. A big NO GO was the result, as this guy also experienced…

WCF Services with constructor parameters
I eventually didn’t use it, but I had a use case this week for having a WCF service in which the constructor would have some parameters. An alternative could be to provide the object instance to use for implementing the service yourself instead of letting WCF instantiate it for you as the standard behaviour is. Again, I’m not the first one willing to do this as these links prove:
Unity & friends: The WCF service host side
WCF Dependency Injection Behavior
WCF Service Dependency Injection

Generics in .Net
I’m still getting used to this. Comming from a C++ background I’m still suprised by compiler errors trying to use a template parameter as a base class, or as an attribute parameter. In C# this is not allowed. Why? Read these posts:
Generic argument as a base class
Generic argument as a base class
Using Generic Parameter as an Attribute constructor parameter

For once and for all: class inheritance in C#

Methods of a class

The methods of a class are stored in a kind of table which maps the method signature to the method implementation. If you then call a method in your code, this table is consulted and the correct implementation of the method is called.
This is illustrated in the following figure:

classinheritancesuperclass

Derive class from another Base class

Deriving a class from another class makes the methods of the latter, the superclass class, available from instances of the former, the subclass. If you have no overlap in the signatures of the methods then nothing special happens. If you have methods in the both classes with the same signature, then without doing anything, you will get a compiler warning:

‘<subclass method signature>’ hides inherited member ‘<superclass method signature>’. Use the new keyword if hiding was intended.

If you want to compile without warnings, a good thing, you must preceed the method in the subclass with the ‘new’ keyword.

Thus in the superclass we have:

public string SomeClassMethod()

and in the subclass we have:

new public string SomeClassMethod()

The result of hiding a member is that when we have a class of the instance of the subclass and cast it to an instance of the superclass, then the method of the superclass is called:

ClassFromClassDefinition inherited = new ClassFromClassDefinition();
ClassDefinition inheritedAsParent = inherited;

Assert.AreEqual(ClassFromClassDefinition.ClassFromClassDefinitionSomeClassMethodReturnValue, inherited.SomeClassMethod());
Assert.AreNotEqual(ClassDefinition.SomeClassMethodReturnValue, inherited.SomeClassMethod());
Assert.AreEqual(ClassDefinition.SomeClassMethodReturnValue, inheritedAsParent.SomeClassMethod());

What happens is illustrated in the following image:

classinheritancevirtualnew

When deriving from a superclass, the methodtable of this superclass (ClassDefinition) is integrated in the methodtable of the subclass (ClassFromClassDefinition). As you can see from the SomeMethod table entries you now have two entries for them: one for the superclass methodtable and one for the subclass methodtable.

If you access an object of the type of the subclass from an instance of this subclass, you use the methodtable for the subclass. If however you cast to the superclass, then the methodtable you use is the one for the superclass and calling SomeMethod results in calling the superclass version of this method. Something which isconfirmed by the above assertions.

If you don’t want this behaviour but instead want the subclass method to be called from superclasses casted from the subclass, you must use the ‘virtual’ and ‘override’ keywords

Thus in the superclass we have:

virtual public string VirtualMethod()

and in the subclass we have:

override public string VirtualMethod()

which results in the desired behaviour:

ClassFromClassDefinition inherited = new ClassFromClassDefinition();
ClassDefinition inheritedAsParent = inherited;
 
Assert.AreEqual(ClassFromClassDefinition.ClassFromClassDefinitionVirtualMethodReturnValue, subclass.VirtualMethod());
Assert.AreEqual(ClassFromClassDefinition.ClassFromClassDefinitionVirtualMethodReturnValue, subclassAsSuper.VirtualMethod());

This is illustrated by following picture:

classinheritancevirtualoverride1

Now, don’t be fooled in thinking the ‘virtual’ keyword resulted in the above behaviour. It is actually a cooperation of the ‘virtual’ and ‘override’ keywords.
If you replace the ‘override’ keyword with the ‘new’ keyword you get the old behaviour of hiding and casting to the supertype will reveale the hidden supertype member.
Thus ‘virtual’ creates the opportunity for users of your class to use overriding or hiding behaviour by choosing the either the ‘new’ or ‘override’ keyword.

However, what happens when using ‘third generation’ inheritance, thus:

public class ClassDefinition
public class ClassFromClassDefinition : ClassDefinition
public class ThirdGenerationClass : ClassFromClassDefinition

There are a few combinations possible here which I will not all explain in this article.
You can download the associated code which provides sample implementations of the combinatons and assertions to see what happens.

The general conclusion we can make is the following:
The ‘virtual’ keyword marks a method as being a candidate for overriding and is generally used in the superclass
The ‘overriding’ keyword marks a method as overriding and is generally used in the subclass
The ‘new’ keyword marks a method as hiding the superclass member
The combination of the ‘new’ and ‘virtual’ keywords in the middle of an inheritance tree marks a method as hiding the implementation of all classes below and make the method a candidate for overriding for all classes above this class in the inheritance tree

Download

You can download the sample code here. To run it you will need MbUnit because that is used to make the assertions. However, just studying the code will also get you a long way. Enjoy…

Links

Superclass (computer science)
Subclass (computer science)
Virtual method table

For once and for all: Graphics.DrawImage

During development of the last update of my Offline Maps application I had been struggling with the DrawImage method of the Graphics class in the System.Drawin namespace

All in all it’s not that difficult. You just need to read the documentation very carefully and understand the meaning of the words.

Just to share what I learned, here’s a little tutorial on the method, more specifically the version that accepts two rectangles: DrawImage(Image, Rectangle, Rectangle, GraphicsUnit)

Create the source bitmap:

Bitmap sourceBmp = 
   new Bitmap(113, 113, PixelFormat.Format24bppRgb);
// perform some initalization on the bitmap ...

Which gives us the following:

In this bitmap, we define a source rectangle. The coordinates of the rectangle are relative to the origin of the bitmap:

Rectangle sourceRect = new Rectangle(21, 64, 157, 86);

This results in following rectangle, with respect to the bitmap:

Next, we define a target bitmap and take its graphical device context:

Bitmap target = 
   new Bitmap(118, 97, PixelFormat.Format24bppRgb);
// perform some initalization on the bitmap ...
Graphics gtargetBmp = Graphics.FromImage(target);

We have following empty bitmap (the rectangle is to show its defining rectangle):

And relative to this bitmap (or device context) we define the target rectangle:

Rectangle destinationRect = new Rectangle(-31, -21, 121, 69);

This results in:

And finally we execute our DrawImage method saying:

  1. take this target bitmap (actally its device context) and in it we draw
  2. the Source Bitmap
  3. in the Destination Rectangle (relative to the target bitmap)
  4. using the Source Rectangle (relative to the source bitmap)
gtargetBmp.DrawImage(
   sourceBmp,
   destinationRect,
   sourceRect,
   GraphicsUnit.Pixel);

A visual presentation gives us:

And the final result is:

Voila, hope this helps someone in making sense of this method. As I said, it’s really not that difficult, just got to keep your head with it.

Downloads

Sample code

Writing code for both the full .NET Framework and the .NET Compact Framework

Porting my Offline Maps application to the .NET Compact Framework, I was in for a big supprise:

I thought it would be simple: I intentionally seperated most of the GUI code from the Business code thinking that I would simply need to port the GUI and everything would be OK.

No sir, that didn’t work…

Problems encountered

The first supprise was that in Visual Studio 2005 you can not set a reference in a Device Application project to a normal .NET library. You must specify a special Class Library project specific to Windows Mobile (I’ ve been using the Windows Mobile 6 Professional SDK).

Secondly, not being used to programming for the .NET Compact Framework, I thought that having explicitly used mainstream classes, a simple recompile for the Compact Framework would suffise. However that didn’t work: apparently you can have equally named classes, but they don’t necessarily have the same methods. The Compact Framework mostly just supports a subset of the full Framework class methods.

Solutions

Looking for solutions I came across this article.
It offers a multitude of solutions from which I mostly used the “one folder, two projects” and “use partial classes”.

Another point to keep in mind is that if you have overloaded methods in a class with versions taking objects and versions taking the bare properties of those objects, sometimes the Compact Framework only supports those taking bare properties.

An example of this last case is a method which takes a rectangle as an argument opposed to a method taking an X and Y coordinate for the position and a Width and Height for the size of the rectangle.

Also, if some classes or methods aren’t supported that can lead to a whole area of functionality not being supported. An example of this are the StartCap, EndCap and LineJoin properties of a pen which are not supported in the Compact Framework. They can require you to implement a complete abstraction layer for your functionality. Fortunately I got a way with a partial class with two different implementations of a “CreateRoundedPen” method.

Something which surprised me the most is that some Environment static properties which after all are meant to enable cross platform development aren’t supported neither.

As an example the Compact Framework does not support the Environment.NewLine property. Weel, at least not in the version I used. I noticed in the Compact Framework 3.5 documentation that it is now supported.

Conclusion

So, cross device development from a single code base does take some preparation. It requires you to think about how to setup your projects folder structure and to read the documentation on classes and methods so to choose the method supported in both platforms.

But what experience, and derived from it tips, do you have?

Links

[1] Share Code: Write Code Once For Both Mobile And Desktop Apps
[2] MSDN documentation on the Environment.NewLine property

Version numbering: solutions to questions remaining

A while ago I posted an entry about version numbering and ended it with two questions:

  1. When is backward compatibility broken? This probably looks like a stupid question, but imagine: A DLL named “SomeFunctionality.dll” uses some other DLL’s, named “Other.dll” and “MoreOther.dll”. But then this ”SomeFunctionality.dll” is changed and doesn’t use “Other.dll” anymore, but uses “Another.dll”. However, the interface of “SomeFunctionality.dll” didn’t change. Is backward compatibility broken or not?
  2. What about customer related changes to old software which breaks backward compatibility? Say for example you have version 1.1.0.1 at a customer site. Meanwhile version 2.x.y.z has already been released. Now the customer with version 1.1.0.1 wants some new feature which breaks backward compatibility. However, major version 2 is already taken. What major version do you use?

After some thought I will present you today with possible solutions.
Continue reading

Implementing a Development Environment

Developing software is more than just writing code.

It involves some paperwork like writing software design specifications, writing documentation.
It involves building the binaries from your code and deploying them.
It involves testing your binaries: unittesting, integration testing, etc…
It involves managing your source code, versioning it, etc…

To do this, you need a lot of tools.
These are the tools we use:

Continue reading