vrijdag 27 januari 2006

Buying Books

I've bought 2 books recently.

The first one is Framework Design Guidelines: Conventions, Idioms, and Patterns for Reusable .NET Libraries (Microsoft .NET Development Series).

framework design guidelines cover
This is a usefull book with some interesting tips for anyone who's interested in or is busy with designing and building frameworks. If you use FxCop, chances are that you're already familiar with most of the tips and guidelines that are in the book. Nonetheless, this book is usefull as reference-book but you can also read it from cover to cover. Most of the guidelines in the book are commented by people like Jeffrey Richter, Rico Mariani, etc... and these comments are very valuable as well.


The second book I've bought is Agile Software Development, Principles, Patterns, and Practices by Robert Martin.

agile software development cover
I haven't found time to start reading this book, but due to the reviews on Amazon and other fora, I'm expecting a lot of it! Maybe I'll post a little review on my blog about this book, after I've read it.

Again, two books that I can remove from my book whishlist

Correction: I didn't really buy the 1st book; it was rather a present. :)

zaterdag 21 januari 2006

Business Objects Framework – Part 2

This is the 2nd article of a serie. The 1ste one can be found here.

In this article, I'll explain the BusinessObjectCollection class. Before starting off with this class, I'd like to go back to the BusinessObject class first, because I want to do a little modification on that class.

Implementation of IEditableObject in BusinessObject


The IEditableObject interface is defined in the .NET framework to control the undo-functionality used by the databinding infrastructure.
There are 2 situations in where this interface is used:

  • If the object is a child of a collection, and this collection is collection is databound to a grid, the IEditableObject interface is used so that the user of the application gets the expected functionality. For instance, when he creates a new row and then presses Escape on that row, the new row should not be added to the collection.

  • When an object is databound to the forms on a control, the IEditableObject.BeginEdit method is called when the object has been changed by the databinding. However, the EndEdit and CancelEdit methods are not called automatically by the infrastructure, and thus, it is the responsability of the application-developer to call these methods.

Since the BusinessObject class already contains the methods defined by the IUndoable interface that are able to undo / commit any changes made to the BusinessObject, I think it is better that the application developer has no 'direct access' to the methods of the IEditableObject interface. The application developer should use our IUndoable methods instead, and the IEditableObject interface should only be used if the BusinessObject is contained in a collection that is databound.

To achieve that the application-developer cannot call the methods of the IEditableObject directly, the IEditableObject interface should be implemented explicitly.
This is done like this:

void IEditableObject.BeginEdit()
{
...
}

void IEditableObject.CancelEdit()
{
...
}

void IEditableObject.EndEdit()
{
...
}


The effect of implementing the IEditableObject interface explicitly is, that the BeginEdit, CancelEdit and EndEdit methods will not appear in the 'Intellisense' list and, that these methods cannot be called directly on instances of BusinessObject.
These methods are only callable if the BusinessObject instance is cast to the IEditableObject type.

Now, the application developer that uses the BusinessObject class, is in a way forced to use the methods of our IUndoable interface if he wants undo-support.

Now we also have to manipulate our _bindingEdit variable in the IUndoable methods instead of in the IEditableObject members:
public void CreateSnapshot()
{
_bindingEdit = true;
...
}

public void CommitSnapshot()
{
_bindingEdit = false;
...
}

public void RevertToPreviousState()
{
_bindingEdit = false;
...
}

void IEditableObject.BeginEdit()
{
if( _bindingEdit == false )
{
this.CreateSnapshot ();
}
}

void IEditableObject.CancelEdit()
{
if( _bindingEdit )
{
this.RevertToPreviousState ();
}
}

void IEditableObject.EndEdit()
{
if( _bindingEdit )
{
this.CommitSnapshot ();
}
}


Now, we can have a look at the BusinessObjectCollection class.

Collections of BusinessObjects


We will need a class that is able to store multiple BusinessObject objects. So, in fact, we'll need to be able to store a collection of businessobjects.
In .NET 2.0, we can use Generics, so that we'll have to create only one BusinessObjectCollection class, and in our application code, we can define what kind of BusinessObject instances this class should contain.

Since CSLA.NET was developped using .NET 1.x, the Collection classes inherited from CollectionBase. However, with .NET 2.0, I can use the Collection<T> class as a base-class for my the BusinessObjectCollection class.
This new Collection<T> class allows me to write less code (I do not have to write my own strong typed Add, Remove, etc... classes), and I do not have to choose in my methods whether I'll use the List or the InnerList property. There's a subtle difference in these properties: List raises events when an item is added / removed, while InnerList does not raise those events.


The rough skeleton of the BusinessObjectCollection class looks like this:

[Serializable]
public class BusinessObjectCollection<T> : Collection<T>,
IUndoable,
IBindingList
where T : BusinessObject
{
}

As you can see, the class is Serializable and inherits from Collection<T> which I just discussed.
Generics are used here so that the application-developer can indicate what kind of objects he wants to put in his collection. However, there is a restriction: the objects that the BusinessObjectCollection can contain, must be inherited from BusinessObject.
So, the application developer can use our BusinessObjectCollection class like this:
BusinessObjectCollection<Customer> customers = 
new BusinessObjectCollection<Customer>();

This will only compile if the Customer class inherits from BusinessObject.

Now, as I said earlier, since this class inherits from Collection<T>, I do not have to write Add, Remove, etc... methods. If I should have used the CollectionBase class, and if I wanted strong typed Add and Remove methods, I should have written those methods like this:
public T this[ int index ]
{
get
{
return (T)List[index];
}
}

public int Add( T item )
{
return List.Add (item);
}


Not only should I have to do this for the Add method and for the indexer, but I should 've done it for the Insert, Remove, ... methods as well.
Now I do not have to do this, because the Collection<T> class already provides this for me. This means that inheriting from Collection<T> saves me a lot of tedious work.

What I do have to do, is, providing extra functionality when a BusinessObject object is added to the collection. If I should have inherited from CollectionBase, I should have been carefull whether I'll use the List or the InnerList property in my own Add and Remove methods, since the List property raises events that I can respond to if I want extra functionality. With the Collection<T> class, I do not have to pay attention to it because this class does not have an InnerList nor List property. It only has an Items property.

I only have to override the InsertItem and the RemoveItem methods.

Every time a BusinessObject is added to the collection, I'll need to keep track of the editlevel at which the object has been added. This is necessary for the 'Undo' functionality of the collection.
Overriding the InsertItem method, allows me to do that:
protected override InsertItem( int index, T item )
{
item.EditLevelAdded = _editLevel;
base.InsertItem (index, item);
}

This means that, the BusinessObject class needs an internal member called EditLevelAdded, that keeps track of the 'editlevel' of the collection at which the item has been added to the collection.
This code also means that our BusinessObjectCollection class needs a private member _editLevel.

When a BusinessObject is removed from the collection, we will need to keep track of the BusinessObject as well, since, when the changes that have been made to our collection are undone, it is quite possible that the previously deleted business-object is to be undeleted.
This means that the BusinessObjectCollection will need a list that contains the BusinessObjects that were deleted from the collection. To achieve this, the BusinessObjectCollection class needs a member that is able to save this collection of deleted BusinessObject instances.
Again, the Collection<T> class is perfectly suited for this. (In .NET 1.x you'll have to create a nested type that inherits from CollectionBase that represents this collection).

Now, every time that an item is being removed from our collection, we'll have to add it to the collection that keeps track of the deleted BusinessObjects:
private Collection<T> _deletedItems = new Collection<T> ();

protected override RemoveItem( int index )
{
// Since we do not have direct access to the item that's
// being removed here, we'll have to get it first.
T businessItem = Items[index];
if( businessItem != null )
{
businessItem.MarkDeleted();
_deletedItems.Add (businessItem);
}

base.RemoveItem(index);
}

Since one of my design goals was to get the data access code out of the BusinessObjects, this means that we'll have to have a way to be able to tell our Data Access components which items were removed, and should be deleted in the database.
This means that we'll have to add these 2 extra methods:
public T[] GetDeletedBusinessObjects()
{
List<T> items = new List<T> ();
foreach( T item in _deletedItems )
{
items.Add (item);
}

return items.ToArray();
}

public void ClearDeleted()
{
_deletedItems.Clear();
}

Now, Data Access Components can use these 2 methods of the collection to see which BusinessObjects should be deleted, and once this is done, they should also be removed from the 'deletedItems list'.

Implementing IUndoable


We still need to implement the IUndoable interface.
Implementing the CreateSnapshot method is quite easy. We only have to make sure that we call the CreateSnapshot method of every BusinessObject that is in our collection, but, we must also not forget to create a snapshot on the BusinessObjects that are in our _deletedItems collection.
private int _editLevel = 0;

public void CreateSnapshot()
{
_editLevel++;

foreach( T item in Items )
{
T.CreateSnapshot();
}
foreach( T item in _deletedItems )
{
T.CreateSnapshot();
}
}

The implementation of CommitSnapshot is fairly simple as well. We just need to call the CommitSnapshot method on every BusinessObject that is in our collection and in the _deletedItems collection.

Implementing RevertToPreviousState is a bit more complex, since we might have a situation in where a deleted BusinessObject should be undeleted; for an exhaustive explanation of the functionality, I'll refer to the Expert C# Business Objects book.
This is the code:

_editLevel--;

if( _editLevel < 0 )
{
_editLevel = 0;
}

for( int i = Items.Count - 1; i >= 0; i-- )
{
T item = Items[i];

item.RevertToPreviousState ();

if( item.EditLevelAdded > _editLevel )
{
base.Items.Remove (item);
}
}

for( int i = _deletedItems.Count - 1; i >= 0; i-- )
{
T item = _deletedItems[i];

item.RevertToPreviousState ();

if( item.EditLevelAdded > _editLevel )
{
_deletedItems.Remove (item);
}

if( item.IsDeleted == false )
{
int saveLevel = item.EditLevelAdded;

// Add the business object back to the list.
Items.Add (item);

if( item.EditLevelAdded != saveLevel )
{
item.EditLevelAdded = saveLevel;
}

_deletedItems.Remove (item);

}
}


In the next article, I'll discuss the LazyBusinessObjectCollection class.

donderdag 19 januari 2006

Car troubles.

Yesterday evening, my car produced a very strange noise when turning.
It seemed that one of my suspensions snapped.

Now, my car (Ford Focus) is being repared and I've received a spare-car.... A Peugeot 106. I do like karting, and I do it alot, but I do not like to drive a kart during rush-hour.
This Peugeot 106 is nothing more then a kart with a back-seat, and wrapped up with some silver foil.

zondag 15 januari 2006

Registration & Comments

When I started this blog, you had to register before you could post a comment. This has been changed so that you can post a comment without being registered.

vrijdag 13 januari 2006

Case sensitive queries in SQL Server

In SQL Server, whether your database is case sensitive or not, depends on the collation that your database uses.

If you have a database that has been setup with a case insensitive collation sequence, but you want to retrieve or sort some data in a case sensitive way, you can do it like this:
SELECT * 
FROM MyTable
WHERE aField = 'a' COLLATE Latin1_General_CS_AS

or, for sorting:
SELECT *
FROM MyTable
ORDER BY aField COLLATE Latin1_General_CS_AS

As you can see, you just have to define a case sensitive (CS stands for Case Sensitive) collation in your query.

Of course, if you have a table that contains data that should be treated in a case-sensitive way, you can create that table/columns with a case sensitive collation sequence.

donderdag 12 januari 2006

Some of my pictures...

I've been practicing photography for more than one year now, and I'd like to share some of my work with you.

These are 4 pictures I've taken somewhere between september 2004 and may 2005. All of them were shot with a Nikon F55 equipped with a 28-80mm zoomlens. I've used a T-Max 400 ISO film, except for the photo with the karts, which was shot on a T-Max 3200 ISO.

I'd like to hear your comments!

pointing child

train

karts prepare to start

fanfare

zondag 8 januari 2006

Business Objects Framework – Part 1

Introduction


More than one year ago, I started reading Expert C# Business Objects by Rockford Lhotka.
In his book, ‘Rocky’ Lhotka explains us how he has developed his CSLA.NET framework.
While his framework has some really nice features, that tackle some problems, it also has some disadvantages.


There are 2 issues in the CSLA.NET framework that are –in my opinion- a big problem:

  • There is data-access code inside the business object.

  • The business object takes care of transaction-handling.


The first issue can be resolved by factoring out the data-access code out of the business object, and putting it in a separate object.
The second issue is a bigger problem. In my opinion, the business object should not be responsible for transaction handling, since the business object does not know the context in where it is used. It is the client itself who should be responsible for the transaction handling, since this is the only place where the context in where the Business Object is used, is known.
(Although the framework has some disadvantages, I think the book is recommended reading material for anyone who is interested in .NET & enterprise applications).

Because of these drawbacks of the CSLA.NET framework, I’ve decided to create my own 'framework', in where I'll implement some good things of CSLA.NET (like n-level undo support, data-binding), but, try to find another solution for the things I do not like.
I also wanted to be able to support lazy-loading of collections.

I will try to explain the things I've done in order to create this set of classes in a serie of articles on this weblog.

N-Level Undo support


So, I already told that the CSLA.NET framework has some features that I really like, like n-level undo support.
This is a feature that I also want in my 'framework'.
Rockford Lhotka has decided to create an UndoableBase base-class that already contains all the functionality for n-level undo support. However, I've thought that it would be appropriate to create an interface that would define the contract to which all types that support n-level undo support must comply to.

This interface just defines 3 methods and looks like this:
public interface IUndoable
{
void CreateSnapshot();
void CommitSnapshot();
void RevertToPreviousState();
}

If you're familiar with the CSLA.NET framework, you probable know (or you can see), that, in the UndoableBase class, a check is performed if a member of the class inherits from the BusinessBase or BusinessCollectionBase class when a snapshot is taken and when the state of an object is reverted to its previous state.
This is a little bit 'dirty' in my opinion, since this code creates some kind of a 'circular reference'. (BusinessBase inherits from UndoableBase, and UndoableBase 'knows' about the existence of BusinessBase).
The introduction of this interface will resolve this problem:
Instead of the two checks (one for BusinessBase and one for BusinessCollectionBase), only one check will have to be performed. The circular reference will also be gone, because the class(es) that will implement IUndoable interface, should then only check if their members implement IUndoable interface as well.

BusinessObject base class


Then, I’ve created an abstract base class BusinessObject from which all the concrete business-objects of the problem-domain should inherit from.
BusinessObject implements the IUndoable and the IEditableObject interfaces.
The latter interface is necessary if you want to support data-binding.

While mr Lhotka created 3 'base-classes' (BusinessBase which inherits from UndoableBase which in turn inherits from BindableBase), I've decided to create only one base-class from which all my business objects will inherit from. I've done this because, at this moment, I do not see the advantage of having the other 2 base-classes.

Since the BusinessObject base-class implements the IUndoable and IEditableObject interfaces, this class is off-course responsible for the n-level undo support and for the databinding.
Apart from that, BusinessObject also contains some 'state tracking' functionality (which is necessary if you do not use an ORM-tool like NHibernate which does the state tracking for you).

The rough skeleton of the BusinessObject class looks like this:
[Serializable]
public abstract class BusinessObject : IUndoable, IEditableObject
{
#region State Tracking functionality
#endregion

#region IUndoable implementation
#endregion

#region IEditableObject implementation
#endregion
}


The class is abstract because it is offcourse intented that you do not use this class directly. You should inherit your 'specific' businessobjects from this class.
The class is also marked as 'Serializable'. This is necessary if you want to use your business objects for instance in a remoting scenario.
Another reason for the Serializable attribute will be clear soon, since Serialization is used to achieve the n-undo functionality.

I still have to discuss the implementation of this class, so let's do it right away.

State tracking


The state tracking code is quite simple. We only need some flags and methods that take care of this.
This code is quite simple and nothing (or very little) has been changed compared with the code that is contained in the BusinessBase class of the CSLA.NET framework, so instead of commenting this code in this post, I'll refer to the 'Expert C# Business Objects' book for further information.
#region State Tracking functionality

private bool _isNew = true;
private bool _isDirty = false;
private bool _isDeleted =false;

protected void MarkDirty()
{
_isDirty = true;
}

protected void MarkClean()
{
_isDirty = false;
}

protected void MarkNew()
{
_isNew = true;
_isDeleted = false;
MarkDirty();
}

internal void MarkDeleted()
{
_isDeleted = true;
MarkDirty();
}

protected void MarkOld()
{
_isNew = false;
MarkClean();
}

public bool IsNew
{
get
{
return _isNew;
}
}

public bool IsDeleted
{
get
{
return _isDeleted;
}
}

public virtual bool IsDirty
{
get
{
return _isDirty;
}
}

#endregion


Implementing N-level undo support


Implementing the n-level undo support requires some more work and is a little bit more complicated then the state-tracking.
Just like in the CSLA.NET framework, this functionality relies heavely on .NET reflection. (In fact, I've played copy-cat here. Apart from the usage of the IUndoable interface, this code is almost identical as the code that Rockford Lhotka has written).

Since the CSLA.NET framework is free to be downloaded (you can get it here), I'll only post some relevant code.

#region IUndoable implementation

[NotUndoable]
/// The stack that will keep track of all our states.
private Stack _stateStack = new Stack();

public void CreateSnapshot()
{
Type currentType;
Hashtable state = new Hashtable();
FieldInfo[] fields;
string fieldName;

currentType = this.GetType();

do
{
// Get the members of this type.
fields = currentType.GetFields (BindingFlags.Public |
BindingFlags.NonPublic |
BindingFlags.Instance);

foreach( FieldInfo field in fields )
{
// If this field is declared in the current type
// and the field is undoable, keep track of it's state
if( field.DeclaringType == currentType &&
this.IsUndoableField (field) )
{
object fieldValue = field.GetValue(this);

// If the member implements IUndoable, cascade
// the call.
IUndoable uf = fieldValue as IUndoable;

if( uf != null )
{
uf.CreateSnapshot();
}
else
{
fieldName = currentType.Name + "." + field.Name;
state.Add (fieldName, fieldValue);
}

}
}

currentType = currentType.BaseType;

}while( currentType != typeof(BusinessObject) );

// Now, use serialization to save the state in the
// statestack
MemoryStream buffer = new MemoryStream ();
BinaryFormatter fmt = new BinaryFormatter ();
fmt.Serialize (buffer, state);
_stateStack.Push (buffer.ToArray ());

}
#endregion


If you have a look at the code above, and compare it with the CSLA.NET code, you'll notice the slight difference.
The implementation of RevertToPreviousState and CommitSnapshot is also almost identical to the UndoChanges and AcceptChanges methods of the UndoableBase class of the CSLA.NET framework. Just as in the CreateSnapshot method, the only change I've made, is checking for the IUndoable interface.
The RevertToPreviousState and CommitSnapshot pop the last saved state from the stack. CommitSnapshot just throws it away, and calls CommitSnapshot for every member of the class that is an IUndoable type, while ReverToPreviousState uses the last saved state to reset the value of all class-members to their previous state.

The [NotUndoable] attribute is a custom attribute that defines that a field that is decorated with this attribute should not be 'undoable'.
The IsUndoableField method is a private member method of BusinessObject. This method just checks whether or not the given field is decorated with the NotUndoable Attribute.

IEditableObject implementation


The IEditableObject implementation makes use of the IUndoable functionality.
For databinding purposes, it must be possible that the state of an object is saved when a user changes something to the object. This is necessary because the object must be reset in it's original state when the user decides to cancel the changes he has made.

We also need a flag that indicates wether or not we have to save the current state.
This is necessary because, in a databinding scenario, the BeginEdit method is called on every databound control in where you change the (databound) content.
Since it is not necessary to keep track of the changes on such a fine-grained level (we will want to keep track of the changes on a 'form level'), we control the 'state support' by this flag.
#region IEditableObject Implementation

[NotUndoable]
private bool _bindingEdit = false;

public void BeginEdit()
{
if( _bindingEdit == false )
{
this.CreateSnapshot ();
_bindingEdit = true;
}
}

public void CancelEdit()
{
if( _bindingEdit )
{
this.RevertToPreviousState ();
}
}

public void EndEdit()
{
if( _bindingEdit )
{
this.CommitSnapshot ();
}
}

#endregion


So, that's enough typing for today. If you have comments, feel free to post them here or to send me an email.
In the next article of this series, I'll discuss the base classes that are used for collections of BusinessObjects.

Since I have modified the CSLA.NET framework for learning purposes, the same licence applies to it as the licence that applies to the CSLA.NET framework.

donderdag 5 januari 2006

Airplanes....


airshow

If you like airplanes and airshows as much as I do, then, you should definitly check out this movie (39mb). It's an advertorial for some airshow, really nice movie.

maandag 2 januari 2006

C# 3.0 Orcas : playing with LINQ

I’ve been playing around with the technology preview of C# 3.0 today. The most important new feature of C# 3.0 is –without any doubt - LINQ.

LINQ enables you to search through collections in an SQL – like way.

For instance, instead of looping through a collection to find the Persons that live in the city that has the postal-code ‘9000’ like this:

List<person> persons = new List<person>();

persons.Add (new Person("Person1", "9000"));
persons.Add (new Person("Person2", "9870"));
persons.Add (new Person("Person3", "9000"));

foreach( Person p in persons )
{
if( p.PostalCode == "9000" )
{
Console.WriteLine (p.Name);
}
}


You will be able to get the same results, by writing the code like this:

List<person> persons = new List<person>();

persons.Add (new Person("Person1", "9000"));
persons.Add (new Person("Person2", "9870"));
persons.Add (new Person("Person3", "9000"));

var result = from p in persons
where p.PostalCode == "9000"
select p.Name;

foreach( string name in result )
{
Console.WriteLine (name);
}


You can imagine that, for complex queries, using LINQ can be an advantage since it keeps your code more readable / understandable.

In order to be able to deliver this functionality, Microsoft had to add some other features to the language:

Implicit types


C# 3.0 introduces the var keyword. If you take a look at the LINQ code example, you’ll see that I’ve used this keyword.

With this keyword, you don’t have to declare the type of the variable. So, when I first saw this, I thought ‘Oh no, is this the same like the ‘variant’ type in VB, and is C# going ‘the VB way’ ?
Luckely, Microsoft has defined some ‘rules’:

  • When declaring a ‘var’, you’ll have to initialize the variable
  • You cannot initialize the variable to null.

So, these restrictions save us from the ‘variant’, because, because of these rules, the type of the variable is specified by the initializer.

The var keyword can be handy in some situations. For instance, suppose you want a Dictionary object like this:
Dictionary<CustomerKey, Customer> custs = new Dictionary<CustomerKey, Customer> ();


You’ll be able to write it in a shorter way like this:
var custs = new Dictionary<CustomerKey, Customer> ();

Extension Methods


Extension methods allow you to ‘extend’ the functionality of a class without the need to change (and recompile) that class, and, without the need to create a subclass of that class (which is not possible if the class that you want to inherit from, is sealed.

Suppose you want to extent the Person class I’ve used in the previous example using an extension method, you’ll have to do it like this:

public static class PersonExtension
{
public static string GetPostalCodeAndName( this Person p )
{
return p.PostalCode + " " + p.Name;
}
}


An extension method is a static method with at least one argument: The first argument of the extension method must be a variable of the type that you want to extend, and, it must be preceded by the this keyword.

The extension method can then be used like this:
Person p = new Person("Person1", "9000");

Console.WriteLine (p.GetPostalCodeAndName());


Luckely, you’re not able to access the non-public members of the class in the extension method.

Anonymous types and Initializers


These 2 features are also added to the c# specification in order to make LINQ possible. However, apart from that, I do not see why I’m going to use these 2 features, so I’m not going to discuss them here.
You’ll find more information about these features (and about the other new C# 3.0 features) on the MSDN

DLINQ


DLINQ is a MS research project that makes use of the LINQ technology. It allows the developer to query a database using similar statements like the ones you use with LINQ instead of using embedded SQL or calling stored procedures.

I haven’t played with DLINQ (yet), but anyway, I’m a little bit sceptical on it.
From what I’ve seen, you have to specify mapping information in your ‘domain object’, so that messes things a little bit up.
I also wonder how this will behave with a complex domain model; in applications with a complex domain model, the domain model is not a one-to-one mapping of the database.
Anyway, it’s an experimental project, and we’ll see what the future brings.

If you want to experiment with LINQ, you can get the technology preview here

Update:The C# code that used generics was not shown properly.

Happy New Year!

I'd like to wish you all the best for 2006!