Ayende on Castle ActiveRecord

I don’t usually do that, but here’s Ayende‘ presentation from last year’s Oredev conference (yes, it says 2007, but it really is from 2008).

It’s fun, very informative if you don’t know Active Record, and of surprisingly good quality (means you can actually hear what Ayende is saying, and see the code). Most of all, this is an awesome presentation.

How many times have you gone to a presentation when presenter said “Give me a domain model that you want to work on” and then went and implemented it!

It’s a must see. Highly recommended. And if you register to viddler, you can download the video in slightly better quality and resolution here.

Meffing with Castle Windsor

Patrik Hägne has an interesting post on removing compile time dependencies between assemblies, while still reaping benefits of using fluent interfaces to bootstrap AutoFac container (go read it, I’m not going to reiterate what Patrick wrote) using MEF.

It inspired me to do similar thing for Castle Winsor.

meffing_with_castle_project

I created a simple solution with 3 project. One is the main application entry, which also holds a MefInstaller which we’ll talk about in a second. Second one: Services, contains interfaces that our application rely on. Impl contains implementation of these interfaces. Pretty simple huh?

The important thing is the tree of dependencies:

meffing_with_castle_dependencies

Notice that there’s no hard dependency on Impl module.

IBar and IFoo along with their implementation are pretty trivial and not really worth showing. Two interesting classes are MefInstaller and ModuleInstaller.

public class MefInstaller : IWindsorInstaller
{
    public void Install(IWindsorContainer container, IConfigurationStore store)
    {
        // NOTE: directory could come from configuration, or any other place
        var directory = Environment.CurrentDirectory;
        
        var compositionContainer = new CompositionContainer(new DirectoryCatalog(directory));
        var installers = compositionContainer.GetExportedObjects<IWindsorInstaller>("ComponentInstaller");
        
        foreach(var installer in installers)
            installer.Install(container, store);
    }
}

Castle Windsor exposes a IWindsorInstaller interface that you can use to batch register whole subsystems or modules with the container. In this case MefInstaller acts as a dynamic composite, which using MEF gathers all IWindsorInstallers that export themselves as “ComponentInstaller” (it’s just a convention I came up with here, this is not mandatory, and doesn’t have any deeper meaning), and then installs them with the container.

[Export("ComponentInstaller")]
public class ModuleInstaller:IWindsorInstaller
{
    public void Install(IWindsorContainer container, IConfigurationStore store)
    {
        container.AddComponent<IFoo, DefaultFoo>("foo");
        container.AddComponent<IBar, BarImpl>("bar");
    }
}

ModuleInstaller is just one such installer, which registers services implemented in its module.

Now the actual bootstrapping is really simple:

class Program
{
    static void Main(string[] args)
    {
        var container = BootstrapContainer();
        var app = container.Resolve<MyApp>("app");
        app.Run();
        Console.ReadKey(true);
    }
 
    private static IWindsorContainer BootstrapContainer()
    {
        var container = new WindsorContainer();
        container.Install(new MefInstaller());
        container.AddComponent<MyApp>("app");
        return container;
    }
}

BootstrapContainer runs the MefInstaller, and registers MyApp class, which is the main class in our application. Then the class is requested from the container, and a method is invoked on its instance.

The class itself is trivial. What is interesting, is that it has dependencies on two services we defined: IFoo and IBar. Just for kicks, I defined one as constructor dependency, and one as property dependency.

public class MyApp
{
    private readonly IFoo _foo;
 
    public IBar Bar { get; set; }
 
    public MyApp(IFoo foo)
    {
        _foo = foo;
    }
 
    public void Run()
    {
        Console.WriteLine("My Foo: {0}", _foo.Foo());
        Console.WriteLine("My Bar: {0}", Bar.Bar());
    }
}

Now, when we compile the application, and copy MeffingWithCode.Impl.dll to the output directory, because it’s not statically linked to the other assemblies, and run it, we’ll see that MEF does indeed pick up our missing dependencies, so that we don’t get NullReferenceException.

With this we get best of both worlds: We get flexibility of XML configuration (without being prone to typing mistakes), and strongly typed, refactoring friendly registration (without static linking between assemblies).

meffing_with_castle_app

Technorati Tags: , ,

Comparing execution speed of .NET dynamic proxy frameworks

A recent comment on Twitter from Tim Barcz started me thinking about alternative proxy frameworks (alternative to Castle Dynamic Proxy that is). Recently LinFu Dynamic Proxy started gaining some popularity, after it was included as one of standard bytecode providers in NHibernate.

Disclaimer:

To make things clear. I’m a long time user of Castle Dynamic proxy and I may be biased towards it. I also happen to know how to use it, contrary to all the other frameworks, that’s why the following test may not be realizing their full potential. If you spot a non-optimal use of any of the frameworks in the following test, let me know and I’ll update it.

Having said that, I put together a small sample test project, where I generate a one-interceptor proxy for a simple interface with each framework and call a method on this proxy 100,000 times.

The interface is as simple as it can be:

public interface IMyInterface1
{
    string Method1(int i);
}

Each interceptor looks roughly the same, and it only sets a return value for the method:

internal class SpringInterceptor : AopAlliance.Intercept.IMethodInterceptor
{
    public object Invoke(AopAlliance.Intercept.IMethodInvocation invocation)
    {
        //Debug.WriteLine("Hey, I intercepted the call! - Spring");
        return 5.ToString();
    }
}

I tested four frameworks. Castle Dynamic Proxy 2.1 RC1, LinFu Dynamic Proxy 1.01, Spring.NET 1.2, which is a big framework in itself, but it has some pretty powerful proxying capabilities, and Microsoft Unity 1.2 which has now some proxying capabilities as well.

Here’s the result of the test on my 4 year old, 2GHz one-core PC:

proxy_frameworks_1

The first pass was a warm up, to let the jitter kick in, so the really important stuff, is the second pass.

Castle Dynamic Proxy was the fastest one, which is not really a surprise for me. It’s designed to be fast and lightweight, and also has some pretty powerful capabilities that allow you to customize the proxy type being created so that you don’t waste cycles intercepting methods you don’t want to intercept, or calling interceptors you don’t need called for a particular method. (for an in-depth overview of Castle Dynamic Proxy see my tutorial series).

The second one was Spring.NET which took over 3 times longer. This is however still pretty fast, and considering that it’s a pretty extensible and configurable framework as well, I’m sure in real life scenario you can squeeze very good performance out of it.

Third one, Unity was an order of magnitude slower than Castle. This is not a surprise considering how bloated and over engineered it is. To be fair however, this may as well be due to strong tie between Unity IoC container and proxy framework. The proxy framework does not seem to be operable outside of the container, so the performance hit, may be partially due to some container overhead.

LinFu was two orders of magnitude slower than Castle. This was really surprising. Or at least until I noticed that it gathers a call stack for each and every invocation, and as I mentioned, this can (as clearly visible) be a performance overkill. I looked for a way to turn it off, but it seems there isn’t any. Also the only way of calling the intercepted method is via MethodInfo.Invoke, which is also a lot slower than direct invocation (or invocation via a delegate).

Note that this is an isolated case of a single performance test. I thought it’s the most important one, but it’s just my opinion. I also didn’t talk about capabilities, which should be your major concern when selecting a framework. – Can it support my scenario is the ultimate test. Frankly, the fastest two, are also the most mature and powerful.

You can check the complete code here.

UPDATE:

Here’s a screenshot from a profiler showing the LinFu’s proxy call tree. As you can clearly see, the major performance hit (over 90% of the time!) is in StackTrace constructor. It also obtains a MethodInfo dynamically instead of caching it, like other frameworks do, which is an expensive operation as well.

LinFu

UPDATE 2:

LinFu has been updated and it no longer collects stack trace information: I re-ran the test and you can see the results here.

 

WPF memory leak with VisualBrush TileMode="Tile"

Recently at work, while working on WPF GUI for our application we noticed, that our app leaks memory. After some time (actually a lot of time, since we first though that it was video codec’s fault) we nailed it, and unfortunately, it looks like it’s a bug in the WPF itself. I attach a sample application that exposes the issue.

leaking_app

What it does is basically… blinking a rectangle. The key thing is, how the rectangle is declared:

        <Rectangle Name="ResultsBorder" Height="100" Width="100" Opacity="0.0">
            <Rectangle.Fill>
                <DrawingBrush TileMode="Tile" Stretch="None" Viewport="0,0,1,4" ViewportUnits="Absolute">
                    <DrawingBrush.Drawing>
                        <DrawingGroup>
                            <GeometryDrawing Brush="#C0FFFFFF">
                                <GeometryDrawing.Geometry>
                                    <RectangleGeometry Rect="0,0,1,2"/>
                                </GeometryDrawing.Geometry>
                            </GeometryDrawing>
                            <GeometryDrawing Brush="#90FFFFFF">
                                <GeometryDrawing.Geometry>
                                    <RectangleGeometry Rect="0,2,1,2"/>
                                </GeometryDrawing.Geometry>
                            </GeometryDrawing>
                        </DrawingGroup>
                    </DrawingBrush.Drawing>
                </DrawingBrush>
            </Rectangle.Fill>
        </Rectangle>

The critical part that causes the leak (and ultimately OutOfMemoryException) is using DrawingBrush  with TileMode set to Tile. Changing this, makes the issue go away. It was tested on few computers, running Intel, AMD, and NVidia GPUs. The issue exists on Windows XP, as well as on Windows 7.

There is a Connect entry for that issue, but so far it is unresolved.

The workaround for now, is to not use DrawingBrush, which is what we did.

If you want to check the issue for yourself here’s the code.

Technorati Tags:

Mommy, there be dragons in my code.

Every developer, and every shop has a Acme.Commons, or Acme.Core library, where they keep useful helper classes and extensions used in almost every project. Ayende has his Rhino Commons that I’ve seen him blogging about a few times but I never quite got around to actually take a look at the code…

…until today, and I’m shocked. In a mostly positive way. There are few good ideas there, that I would like to discuss.

The first class I found astonishing was HackExpiredException. My first reaction looked something like this:

Then I looked for some code that throws this exception and found this class:

/// <summary>
/// Helper class that allow to specify temporary hacks in a 
/// simple fashion
/// </summary>
/// <example>
/// <code>
/// TimeBombHack.Until(new DateTime(2007,12,31), "Ignoring security for the client demo");
/// </code>
/// </example>
public static class TimeBombHack
{
    /// <summary>
    /// Will throw with the specified message after the 
    /// <param name="expiredAt">The expiry date</param>
    /// <param name="message">The message.</param>
    /// </summary>
    public static void Until(DateTime expiredAt, string message)    
    {
        if (DateTime.Today > expiredAt)
            throw new HackExpiredException(
                string.Format(
                    "The hack ({0}) expired on ({1}). You really should fix it already",
                    message,
                    expiredAt));
    }
}

I really like the idea of being able to mark some parts of code as TODO and have it blown into your face in a controlled fashion when you forget about it. Too many times a forgotten quick and dirty hack slips under the radar and get left behind, forgotten waiting to blow up in production or during very important presentation.

Another, very neat idea I found in the library is the ThereBeDragonsAttribute class.

This marker attribute decorate dangerous parts of the code where for some reason the developer decided to do something in a way that is not straight-forward. This usually means that this is using some functionality that is not fully supported.

Using wacky, unsupported or hackish code is something everyone does occasionally. I usually comment this piece of code, be it a method or a class, but comments are often not enough. With little help of NDepend to bring these pieces of code to everyone’s attention this may be a very useful warning sign for everyone on the team to handle this code with special care.

There are many other useful classes in Rhino Commons, but most of them are pretty standard stuff (maybe with the exception of property indexers).

What other non-standard, helpful little (or not so little) classes do you use in your code?

Working effectively with Reflection.Emit

I’ve been working a little bit with dynamic code generation at runtime (classes in Reflection.Emit namespace, collectively referred to as Reflection.Emit). It’s a low level API, that requires you to work with IL operations, keep track of what is on the stack, and requires quite a bit of knowledge about IL and CLR.

I’m no expert in IL, as probably most of developers, but there are ways to make this things easier.

To work my way through generating code, I use iterative approach.

  1. Write a class/method in C# that exactly (or as closely as possible) reassembles a single small part of what I want my dynamic method to look like. If my dynamic method is a static method – I write a static method. If it has a value type parameter, I write a method with value type parameter. I think you get the picture. The important thing is to really get as close to what you want to achieve with dynamic method as possible, and understand influence of those parts you can’t get exactly the same (for example because of C# limitations).
  2. I compile the class (also notice differences between mode you compile in – you usually want Release version, not Debug), and open it up in Reflector to see its IL.
  3. I write my code that does code generation, to generate IL identical to the one of my statically wrote method (taking into account all the variability).
  4. I save generated assembly, open it up in Reflector, and compare the IL, to the one created earlier, to see if they match. I often switch in Reflector to C# view, to better see some kinds of errors (passing wrong parameters, or calling method on wrong object). If you can’t save your generated code to physical assembly you can’t use this debugger visualizer to see its IL.
  5. Write and run tests.
  6. If everything works, go back to step one, add another part of code and repeat until you have all you wanted.

Here’s an example of this approach. It’s an actual code I wrote while working on DynamicProxy feature. The thing that is different here, is that Castle has an additional layer of abstraction on top of Reflection.Emit so I was not working directly with IL. This makes things a little bit easier, because you’re operating on a higher level of abstraction. On the other hand however, you don’t get that tight control over what gets generated, and you have a new API to learn.

Anyway, I actually already had a pretty good idea of what I wanted to do (I only needed to change the way things worked, by calling other constructor in my dynamic method, passing additional parameters). I wrote some tests to verify that my code works the way I wanted it to, and I implemented it. Unfortunately one test didn’t pass with the following error.

reflectionemiterror1 

One parameter I wanted to pass was an array, passed by reference, and it seemed that there was something wrong with it.

I opened Reflector and peeked into the generated method. Everything looked just fine when I switched to C# view.

 reflectionemitReflector

To investigate things further I saved IL of generated method to a file, and I did the same with IL of C# method I wrote as an example of what I wanted to accomplish. I then opened them both up in a diff tool to see where the difference was.

reflectionemitdiff

As it turns out, the code below (generated.txt) passes the loads the field value (ldfld) while it should load its address (ldflda). Knowing this it was trivial to fix my code.

On a side note, there’s also a Reflection.Emit Language plug-in for Reflector that may be useful to you if you’re working directly with Reflection.Emit classes. It shows you for any method you select the C# code that you’d write to generate that method with Reflection.Emit.

Technorati Tags: , ,

The most important part of .NET 4.0 – code contracts

There’s been about a year since .NET 3.0 along with C# 3.0 became RTM. Clearly the most publicized feature of the release was LINQ. Is it the most widely used feature? I’d doubt so.

Simply because scope of it’s usage is limited and people have yet to learn how to use it properly. Personally the things I’m using the most often are ‘var’ and a feature I’ve been really skeptical about – automatic properties. Now, few weeks after announcements of what is going to be present in the next wave of .NET, Visual Studio and the language, the dust has settled, and we’re past initial impressions. There’s been one (well actually more than one, but I’m just going to concentrate on the one in this post) announcement, that didn’t get quite as much attention as it, in my opinion, should have.

What I’m talking is – code contracts. The reason why I think they’re so important is not, that they finally give you the tool to explicitly state your assumptions and agreements regarding behavior of your methods in a written down, commonly understood way. The reason why I think it’s important is – because Microsoft can do it.

If you think about why they tend to lock things down in the framework, producing immense number if sealed internal non-virtual and otherwise not available classes and methods, it will become clear. They do it, because by not allowing you to override, or plug-in your code, they control the implicit contract between different interacting parties. And if they control it they can verify that their implicit contract does not get violated. They lock the things so that they control who and how can call the methods and how they should behave.

With Code Contracts however, there’s no more need for that. Contracts are there to state the assumptions explicitly. They can be verified, either at compile time, or at runtime (and with ReSharper, I guess, as-you-type) and they will ensure that the assumptions methods make about their callers, are met. With that hopefully, Microsoft will acknowledge that locking things down was a poor workaround for the real problem, and since they’ll have better solution now, we’ll see more open and extensible API in the framework.

Or maybe I’m only dreaming.

Multilingual .NET applications. Enter .NET localization

Creating multilingual applications is a huge topic. There are whole books devoted to it, and if you’re serious about it, you should definitely read those, because what you see on surface, is only the tip of an iceberg.

If you only want to play with localization or need a quick reference, hopefully this post will help.

Fist thing is, .NET is really well thought of if it comes to localization, so if you know what you’re doing, it’s pretty painless to create application that will be easy to translate to other languages (localization is a LOT bigger topic than showing labels in different languages, but I’ll leave this topic out.)

Second thing is, localization mechanism in .NET is greatly based on conventions, and it’s what we’ll focus here.

First obvious rule is, that each string, picture, video… generally speaking localizable resource must not be hardcoded.

If you don’t hardcode resources where do you keep them? In (surprise) Resources file. Generally you can use .resx files, or plain .txt, though the latter are useful only if you only keep strings.

resourceFile

Visual Studio has pretty good support for editing resources in .resx files, and later I’ll show you another tool that can do it as well.

To access the resources programmatically you need ResourceManager class. To instantiate it you need to give it the part to resources within an assembly, and the assembly itself. If it’s a little bit unclear, here’s the example:

resourcePath

If the Visual Studio project is named LocalizableApp, and the .resx file we want to use is in folder Properties, and the file itself is named Resources.resx, the whole base name for the resources is “LocalizableApp.Properties.Resources”.

That’s where the compiled .resx file (.resources) will be located within the assembly. You can see it, if you open the compiled assembly with Reflector.

resourceLocation

So to instantiate the ResourceManager you’d write code similar to the following:

var manager = new ResourceManager("LocalizableApp.Properties.Resources", typeof(Program).Assembly);

Each resource is identified by it’s unique name string. For example in the picture below, we have two resources with names, “greeting” and “howAreYou”

resourceEditor

You use these names to get the values of the resources. The resource manager does its magic, to provide you with resources best matching the CultureInfo you provided. If you don’t provide any Culture, current thread’s CurrentUICulture is used. So if you write:

Console.WriteLine("{0} {1}", manager.GetString("greeting"), manager.GetString("howAreYou"));

The CultureInfo object held in CurrentUICulture property of currently executing thread will be used. The default value for this property is the same as language version of Windows OS the program is executing on, which is reasonable. If your user uses Polish Windows she will probably want to interact with Polish version of your app as well.

You may not rely on this default though, and either override the Thread’s property, or specify the culture explicitly when calling methods on ResourceManager, like so:

culture = CultureInfo.GetCultureInfo("pl-PL");
Console.WriteLine("{0} {1}", manager.GetString("greeting", culture), 
    manager.GetString("howAreYou", culture));

Of course you wouldn’t hardcode the culture the way I did in the example, because it would defeat the purpose of using culture in the first place.

OK, so how to add another language?

You have the .resx file with the default, fallback resources, right? So now all you need is either send the file to a localization company, sit back and enjoy life, waiting for them to do the hard job, or do it yourself. To go with the latter option, you may want to use a tool to edit resource files, called Resourcer, by Lutz Roeder (Reflector, people!).

resourceResourcer

You can easily edit any kind of resources in it (not only strings). When you’re done translating your resources, save the file as .resources file, using following pattern: {baseResourceName}.{culture}.resources. For example if you were to translate our example app, to German language as spoken in Germany, you’d save your edited file with the following name: LocalizableApp.Properties.Resources.de-de.resources

It is important to obey this pattern, as by convention, this is what ResourceManager expects. If you fail to obey it, ResourceManager will not be able to pick your translated resources and will fall back to the default.

Having translated and properly named .resource file we need to make a satellite assembly out of it. To do it, you need Assembly Linker (al.exe) tool that is part of .NET SDK.

al

There are multiple properties you can set with al, the minimal version to get valid satellite assembly is shown on above screenshot. One thing that’s important to note, is the name of resulting satellite assembly. Again, by convention it has to be {NameOfBaseAssemblyWithoutExtension}.resources.dll, so if our application assembly was named LocalizableApp.exe, satellite assembly must be called LocalizableApp.resources.dll

Notice that the name of the assembly is the same for every culture. So how do we deal with that. Obviously we can’t have two files with the same name in one folder. The way it is handled, is through subfolders. Each satellite assembly is held in a folder which is named after the culture of the satellite assembly.

resourceFolders

For example if our LocalizableApp.exe is held in a folder, let’s say Debug like on the above screenshot, the de-de satellite assembly would be Debug\de-de\LocalizableApp.resources.dll and for instance pl assembly would be in Debug\pl\LocalizableApp.resources.dll.

I hope this is all clear by now. The greatest thing is, to add new language you don’t even need the actual base assembly. All you need is its resources and their location within the assembly.

Technorati Tags: , ,

My $0.02 on internal sealed API vs public virtual discussion

Accidently this post hit the wave of discussion on the blogosphere regarding Microsoft’s approach of keeping very big chunks of APIs internal, sealed, or otherwise unusable by users, and backward compatibility.

To some extent I can agree with both sides, because as always, the truth is in the middle, and I believe we’re talking about the solution (keeping things non-public and non-extensible) instead of the actual problem (the way API is designed, that makes a lot of useless parts public, and useful parts non-visible).

One ridiculous example I saw is the IlGenerator class.

  • It’s public
  • Most of it’s methods are virtual

But

  • All of it’s constructors are internal

So it’s OK for me to use this class, but I can’t subclass it? Sure it reaches into the guts of the framework, dancing with the devil himself, by manipulating IL stream, but this all looks to me like a carrot on the stick.

From the Good News Department, my colleague Monika started a blog today. She’s a WPF geek, so if you’re into this stuff as well, you should keep an eye on her blog.

Technorati Tags: ,

Unity framework and the Principle of the Least Surprise

I don’t like the Unity Inversion of Control framework. I find it too verbose, requiring user to be too explicit (except for cases where it doesn’t while it should), not intuitive and I generally don’t like its design. Unfortunately, it’s the only IoC framework I’m allowed to used at work, so I’m stuck with it, good or bad. There are times however that I’m just astonished by how it works, and mostly, in a negative sense. There’s an important principle in computer science, called Principle of the Least Surprise, that says, that framework (in particular) should have its API designed in such a way that it works like the user (programmer in this case) would expect it to.

Let’s take… well, I don’t know… Unity for example.

Take a look at the following piece of code:

unity_method_signature

Everything seems pretty obvious here, to anyone who has ever used an IoC container. Using generic parameter I register a type (ServiceHost) service, with specific key (myService), then I explicitly (I could write a whole post about how not good idea it is, but it’s leave it out for now) specify constructor I want used and it’s parameters using InjectionConstructor, next I specify method injection with InjectionMethod class. Pretty simple, huh?

Now, let’s take a closer look at InjectionMethod constructor. It takes a string, denoting method’s name, and next it takes the list of objects (array of System.Object to be precise) that should be used as method’s parameters, right? the tooltip leaves no doubt about it. It says:

methodParameters: Parameter values for the method.

Well, if you think it’s obvious imagine my surprise when I saw this, after running this code:

unity_exception

Turns out it’s not so obvious to everybody. To make the long story short, pulling Unity’s source code showed, that there’s a fine print to that method (well, actually there’s none, it just works in unexpected ways, maybe that behavior is mentioned somewhere in the docs, but I’m paid for writing working code, not for reading docs). It does use the parameters you provide literally, most of the time. However if you pass an argument of type System.Type, like I did, Unity implicitly tries to know better, what you want to do, than yourself. It assumes that since you passed a System.Type, as System.Object parameter, for sure what you meant was not to use it literally, but instead to use instance of service of that type registered with the container, and that’s what it tries to do. It then fails to bind those parameters to the method, which results in aforementioned exception. To make it work you have to be yet smarter and know another implicit rule of Unity, that if you pass as parameters values of types derived from InjectionParameterValue it will handle them correctly. So changing the above code to this, yields the expected results:

unity_fixed

Technorati Tags: ,