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

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

I’ve been working some more on the UML editor for Caramel.
I’ve added comment elements and relations to the editor now:

 

Caramel - Screenshots

April 20, 2008

I’ve been working on the class designer this weekend and made some nice progress.
It is now possible to add interfaces and enums to the designer surface.
(and alter their members ofc)

The next thing I have to dig into is to add support for association and inheritance lines.

//Roger

I do a fair amount of GDI+ programming, and thus using a lot of IDisposable objects.
But I also use template or factory methods alot in my apps, and that doesnt work well with disposable objects

Imagine something like this:

public abstract class MyRendererBase
{
      public void Render(Graphics g)
      {
            //use templated objects
            Brush bgBrush = GetBackgroundBrush();
            Brush fgBrush = GetForegroundBrush();
           
            g.FillRectangle(bgBrush ....);
            g.FillRectangle(fgBrush ....);
      }
      //templated methods
      public abstract Brush GetBackgroundBrush();
      public abstract Brush GetForegroundBrush();
}

What could go wrong here?
Well, lets say that you implement the class like this:

public class SomeRenderer : MyRendererBase
{
      public override Brush GetBackgroundBrush()
      {
            return SystemBrushes.Control; //return existing
      }
      public override Brush GetForegroundBrush()
      {
            return new SolidBrush(Colors.Blue); //return new
      }
}

In this case, the GetForegroundBrush method creates a new custom brush for each call and that brush should be disposed once we are finished with it.
While the GetBackgroundBrush method returns an existing brush that should NOT be disposed, it could be a system brush or just a brush that you defined in a static settings class or something similair.

How should the consumer of the templated methods know if it should or should not dispose the objects in this case?
Normally when you use disposable objects you create them directly in the consumer code and you can easily decide if you need to dispose or not.
But if we do so, we would lose the benefits of template/factory methods, that is: beeing able to substitute values/objects in a larger algorithm/flow.

So my solution to this problem is to make  wrapper class that will hold a ref to the disposable object, and you can tell the wrapper if it should dispose the resource or not:

public class Disposer<T> : IDisposable where T : IDisposable
{
    public T Value { get; set; }
    public bool ShouldDispose { get; set; }
    public Disposer(T value,bool shouldDispose)
    {
        Value = value;
        ShouldDispose = shouldDispose;
    }
    ~Disposer()
    {
        Dispose(false);
    }
    protected virtual void Dispose(bool disposing)
    {
        if (disposing)
        {
            lock (this)
            {
                Value.Dispose();
            }
        }
    }
    public void Dispose()
    {
        if (ShouldDispose)
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }           
    }
}

Once we have this class, we can alter our sample code to:

public abstract class MyRendererBase
{
      public void Render(Graphics g)
      {
           using (var bgBrush = GetBackgroundBrush())
            {
               g.FillRectangle(bgBrush.Value ....);
            }
           using (var fgBrush = GetForegroundBrush())
            {
               g.FillRectangle(bgBrush.Value ....);
            }
      }
      //templated methods
      public abstract Disposer<Brush> GetBackgroundBrush();
      public abstract Disposer<Brush> GetForegroundBrush();
}

And the implementation to:

public class SomeRenderer : MyRendererBase
{
      public override Disposer<Brush> GetBackgroundBrush()
      {
            //return a wrapper that does not dispose the content
            return new Disposer<Brush> (SystemBrushes.Control, false);
      }
      public override Disposer<Brush> GetForegroundBrush()
      {
            //return a wrapper that dispose the content
            return new Disposer<Brush>(new SolidBrush(Colors.Blue),true);
      }
}

And that’s it.
The wrapper objects will always be disposed by the consumer, but the template methods can now tell if the content of the wrapper objects should or should not be disposed together with the wrapper.

Note:
The above sample is very naive, in this case we could just as well have created our solid blue brush somehwere else and used w/o disposing in the consumer code.
But there are cases where you actually have to create new objects in the template methods for each call.
Eg. when using GradientBrushes that need to start their gradients at a specific point. (based on some state somewhere)

Enjoy.
//Roger

Caramel - Screenshots

April 14, 2008

For those who havent read my earlier posts:

Caramel is a hybrid between old school code generators and Entity Mapping tool.
You can also plug in your own node types in the meta tree, and thus allowing you to generate pretty much whatever you want.

My intention is to release it with built in support for the most common O/R Mappers so you can build your domain models for NHibernate, NPersist etc in Caramel.

And I might also add some simplistic web page support so you can generate edit/list pages for the mapped entities.

Anyway, here are some new screenshots.

Summary:

Template Editor:

Class Designer:

//Roger

It’s a girl

April 13, 2008

Yesterday at 17:45 me and my wife arrived at the hospital here in Örebro, and 27 minutes later our daughter was born :-)

Well I’ve got some sleep to catch up now :-)

 

As some of you might know, I’ve been working on a class designer (Albino horse) off and on for a while now.

I’ve also started to work on a code generator where the class designer will be used.
The code generator will be a sort of hybrid between old school DB code generator and Puzzle ObjectMapper.

You will be able to edit domain models and table models just like ObjectMapper, but you can also add your own kind of nodes, making it possible to extend the generator for pretty much whatever you want.
Eg. you could add nodes for different types of web pages and map entities to those and genereate entire apps.

Enough talking, a picture says more than , all the blabbering above :-)

Very very alpha’ish screenshot of the generator:

 

Once I’ve added a bit more functionallity and cleaned it up a bit I will publish it on codeplex.

Patrik Löwendahl blogged about using C#3 features in .NET 2 via VS.NET 2008 a few days ago:
http://www.lowendahl.net/showShout.aspx?id=191

There are quite a few of the new features that works straight out of the box.
However, Linq does not, alot of the code that Linq uses is simply not present in the .NET 2 BCL.

So, inspired by Patriks post I opened up an old custom Linq engine that I wrote a while back and spiced it up and adapted it for .NET 2.
I also added a few of the standard list extensions such as “Take” “Skip” etc.

The code can be found here:
www.puzzleframework.com/Roger/LinqForNet2.zip

And before you get all excited, this is only Linq to objects, NOT Linq to SQL….

The code supports the following Linq constructs, features and list extensions:

  • from (ok ok, I didn’t have to code anything for that)
  • where
  • join
  • groupby
  • orderby
  • select
  • Take
  • Skip
  • TakeWhile
  • SkipWhile
  • Distinct
  • Deferred execution

Enjoy : - )

 //Roger

I’ve been digging through the ObjectDataSource today and I was trying to figure out how they created the datasource instance from the type name.

Now some clever reader might say “I know, I know, Type.GetType(string)”… But that’s wrong..
Type.GetType(string) requires full type names with assembly name and the whole shebang.

The ObjectDataSource is able to create instances w/o all that information.
So after a while of digging I found a precious gem, hidden in System.Configuration:
“BuildManager.GetType(string)”

Very very nice :-)

I can now inherit ObjectDataSource and fetch the type via buildmanager and then call NAspect to proxy the type and get an AOP enabled datasource.

Thats all for now, just wanted to share this one :-)