DDD - NWorkspace Linq experiment
July 3, 2008
In Jimmy Nilsson’s book ”Applying Domain Driven Design and Patterns” he writes about a project of his called “NWorkspace”, which is a kind of abstraction layer for O/R mappers.
The concept is to let your Repositories only talk to the workspace abstraction, making it possible to swap underlying mapper.
The biggest problem with such abstraction is querying, there have never existed a standard way to make queries for domain models in .NET.
So you end up abstracting the querying mechanism too, and that in turn forces you to create translators from your own query model to the underlying mappers query model.
Now days we have Linq.
Linq allows us to create queries in a standardized way against domain models.
So, yesterday I decided to try to make a Linq based abstraction layer in the spirit of NWorkspace.
(Note: My project is simply a ripoff from Jimmy’s concept, there is no relation to the real NWorkspace)
First I had to pick some different persistance tools, so I decided to go with NHibernate, LinqToSql and DB4O (object DB for .NET)
Once I had selected the persistence tools I started writing my abstraction layer.
It turned out to be really easy to implement, one interface with five methods:
LinqQuery[of T] //creates a Linq query
Add(T) //attaches a transient entity to the workspace
Delete(T) //removes a persistent entity from the workspace
Commit() //commits all changes to the persistent store
Rollback() //discards all changes
I then created an implementation for each of the persistence tools for my interface.
So now I can pass instances of my workspace into my repositories and make them operate almost agnostic of what persistence tool I use.
I say “almost” because there are a bit too many differences between the tools when it comes to query support and entity design.
LinqToSql is far from being POCO / PI, and even if NH and DB4O are both POCO’ish, there are still differences.
There are also differences in the Linq support, so you can not always run the same type of queries against the different workspace implementations.
But all in all, it turned out really nice, making the Repository design much cleaner.
As long as you adapt your domain model for whatever persistence tool you use and don’t use too complex queries, the most of your repositories and business logic can remain unchanged.
Pretty slick IMO.
//Roger
Vacation!
July 1, 2008
Today is the first day of my four week long vacation.
So I will finally get some time to get some work done on Caramel.
Well I’m off to get some sun and some beer ![]()
Caramel - Alpha source code is public
June 19, 2008
I have added the Caramel code generator to my public repository at google code.
http://code.google.com/p/alsing/
Please note that this is very very alpha and not actually useful yet.
Before it can be used I need to finish the template support and fully implement the DB meta data importer.
But if you are interested in this kind of stuff and want to help out building it, please let me know.

Book - Compiler principles… (The red dragon book)
June 19, 2008
Parsing and languages have always been one of my main interests when it comes to programming.
So a few weeks ago I decided to buy the “red dragon book” from Amazon.com.
http://www.amazon.com/Compilers-Principles-Techniques-Alfred-Aho/dp/0201100886
(note: For some reason I managed to buy the edition from 1986 instead of 2006)
It is definetly one of the most interesting books I’ve ever read.
Maybe the most interesting part is that It is very humbeling to see how bloody brilliant those old computer science language guys are.
My biggest problem at the moment is that I fall asleep every 3-4 pages.
It is not because of boredom or anything, it’s just that I have to pause and reflect on what I have read for each page and that’s when I fall asleep
So if you are into geeky stuff like domain specific languages and such, read the book, it’s awesome!
.NET Stateful delegates and memoization
June 4, 2008
I’ve been planning to write about stateful anonymous delegates for quite some time now so here I go
The common perception of anonymous delegates is that they are stateless functions used for filtering and transformations and similar things.
What is less known is that anonymous delegates can hold state by binding to local variables.
If you create an anonymous delegate inside a factory method, you can infact give the delegate it’s own state.
Example:
static Func<int> CreateCounter()
{
int i = 0; //bind delegate to a local mutable variable
return () => i++;
//"i" doesn't really go out of scope here
// because it is bound to our delegate
}
By using this method we can now create a stateful delegate:
var myCounter = CreateCounter(); Console.WriteLine( myCounter() ); //prints : 0 Console.WriteLine( myCounter() ); //prints : 1 Console.WriteLine( myCounter() ); //prints : 2
The above code will print 1, 2, 3 in the console window, simply because the delegate is increasing the value of the bound variable inside it’s body.
So where does anonymous delegates store it’s state?
The state is stored as fields inside a class that is auto generated by the C# compiler.
This class will contain the state for all bound variables / arguments that are used inside anonymous delegates defined inside the same method.
And when is this useful?
To be honest, almost never ![]()
But there are cases where it is actually quite nice.
Here is a sample that I came up with after reading Ayendes blog ( http://www.ayende.com/Blog/archive/2008/06/04/Review-Umbrella-project.aspx )
He wrote about “memoization” and I thought that would make a great example of stateful delegates.
We can create memoizations in C# by exploiting the fact that anonymous delegates bind to local variables.
Example:
static Func<T1, T2, TResult> CreateMemo
<T1, T2, TResult>(Func<T1, T2, TResult> source)
{
var cache = new Dictionary<string, TResult>();
return (arg1, arg2) =>
{
string key = string.Format("{0}|{1}", arg1, arg2);
if (!cache.ContainsKey(key))
{
var value = source(arg1, arg2);
Console.WriteLine
("Returning {0} and adding it to cache", value);
cache.Add(key, value);
return value;
}
else
{
var value = cache[key];
Console.WriteLine
(”Returning {0} from cache”, value);
return value;
}
};
}
This code will create a memoization for any delegate of the type Func<T1, T2, TResult>.
You simply pass a delegate to it, and you will get a memoized delegate back.
The code creates a dictionary that will act as our cache.
And then returns a new delegate that are bound to this dictionary.
The returned delegate will transform it’s arguments into a key and then check if the key is present in the cache.
If the key is present, it will return the cached value.
And if not, it will call the wrapped delegate and then store the result in the cache.
You can even pass normal methods as argument to the memoizer and get a delegate that acts as a cache around your method.
Well that’s it ![]()
Now go and abuse the mutable variable bindings in your delegates.
Enjoy.
//Roger
Argument validation framework released
May 28, 2008
Download:
http://www.puzzleframework.com/Roger/alsingcore.zip
I’ve finally got my thumb out and cleaned up and made a mini framework of the fluent argument validation concept I blogged about in my last post: http://rogeralsing.com/2008/05/10/followup-how-to-validate-a-methods-arguments/
The framework contains a little bit of everything.
Fluent Argument Validation Specification.
An extensible argument validation system based on a fluent extension method API.
(Maybe I should work at marketing
)
Async fork.
A fluent API for performing async operations.
Text parser.
A Deterministic Finite-State Automata based parser.
It is the same parser that we used in NPath for NPersist but with a cleaned up API.
Flextensions.
A handful of useful extension methods to increase expressiveness.
Loggers, casting, formatting etc.
Generic Math.
A generic numeric type that supports math operations.
Examples:
Validation pre conditions:
static string ValidationFunc(int a,string b,DateTime c)
{
//pre conditions:
a.Require("a")
.IsGreaterThan(10);
b.Require("b")
.NotNull()
.NotEmpty()
.LongerThan(2)
.StartsWith("Ro");
c.Require("c")
.IsInRange(new DateTime(2000, 01, 01),
new DateTime(2010, 01, 01));
Validation post conditions:
string res = "Foo";
//post condition:
return res.Require("res")
.NotNull()
.LongerThan(2)
.ShorterThan(100);
Async fork:
static int ForkIt()
{
int a = 0;
int b = 0;
//begin async fork
Fork.Begin()
.Call(() => a = SomeSlowCall())
.Call(() => b = SomeOtherSlowCall())
.End();
//async fork done
return a + b;
}
Flextensions:
//fluent casts, no need to wrap in ((int)var).
someVar.Cast<Foo>().Bar();
someVar.As<Boo>().Yoo();
//formatting and output;
myVar.FormatAs("myVar is: {0}").Output();
"Hello {0} {1}".FormatWith(firstName,LastName).Output();
"ROGER ALSING".ToProperCase().Output();
//string matching
bool match = myString.Like("Roger%");
bool match = myString.Match(regexPattern);
More examples can be found in the demo project and in the unit tests in the same zip as the framework.
Enjoy.
//Roger
Download:
http://www.puzzleframework.com/Roger/alsingcore.zip
Followup: How to validate a method’s arguments?
May 10, 2008
A few days ago I and Fredrik Normén had a discussion about argument validation here: http://weblogs.asp.net/fredriknormen/archive/2008/05/08/how-to-validate-a-method-s-arguments.aspx
The discussion got kind of stuck in my head, so I have been thinking a bit more about it.
And today I came up with a solution that I think is both clean and easy to extend.
Fluent Argument Validation Specification
The idea is to transform the value of the argument that should be validated into an object which contains both value and argument name, so that this object can be passed around to different fluent validation methods.
By doing this, we can now add new extension methods for the generic argument class in order to extend our fluent validation API.
A fulent API will let us read and write the requirements just like a specification for each argument.
Here is an example of the consumer:
public static void MyMethod(string someArg,int someOtherArg)
{
someArg.RequireArgument("someArg")
.NotNull()
.ShorterThan(10)
.StartsWith("Roger");
someOtherArg.RequireArgument("someOtherArg")
.InRange(10,100)
.NotEqual(33)
.NotEqual(51)
//do stuff
}
As you can see, we only have to specify the argument name in the require method.
The require method will return an instance of “Validation<T>” which is our generic argument class.
The argument class have no own instance methods, instead we have extension methods which are fluent so that we can call them in a chain.
These extension methods can operate directly on “Validation<T>”,with or without generic constraints.
We can also add extension methods for specific types, like: “Validation<string>”, and thus allow us to validate strings in different ways than other types.
But enough talking, here is the required code to accomplish this:
The implementation of the Validation<T> class:
public class Validation<T>
{
public T Value { get; set; }
public string ArgName { get; set; }
public Validation(T value, string argName)
{
Value = value;
ArgName = argName;
}
}
The implementation of the Require method:
public static class Extensions
{
public static Validation<T> RequireArgument<T>(this T item, string argName)
{
return new Validation<T>(item, argName);
}
}
And the implementation of the different validation methods:
public static class ValidationExtender
{
[DebuggerHidden]
public static Validation<T> NotNull<T>
(this Validation<T> item) where T : class
{
if (item.Value == null)
throw new ArgumentNullException(item.ArgName);
return item;
}
[DebuggerHidden]
public static Validation<string> ShorterThan
(this Validation<string> item, int limit)
{
if (item.Value.Length >= limit)
throw new ArgumentException(
string.Format(”Parameter {0} must be shorter than {1} chars”,
item.ArgName,limit)
);
return item;
}
[DebuggerHidden]
public static Validation<string> StartsWith
(this Validation<string> item, string pattern)
{
if (!item.Value.StartsWith(pattern))
throw new ArgumentException(
string.Format (”Parameter {0} must start with {1}”,item.ArgName, pattern)
);
return item;
}
//other validation methos
…..
}
The [DebuggerHidden] attribute is optional, but it will make your stacktrace look better since it will break in the method that performs the Require call, and not inside the validation methods.
So by using the debugger hidden attribute we can get the behaviour as seen on this screenshot:

Enjoy
//Roger
Optimizing SOA Applications - C# Async Fork
May 9, 2008
I’m currently developing a site where my domain model is filled with data from both a database and allot of service calls; normal web services and quite a bit of main frame calls.
So I’m accessing data from multiple remote sources, and each call to such source will cost me a bit of time.
If I call them in a synchronous manner, then the time to call each source will be accumulative.
Lets say that I make four remote calls per page request and that each call takes about 0.25 sec, then we would spend a total of 1 sec just waiting for responses.
But if I we spawn a thread per call and then call those services at the same time, we would only have to wait a total of 0.25 sec, thats four times faster than the synchronous way.
The problem is just that .NET does not support any small and clean way to do this (AFAIK)
We can of course use async callbacks and such, but you will have to design your code a certain way to do this and the code will be both bloated and harder to read.
I just want to be able to design my code just as I would when I build a synchronous flow.
So I came up with a small fluent fork API for this.
The API is based on three methods, Begin , Call and End:
- Begin will spawn a new async fork
- Call will add the action we want to perform onto a queue
- End will execute the queue of actions and then wait for all of them to finish.
When the fork is finished, we can be sure that all the calls have completed and we can safely access any variable that was assigned within the fork calls.
Example:
//declare the variables we want to assign
string str = null;
int val = 0;
//start a new async fork
//assign the variables inside the fork
Fork.Begin()
.Call(() => str = CallSomeWebService (123,"abc") )
.Call(() => val = ExecSomeStoredProc ("hello") )
.End();
//the fork has finished
//we can use the variables now
Console.WriteLine("{0} {1}", str, val);
We can write the code just like normal, we do not have to redirect our flow to any async callbacks or deal with IAsyncResults or stuff like that.
If you know any easier way to do this, please let me know.
As for now, this is the way I do my async variable assignments.
You can find the C# code for the fork class here:
http://www.puzzleframework.com/Roger/fork.txt
Enjoy
//Roger

