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.

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
Linq Expressions - Creating objects
February 28, 2008
This post shows how you can use Linq expression trees to replace Activator.CreateInstance.
but first, please note that this is a followup on Oren’s post so read it before you read mine:
http://www.ayende.com/Blog/archive/2008/02/27/Creating-objects–Perf-implications.aspx
In C#3 we can use Linq expression trees to solve this problem to.
I’m not saying that it is a better or faster solution than Oren’s IL emit version.
The IL emit is completely optimized for what it is supposed to do, so its hard to beat.
This is just an alternative if you are a bit affraid of IL emit ;-), Linq expressions are just easier to understand for most people.
So how is it done?
First we need a delegate declaration:
delegate T ObjectActivator<T>(params object[] args);
We will use this delegate in order to create our instances.
We also need a generator that can compile our delegates from expression trees:
public static ObjectActivator<T> GetActivator<T>
(ConstructorInfo ctor)
{
Type type = ctor.DeclaringType;
ParameterInfo[] paramsInfo = ctor.GetParameters();
//create a single param of type object[]
ParameterExpression param =
Expression.Parameter(typeof(object[]), “args”);
Expression[] argsExp =
new Expression[paramsInfo.Length];
//pick each arg from the params array
//and create a typed expression of them
for (int i = 0; i < paramsInfo.Length; i++)
{
Expression index = Expression.Constant(i);
Type paramType = paramsInfo[i].ParameterType;
Expression paramAccessorExp =
Expression.ArrayIndex(param, index);
Expression paramCastExp =
Expression.Convert (paramAccessorExp, paramType);
argsExp[i] = paramCastExp;
}
//make a NewExpression that calls the
//ctor with the args we just created
NewExpression newExp = Expression.New(ctor,argsExp);
//create a lambda with the New
//Expression as body and our param object[] as arg
LambdaExpression lambda =
Expression.Lambda(typeof(ObjectActivator<T>), newExp, param);
//compile it
ObjectActivator<T> compiled = (ObjectActivator<T>)lambda.Compile();
return compiled;
}
It’s a bit bloated but keep in mind that this version is completely dynamic and you can pass any constructor with any arguments to it.
Once we have the generator and the delegate in place, we can start creating instances with it:
ConstructorInfo ctor = typeof(Created).GetConstructors().First(); ObjectActivator<Created> createdActivator = GetActivator<Created>(ctor); ... //create an instance: Created instance = createdActivator (123, "Roger");
And that’s it.
I haven’t done any benchmarking to compare it to Oren’s IL emit version, but I would guess that it is almost but not quite as fast.
Benchmark - Creating 1000 000 instances:
Activator.CreateInstance: 8.74 sec Linq Expressions: 0.104 sec
My benchmarks is w/o the .ToString() stuff that is included in Oren’s post.. so don’t compare my numbers to his.. it’s done on a different machine too.
//Roger
More Linq support for NPersist
February 20, 2008
I’ve added a bit more Linq support for NPersist today.
The nice thing is that we can “cheat” in our Linq provider, we can transform our Linq queries into NPath queries.
Thus, I don’t have to touch the wicked SQL generation.
I just have to produce valid NPath, which is pretty similair to Linq.
Just look at the following code:
private string ConvertAnyExpression(MethodCallExpression expression)
{
string fromWhere = ConvertExpression(expression.Arguments[0]);
if (expression.Arguments.Count == 1)
return string.Format(”(select count(*) from {0}) > 0″, fromWhere);
else
{
LambdaExpression lambda = expression.Arguments[1] as LambdaExpression;
string anyCond = ConvertExpression(lambda.Body);
return string.Format(”(select count(*) from {0} and {1}) > 0″, fromWhere,anyCond);
}
}
Thats all the code that we needed in order to support “list.Any()” and “list.Any(x => ….)”
This both makes the Linq provider easier to build, and it makes it way easier to unit test it too.
We simply have to compare the result with an expected NPath string.
Like this:
string expected = "select * from Customer where ((Customer != ?))"; string actual = res.Query.ToNPath(); Assert.AreEqual<string>(expected, actual);
So I think we have most of the standard query elements in place now.
I just have to add support for a few more things inside NPath, things like “skip”, “is” etc.
Added “Documents” page.
February 18, 2008
I’ve added a “Documents” page here on the blog.
This page will contain links to documents/papers regarding my projects and related material.
MyLisp Editor
February 8, 2008
I’ve started to make a very simple editor for MyLisp, just so I can get some highlighting and testrun my snippets.
Here is the exclusive world first screenshot
Well, thats about it, source and binaries will be out once it’s more complete.
(The SyntaxHighlight editor component is available for download at www.puzzleframework.com )
Lazy evaluation
February 3, 2008
My Lisp now supports Lazy evaluation.
I’ve made it possible to define per function if it should use lazy or eager evaluation.
(The next step will be to decide that through code analysis.)
For those who don’t know what lazy evaluation is about, the purpose of lazy evaluation is to avoiding unnecessary calculations.
Take the following example (in C#)
public static void FooBar ()
{
int res = GetSomeValue();
//pass the value to a logger
Logger.Log ("value of GetSomeValue was:" , res);
}
public static int GetSomeValue()
{
//some realy heavy algorithm here
... heavy code ...
... more heavy code ...
return res;
}
... logger code ...
public void Log (string message,params object[] args)
{
//lets assume we can attach multiple providers to our logger
foreach (LogProvider provider in LogProviders)
{
provider.WriteString(message,args);
}
}
In this case, we would always need to execute “GetSomeValue” first in order to call our logger.
EVEN if there is no provider attached to the logger.
So, even if we don’t want to write anything to disc or DB or anywhere, we would still have to call “GetSomeValue”.
It is ofcourse possible to add special code to your consumer , “if (logger.Providers.Count == 0) then ignore…”.
But that forces you to add responsibility to your code that isn’t supposed to be there.
My FooBar method should not have to care about the number of log providers etc.
Lazy evaluation can solve this for us.
By applying Lazy evaluation to ”GetSomeValue” method, we would only need to call the method once the result of it is used.
Sounds odd?
How can you use the result before the code have executed?
It’s quite simple, its done through delegates, we can even do this in C# by passing delegates around.
However, you do have to know that you are passing delegates and not simple values, so it is not very implicit in C#.
In My Lisp, the code would look something like this:
(func FooBar ()
(
(= res (GetSomeValue))
(call logger log "value of GetSomeValue was:" res)))
(lazy-func GetSomeValue ()
(
... heavy code ...
... more heavy code ...
(return res)))
...logger...
(func Log (message data)
(
(foreach provider Providers
;;; GetSomeValue will be called here
(call provider WriteString message data))))
As you see, there is no special code to handle the lazy evaluation.
The only thing that I need to do was define “GetSomeValue” as a lazy function.
So if we do not have any log providers attached to our logger, “GetSomeValue” will never be executed, since its result is never needed.
And if there are providers attached, “GetSomeValue” will be executed from within the foreach loop inside the logger.
(Once, then caching its value)
Pretty slick IMO.
Updated personal info
February 2, 2008
Added an “About me” AKA. “meet the geek” page on this blog.
Hello World
January 8, 2008
Console.WriteLine (”Hello World”);
