Archive for the ‘.NET’ Category

Framework Tips XII: Advanced .NET delegates

Saturday, July 18th, 2009

All .NET del­e­gates inherit (indi­rectly) from System.Delegate class (and directly from System.MulticastDelegate) which has a sta­tic Cre­at­eDel­e­gate method. The method has two pow­er­ful char­ac­ter­is­tics that are not widely known.

All del­e­gate types are imple­mented by the run­time. What do I mean by that? Let’s have a look at how any del­e­gate type looks at the IL level:

delegateInIL

All meth­ods are run­time man­aged, mean­ing that, in a sim­i­lar fash­ion you pro­vide imple­men­ta­tion for inter­face meth­ods, run­time pro­vides imple­men­ta­tion for del­e­gate meth­ods. Take a look at the con­struc­tor. Regard­less of del­e­gate type it always has two argu­ments: object (on which a method will be invoked via the del­e­gate) and a han­dle to that method.

While try­ing (with great help of Ken­neth Xu) to find a way of pro­vid­ing prox­y­ing of explic­itly imple­mented inter­face mem­bers in Dynamic Proxy, I saw this as a pos­si­ble way of being able to imple­ment the fea­ture. The prob­lem in this case is, that proxy is an inher­ited class, that has to call a pri­vate method on the base class. So given that Dynamic Proxy works in IL, I tried to call that con­struc­tor in IL pass­ing required para­me­ters, but unsur­pris­ingly, run­time does access checks so what I got instead of work­ing del­e­gate was this:

MethodAccessException

 

 

Ken­neth sug­gested another approach – using Delegate.CreateDelegate, because as it turns out, you can suc­cess­fully use that method to bind del­e­gates to pri­vate meth­ods. That is the first impor­tant char­ac­ter­is­tic that may be a life saver in cer­tain cases.

So, instead of this (which won’t compile):

public override int BarMethod(int num1)
{
    Func<int, int> d = new Func<int, int>(this.DynamicProxy.Program.IFoo.BarMethod);
    return d(num1);
}

You can use this, which will both com­pile and work:

public override int BarMethod(int num1)
{
    Func<int, int> d = Delegate.CreateDelegate(typeof(Func<int, int>), this, barMethodInfo) as Func<int, int>;
    return d(num1);
}

It has a draw­back though – it’s order of mag­ni­tude slower than cre­at­ing the del­e­gate via its con­struc­tor. Solu­tion brings us to the sec­ond char­ac­ter­is­tic I wanted to talk about – open instance methods.

Each instance method at IL level has an addi­tional argu­ment, implic­itly passed this pointer. Armed with this knowl­edge, let’s read what MSDN says about Delegate.CreateDelegate and open instance methods:

If firstAr­gu­ment is a null ref­er­ence and method is an instance method, the result depends on the sig­na­tures of the del­e­gate type type and of method:

  • If the sig­na­ture of type explic­itly includes the hid­den first para­me­ter of method, the del­e­gate is said to rep­re­sent an open instance method. When the del­e­gate is invoked, the first argu­ment in the argu­ment list is passed to the hid­den instance para­me­ter of method.

  • If the sig­na­tures of method and type match (that is, all para­me­ter types are com­pat­i­ble), then the del­e­gate is said to be closed over a null ref­er­ence. Invok­ing the del­e­gate is like call­ing an instance method on a null instance, which is not a par­tic­u­larly use­ful thing to do.

This basi­cally says that we can bind method to del­e­gate that passes the ‘this’ argu­ment explic­itly, so that we can reuse the del­e­gate for mul­ti­ple instances. Here’s how that works:

private static Func<Foo, int, int> d;
 
static Foo()
{
    d = Delegate.CreateDelegate(typeof(Func<Foo, int, int>), barMethodInfo) as Func<Foo, int, int>;
}
 
public override int BarMethod(int num1)
{
    return d(this, num1);
}

With this approach we pay the price of del­e­gate cre­ation only once per life­time of the type.

I was curi­ous how all these approaches would per­form, so I cre­ated a quick poor-man’s benchmark.

I invoked an instance method 100 times using four approaches:

  1. directly
  2. via del­e­gate cre­ated using its constructor
  3. via del­e­gate cre­ated using Cre­at­eDel­e­gate pass­ing first argu­ment explic­itly (not null).
  4. via del­e­gate cre­ated once using Cre­at­eDel­e­gate and then reusing it for sub­se­quent calls.

Here are the results (times are in ticks):

poormansDelegateBenchmark

As you can see, when reusing the instance after 100 calls we can achieve the same per­for­mance as when using the delegate’s con­struc­tor, which, given we can use in broader spec­trum of cases, is pretty amazing.

If you want to run the tests for your­self, the code is here.

Tech­no­rati Tags: ,,,

Code generation and DRY

Monday, May 25th, 2009

I’m gen­er­ally against code gen­er­a­tion for a vari­ety of rea­sons I’m not going to talk about here. How­ever in some cases, small, tar­geted code gen­er­a­tion is good, as it helps you avoid repet­i­tive typ­ing in ver­bose lan­guages like C# with­out cre­at­ing unmain­tain­able blob of poor qual­ity code.

In other words, I very much like being able to go from this:

codegen_before

to this:

codegen_after

by just press­ing Enter.

Ayende on Castle ActiveRecord

Thursday, April 23rd, 2009

I don't usu­ally do that, but here's Ayende' pre­sen­ta­tion from last year's Ore­dev con­fer­ence (yes, it says 2007, but it really is from 2008).

It's fun, very infor­ma­tive if you don't know Active Record, and of sur­pris­ingly good qual­ity (means you can actu­ally hear what Ayende is say­ing, and see the code). Most of all, this is an awe­some presentation.

How many times have you gone to a pre­sen­ta­tion when pre­sen­ter said "Give me a domain model that you want to work on" and then went and imple­mented it!

It's a must see. Highly rec­om­mended. And if you reg­is­ter to vid­dler, you can down­load the video in slightly bet­ter qual­ity and res­o­lu­tion here.

Meffing with Castle Windsor

Sunday, April 5th, 2009

Patrik Hägne has an inter­est­ing post on remov­ing com­pile time depen­den­cies between assem­blies, while still reap­ing ben­e­fits of using flu­ent inter­faces to boot­strap Aut­o­Fac con­tainer (go read it, I’m not going to reit­er­ate what Patrick wrote) using MEF.

It inspired me to do sim­i­lar thing for Cas­tle Winsor.

meffing_with_castle_project

I cre­ated a sim­ple solu­tion with 3 project. One is the main appli­ca­tion entry, which also holds a MefIn­staller which we’ll talk about in a sec­ond. Sec­ond one: Ser­vices, con­tains inter­faces that our appli­ca­tion rely on. Impl con­tains imple­men­ta­tion of these inter­faces. Pretty sim­ple huh?

The impor­tant thing is the tree of dependencies:

meffing_with_castle_dependencies

Notice that there’s no hard depen­dency on Impl module.

IBar and IFoo along with their imple­men­ta­tion are pretty triv­ial and not really worth show­ing. Two inter­est­ing classes are MefIn­staller 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);
    }
}

Cas­tle Wind­sor exposes a IWind­sorIn­staller inter­face that you can use to batch reg­is­ter whole sub­sys­tems or mod­ules with the con­tainer. In this case MefIn­staller acts as a dynamic com­pos­ite, which using MEF gath­ers all IWind­sorIn­stallers that export them­selves as “Com­po­nentIn­staller” (it’s just a con­ven­tion I came up with here, this is not manda­tory, and doesn’t have any deeper mean­ing), 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");
    }
}

Mod­ule­In­staller is just one such installer, which reg­is­ters ser­vices imple­mented in its module.

Now the actual boot­strap­ping 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;
    }
}

Boot­strap­Con­tainer runs the MefIn­staller, and reg­is­ters MyApp class, which is the main class in our appli­ca­tion. Then the class is requested from the con­tainer, and a method is invoked on its instance.

The class itself is triv­ial. What is inter­est­ing, is that it has depen­den­cies on two ser­vices we defined: IFoo and IBar. Just for kicks, I defined one as con­struc­tor depen­dency, and one as prop­erty 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 com­pile the appli­ca­tion, and copy MeffingWithCode.Impl.dll to the out­put direc­tory, because it’s not sta­t­i­cally linked to the other assem­blies, and run it, we’ll see that MEF does indeed pick up our miss­ing depen­den­cies, so that we don’t get NullReferenceException.

With this we get best of both worlds: We get flex­i­bil­ity of XML con­fig­u­ra­tion (with­out being prone to typ­ing mis­takes), and strongly typed, refac­tor­ing friendly reg­is­tra­tion (with­out sta­tic link­ing between assemblies).

meffing_with_castle_app

Tech­no­rati Tags: , ,

Comparing execution speed of .NET dynamic proxy frameworks

Wednesday, March 18th, 2009

A recent com­ment on Twit­ter from Tim Barcz started me think­ing about alter­na­tive proxy frame­works (alter­na­tive to Cas­tle Dynamic Proxy that is). Recently LinFu Dynamic Proxy started gain­ing some pop­u­lar­ity, after it was included as one of stan­dard byte­code providers in NHibernate.

Dis­claimer:

To make things clear. I'm a long time user of Cas­tle Dynamic proxy and I may be biased towards it. I also hap­pen to know how to use it, con­trary to all the other frame­works, that’s why the fol­low­ing test may not be real­iz­ing their full poten­tial. If you spot a non-optimal use of any of the frame­works in the fol­low­ing test, let me know and I’ll update it.

Hav­ing said that, I put together a small sam­ple test project, where I gen­er­ate a one-interceptor proxy for a sim­ple inter­face with each frame­work and call a method on this proxy 100,000 times.

The inter­face is as sim­ple as it can be:

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

Each inter­cep­tor 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 frame­works. Cas­tle Dynamic Proxy 2.1 RC1, LinFu Dynamic Proxy 1.01, Spring.NET 1.2, which is a big frame­work in itself, but it has some pretty pow­er­ful prox­y­ing capa­bil­i­ties, and Microsoft Unity 1.2 which has now some prox­y­ing capa­bil­i­ties 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 jit­ter kick in, so the really impor­tant stuff, is the sec­ond pass.

Cas­tle Dynamic Proxy was the fastest one, which is not really a sur­prise for me. It’s designed to be fast and light­weight, and also has some pretty pow­er­ful capa­bil­i­ties that allow you to cus­tomize the proxy type being cre­ated so that you don’t waste cycles inter­cept­ing meth­ods you don’t want to inter­cept, or call­ing inter­cep­tors you don’t need called for a par­tic­u­lar method. (for an in-depth overview of Cas­tle Dynamic Proxy see my tuto­r­ial series).

The sec­ond one was Spring.NET which took over 3 times longer. This is how­ever still pretty fast, and con­sid­er­ing that it’s a pretty exten­si­ble and con­fig­urable frame­work as well, I’m sure in real life sce­nario you can squeeze very good per­for­mance out of it.

Third one, Unity was an order of mag­ni­tude slower than Cas­tle. This is not a sur­prise con­sid­er­ing how bloated and over engi­neered it is. To be fair how­ever, this may as well be due to strong tie between Unity IoC con­tainer and proxy frame­work. The proxy frame­work does not seem to be oper­a­ble out­side of the con­tainer, so the per­for­mance hit, may be par­tially due to some con­tainer overhead.

LinFu was two orders of mag­ni­tude slower than Cas­tle. This was really sur­pris­ing. Or at least until I noticed that it gath­ers a call stack for each and every invo­ca­tion, and as I men­tioned, this can (as clearly vis­i­ble) be a per­for­mance overkill. I looked for a way to turn it off, but it seems there isn’t any. Also the only way of call­ing the inter­cepted method is via MethodInfo.Invoke, which is also a lot slower than direct invo­ca­tion (or invo­ca­tion via a delegate).

Note that this is an iso­lated case of a sin­gle per­for­mance test. I thought it’s the most impor­tant one, but it’s just my opin­ion. I also didn’t talk about capa­bil­i­ties, which should be your major con­cern when select­ing a frame­work. – Can it sup­port my sce­nario is the ulti­mate test. Frankly, the fastest two, are also the most mature and powerful.

You can check the com­plete code here.

UPDATE:

Here’s a screen­shot from a pro­filer show­ing the LinFu’s proxy call tree. As you can clearly see, the major per­for­mance hit (over 90% of the time!) is in Stack­Trace con­struc­tor. It also obtains a Method­Info dynam­i­cally instead of caching it, like other frame­works do, which is an expen­sive oper­a­tion as well.

LinFu

UPDATE 2:

LinFu has been updated and it no longer col­lects stack trace infor­ma­tion: I re-ran the test and you can see the results here.

 

Tech­no­rati Tags: , , , ,

WPF memory leak with VisualBrush TileMode="Tile"

Wednesday, March 11th, 2009

Recently at work, while work­ing on WPF GUI for our appli­ca­tion we noticed, that our app leaks mem­ory. After some time (actu­ally a lot of time, since we first though that it was video codec’s fault) we nailed it, and unfor­tu­nately, it looks like it’s a bug in the WPF itself. I attach a sam­ple appli­ca­tion that exposes the issue.

leaking_app

What it does is basi­cally… blink­ing a rec­tan­gle. The key thing is, how the rec­tan­gle 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 crit­i­cal part that causes the leak (and ulti­mately Out­OfMem­o­ryEx­cep­tion) is using Draw­ing­Brush  with Tile­Mode set to Tile. Chang­ing this, makes the issue go away. It was tested on few com­put­ers, run­ning Intel, AMD, and NVidia GPUs. The issue exists on Win­dows XP, as well as on Win­dows 7.

There is a Con­nect entry for that issue, but so far it is unresolved.

The workaround for now, is to not use Draw­ing­Brush, which is what we did.

If you want to check the issue for your­self here’s the code.

Tech­no­rati Tags:

Mommy, there be dragons in my code.

Monday, February 23rd, 2009

Every devel­oper, and every shop has a Acme.Commons, or Acme.Core library, where they keep use­ful helper classes and exten­sions used in almost every project. Ayende has his Rhino Com­mons that I’ve seen him blog­ging about a few times but I never quite got around to actu­ally take a look at the code…

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

The first class I found aston­ish­ing was Hack­Ex­piredEx­cep­tion. My first reac­tion looked some­thing like this:

Then I looked for some code that throws this excep­tion 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 con­trolled fash­ion when you for­get about it. Too many times a for­got­ten quick and dirty hack slips under the radar and get left behind, for­got­ten wait­ing to blow up in pro­duc­tion or dur­ing very impor­tant presentation.

Another, very neat idea I found in the library is the ThereBeDrag­on­sAt­tribute class.

This marker attribute dec­o­rate dan­ger­ous parts of the code where for some rea­son the devel­oper decided to do some­thing in a way that is not straight-forward. This usu­ally means that this is using some func­tion­al­ity that is not fully supported.

Using wacky, unsup­ported or hack­ish code is some­thing every­one does occa­sion­ally. I usu­ally com­ment this piece of code, be it a method or a class, but com­ments are often not enough. With lit­tle help of NDe­pend to bring these pieces of code to everyone’s atten­tion this may be a very use­ful warn­ing sign for every­one on the team to han­dle this code with spe­cial care.

There are many other use­ful classes in Rhino Com­mons, but most of them are pretty stan­dard stuff (maybe with the excep­tion of prop­erty indexers).

What other non-standard, help­ful lit­tle (or not so lit­tle) classes do you use in your code?

Working effectively with Reflection.Emit

Monday, January 19th, 2009

I’ve been work­ing a lit­tle bit with dynamic code gen­er­a­tion at run­time (classes in Reflection.Emit name­space, col­lec­tively referred to as Reflection.Emit). It’s a low level API, that requires you to work with IL oper­a­tions, keep track of what is on the stack, and requires quite a bit of knowl­edge about IL and CLR.

I’m no expert in IL, as prob­a­bly most of devel­op­ers, but there are ways to make this things easier.

To work my way through gen­er­at­ing code, I use iter­a­tive approach.

  1. Write a class/method in C# that exactly (or as closely as pos­si­ble) reassem­bles a sin­gle small part of what I want my dynamic method to look like. If my dynamic method is a sta­tic method – I write a sta­tic method. If it has a value type para­me­ter, I write a method with value type para­me­ter. I think you get the pic­ture. The impor­tant thing is to really get as close to what you want to achieve with dynamic method as pos­si­ble, and under­stand influ­ence of those parts you can’t get exactly the same (for exam­ple because of C# limitations).
  2. I com­pile the class (also notice dif­fer­ences between mode you com­pile in – you usu­ally want Release ver­sion, not Debug), and open it up in Reflec­tor to see its IL.
  3. I write my code that does code gen­er­a­tion, to gen­er­ate IL iden­ti­cal to the one of my sta­t­i­cally wrote method (tak­ing into account all the variability).
  4. I save gen­er­ated assem­bly, open it up in Reflec­tor, and com­pare the IL, to the one cre­ated ear­lier, to see if they match. I often switch in Reflec­tor to C# view, to bet­ter see some kinds of errors (pass­ing wrong para­me­ters, or call­ing method on wrong object). If you can’t save your gen­er­ated code to phys­i­cal assem­bly you can’t use this debug­ger visu­al­izer to see its IL.
  5. Write and run tests.
  6. If every­thing works, go back to step one, add another part of code and repeat until you have all you wanted.

Here’s an exam­ple of this approach. It’s an actual code I wrote while work­ing on Dynam­icProxy fea­ture. The thing that is dif­fer­ent here, is that Cas­tle has an addi­tional layer of abstrac­tion on top of Reflection.Emit so I was not work­ing directly with IL. This makes things a lit­tle bit eas­ier, because you’re oper­at­ing on a higher level of abstrac­tion. On the other hand how­ever, you don’t get that tight con­trol over what gets gen­er­ated, and you have a new API to learn.

Any­way, I actu­ally already had a pretty good idea of what I wanted to do (I only needed to change the way things worked, by call­ing other con­struc­tor in my dynamic method, pass­ing addi­tional para­me­ters). I wrote some tests to ver­ify that my code works the way I wanted it to, and I imple­mented it. Unfor­tu­nately one test didn’t pass with the fol­low­ing error.

reflectionemiterror1 

One para­me­ter I wanted to pass was an array, passed by ref­er­ence, and it seemed that there was some­thing wrong with it.

I opened Reflec­tor and peeked into the gen­er­ated method. Every­thing looked just fine when I switched to C# view.

 reflectionemitReflector

To inves­ti­gate things fur­ther I saved IL of gen­er­ated method to a file, and I did the same with IL of C# method I wrote as an exam­ple of what I wanted to accom­plish. I then opened them both up in a diff tool to see where the dif­fer­ence 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). Know­ing this it was triv­ial to fix my code.

On a side note, there’s also a Reflection.Emit Lan­guage plug-in for Reflec­tor that may be use­ful to you if you’re work­ing directly with Reflection.Emit classes. It shows you for any method you select the C# code that you’d write to gen­er­ate that method with Reflection.Emit.

Tech­no­rati Tags: , ,

The most important part of .NET 4.0 – code contracts

Wednesday, December 17th, 2008

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

Sim­ply because scope of it’s usage is lim­ited and peo­ple have yet to learn how to use it prop­erly. Per­son­ally the things I’m using the most often are ‘var’ and a fea­ture I’ve been really skep­ti­cal about – auto­matic prop­er­ties. Now, few weeks after announce­ments of what is going to be present in the next wave of .NET, Visual Stu­dio and the lan­guage, the dust has set­tled, and we’re past ini­tial impres­sions. There’s been one (well actu­ally more than one, but I’m just going to con­cen­trate on the one in this post) announce­ment, that didn’t get quite as much atten­tion as it, in my opin­ion, should have.

What I’m talk­ing is – code con­tracts. The rea­son why I think they’re so impor­tant is not, that they finally give you the tool to explic­itly state your assump­tions and agree­ments regard­ing behav­ior of your meth­ods in a writ­ten down, com­monly under­stood way. The rea­son why I think it’s impor­tant is – because Microsoft can do it.

If you think about why they tend to lock things down in the frame­work, pro­duc­ing immense num­ber if sealed inter­nal non-virtual and oth­er­wise not avail­able classes and meth­ods, it will become clear. They do it, because by not allow­ing you to over­ride, or plug-in your code, they con­trol the implicit con­tract between dif­fer­ent inter­act­ing par­ties. And if they con­trol it they can ver­ify that their implicit con­tract does not get vio­lated. They lock the things so that they con­trol who and how can call the meth­ods and how they should behave.

With Code Con­tracts how­ever, there’s no more need for that. Con­tracts are there to state the assump­tions explic­itly. They can be ver­i­fied, either at com­pile time, or at run­time (and with ReSharper, I guess, as-you-type) and they will ensure that the assump­tions meth­ods make about their callers, are met. With that hope­fully, Microsoft will acknowl­edge that lock­ing things down was a poor workaround for the real prob­lem, and since they’ll have bet­ter solu­tion now, we’ll see more open and exten­si­ble API in the framework.

Or maybe I’m only dreaming.

Multilingual .NET applications. Enter .NET localization

Wednesday, December 10th, 2008

Cre­at­ing mul­ti­lin­gual appli­ca­tions is a huge topic. There are whole books devoted to it, and if you’re seri­ous about it, you should def­i­nitely read those, because what you see on sur­face, is only the tip of an iceberg.

If you only want to play with local­iza­tion or need a quick ref­er­ence, hope­fully this post will help.

Fist thing is, .NET is really well thought of if it comes to local­iza­tion, so if you know what you’re doing, it’s pretty pain­less to cre­ate appli­ca­tion that will be easy to trans­late to other lan­guages (local­iza­tion is a LOT big­ger topic than show­ing labels in dif­fer­ent lan­guages, but I’ll leave this topic out.)

Sec­ond thing is, local­iza­tion mech­a­nism in .NET is greatly based on con­ven­tions, and it’s what we’ll focus here.

First obvi­ous rule is, that each string, pic­ture, video… gen­er­ally speak­ing local­iz­able resource must not be hardcoded.

If you don’t hard­code resources where do you keep them? In (sur­prise) Resources file. Gen­er­ally you can use .resx files, or plain .txt, though the lat­ter are use­ful only if you only keep strings.

resourceFile

Visual Stu­dio has pretty good sup­port for edit­ing resources in .resx files, and later I’ll show you another tool that can do it as well.

To access the resources pro­gram­mat­i­cally you need Resource­M­an­ager class. To instan­ti­ate it you need to give it the part to resources within an assem­bly, and the assem­bly itself. If it’s a lit­tle bit unclear, here’s the example:

resourcePath

If the Visual Stu­dio project is named Local­iz­ableApp, and the .resx file we want to use is in folder Prop­er­ties, and the file itself is named Resources.resx, the whole base name for the resources is “LocalizableApp.Properties.Resources”.

That’s where the com­piled .resx file (.resources) will be located within the assem­bly. You can see it, if you open the com­piled assem­bly with Reflector.

resourceLocation

So to instan­ti­ate the Resource­M­an­ager you’d write code sim­i­lar to the following:

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

Each resource is iden­ti­fied by it’s unique name string. For exam­ple in the pic­ture below, we have two resources with names, “greet­ing” and “howAreYou”

resourceEditor

You use these names to get the val­ues of the resources. The resource man­ager does its magic, to pro­vide you with resources best match­ing the Cul­ture­Info you pro­vided. If you don’t pro­vide any Cul­ture, cur­rent thread’s Cur­ren­tU­I­Cul­ture is used. So if you write:

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

The Cul­ture­Info object held in Cur­ren­tU­I­Cul­ture prop­erty of cur­rently exe­cut­ing thread will be used. The default value for this prop­erty is the same as lan­guage ver­sion of Win­dows OS the pro­gram is exe­cut­ing on, which is rea­son­able. If your user uses Pol­ish Win­dows she will prob­a­bly want to inter­act with Pol­ish ver­sion of your app as well.

You may not rely on this default though, and either over­ride the Thread’s prop­erty, or spec­ify the cul­ture explic­itly when call­ing meth­ods on Resource­M­an­ager, like so:

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

Of course you wouldn’t hard­code the cul­ture the way I did in the exam­ple, because it would defeat the pur­pose of using cul­ture in the first place.

OK, so how to add another language?

You have the .resx file with the default, fall­back resources, right? So now all you need is either send the file to a local­iza­tion com­pany, sit back and enjoy life, wait­ing for them to do the hard job, or do it your­self. To go with the lat­ter option, you may want to use a tool to edit resource files, called Resourcer, by Lutz Roeder (Reflec­tor, people!).

resourceResourcer

You can eas­ily edit any kind of resources in it (not only strings). When you’re done trans­lat­ing your resources, save the file as .resources file, using fol­low­ing pat­tern: {baseResourceName}.{culture}.resources. For exam­ple if you were to trans­late our exam­ple app, to Ger­man lan­guage as spo­ken in Ger­many, you’d save your edited file with the fol­low­ing name: LocalizableApp.Properties.Resources.de-de.resources

It is impor­tant to obey this pat­tern, as by con­ven­tion, this is what Resource­M­an­ager expects. If you fail to obey it, Resource­M­an­ager will not be able to pick your trans­lated resources and will fall back to the default.

Hav­ing trans­lated and prop­erly named .resource file we need to make a satel­lite assem­bly out of it. To do it, you need Assem­bly Linker (al.exe) tool that is part of .NET SDK.

al

There are mul­ti­ple prop­er­ties you can set with al, the min­i­mal ver­sion to get valid satel­lite assem­bly is shown on above screen­shot. One thing that’s impor­tant to note, is the name of result­ing satel­lite assem­bly. Again, by con­ven­tion it has to be {NameOfBaseAssemblyWithoutExtension}.resources.dll, so if our appli­ca­tion assem­bly was named LocalizableApp.exe, satel­lite assem­bly must be called LocalizableApp.resources.dll

Notice that the name of the assem­bly is the same for every cul­ture. So how do we deal with that. Obvi­ously we can’t have two files with the same name in one folder. The way it is han­dled, is through sub­fold­ers. Each satel­lite assem­bly is held in a folder which is named after the cul­ture of the satel­lite assembly.

resourceFolders

For exam­ple if our LocalizableApp.exe is held in a folder, let’s say Debug like on the above screen­shot, the de-de satel­lite assem­bly would be Debug\de-de\LocalizableApp.resources.dll and for instance pl assem­bly would be in Debug\pl\LocalizableApp.resources.dll.

I hope this is all clear by now. The great­est thing is, to add new lan­guage you don’t even need the actual base assem­bly. All you need is its resources and their loca­tion within the assembly.

Tech­no­rati Tags: , ,