Archive for the ‘c#’ Category

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: , ,

Castle DynamicProxy tutorial part I: Introduction

Tuesday, December 16th, 2008

I’ve been exper­i­ment­ing lately quite a lot with Cas­tle Dynamic Proxy, cre­at­ing pro­to­type for a project I work on at work and I even imple­mented a small fea­ture that was miss­ing from it. Gen­er­ally, Dynamic Proxy (DP from now on) is a great, light­weight frame­work, but it’s great­est down­side is lack of doc­u­men­ta­tion. It’s sur­pris­ingly log­i­cal a easy to use, but since there are almost no resources on the web, that could help you get started with it, I decided to give it a go, and start a small tuto­r­ial series of posts, that will intro­duce var­i­ous fea­tures of DP while work­ing on a sim­ple sam­ple project.

The project is to add abil­ity to freeze objects, so that from the point in time where object has been frozen, it’s state can not change. AFAIK there’s such fea­ture in WPF, but since my knowl­edge of WPF is very lim­ited, I don’t know how that works. The project itself is not impor­tant (nor the use­ful­ness of its imple­men­ta­tion). It’s only pur­pose is to serve as didac­ti­cal exam­ple. I am also aware that the state of the project shown here is far from how good code should look like. We will evolve the imple­men­ta­tion in forth­com­ing parts of the tuto­r­ial, as we intro­duce other con­cepts and fea­tures of DP.

Basi­cally here’s what we want to achieve:

  • Be able to use non-frozen freez­able object just like any other object
  • Be able to check if the object is freezable
  • Be able to check if the object is frozen
  • be able to freeze freez­able object
  • NOT be able to change state of the object after it has been frozen

How do we do that? Well, DP cre­ates a trans­par­ent proxy for the real objet at run­time for as, and we can inter­cept the calls to it, and add logic to the objects. This is a very pow­er­ful capa­bil­ity and pos­si­bil­i­ties of using it, are vir­tu­ally endless.

To spec­ify our require­ments, we use tests, using xUnit framework:

[Fact]
public void IsFreezable_should_be_false_for_objects_created_with_ctor()
{
    var nonFreezablePet = new Pet();
    Assert.False(Freezable.IsFreezable(nonFreezablePet));
}

[Fact]
public void IsFreezable_should_be_true_for_objects_created_with_MakeFreezable()
{
    var freezablePet = Freezable.MakeFreezable<pet>();
    Assert.True(Freezable.IsFreezable(freezablePet));
}

[Fact]
public void Freezable_should_work_normally()
{
    var pet = Freezable.MakeFreezable</pet><pet>();
    pet.Age = 3;
    pet.Deceased = true;
    pet.Name = "Rex";
    pet.Age += pet.Name.Length;
    pet.ToString();
}

[Fact]
public void Frozen_object_should_throw_ObjectFrozenException_when_trying_to_set_a_property()
{
    var pet = Freezable.MakeFreezable</pet><pet>();
    pet.Age = 3;

    Freezable.Freeze(pet);

    Assert.Throws<objectfrozenexception>(delegate { pet.Name = "This should throw"; });
}

[Fact]
public void Frozen_object_should_not_throw_when_trying_to_read_it()
{
    var pet = Freezable.MakeFreezable<pet>();
    pet.Age = 3;

    Freezable.Freeze(pet);

    Assert.DoesNotThrow(delegate { int age = pet.Age; });
    Assert.DoesNotThrow(delegate { string name = pet.Name; });
    Assert.DoesNotThrow(delegate { bool deceased = pet.Deceased; });
    Assert.DoesNotThrow(delegate { string str = pet.ToString(); });
}

[Fact]
public void Freeze_nonFreezable_object_should_throw_NotFreezableObjectException()
{
    var rex = new Pet();
    Assert.Throws<notfreezableobjectexception>(() => Freezable.Freeze(rex));
}

We use sta­tic class  Freez­able to cre­ate freez­able objects, and to query their state. This allows us to have really sim­ple API (and imple­men­ta­tion), and encap­su­late all (well, not all — yet) freez­able logic in one place. This imple­men­ta­tion has one short­com­ing that you may have spot­ted – the class we want to make freez­able instance of, has to have default, para­me­ter­less constructor.

This is not a DP lim­i­ta­tion how­ever, and fur­ther along the way, we will remove it.

The way DP works, is by sub­class­ing given class and over­rid­ing it’s meth­ods. This approach has few limitations:

  • you obvi­ously can’t proxy sealed class, since it can’t be inher­ited from
  • you can only over­ride vir­tual meth­ods, so for non-virtual meth­ods there’s noth­ing you can gain

Ok, so how do we go about imple­ment­ing the whole thing?

First we need some way of track­ing which objects are freez­able and  their freez­abil­ity state. For that we cre­ate an interface:

internal interface IFreezable
{
    bool IsFrozen { get; }
    void Freeze();
}

It will help us by pro­vid­ing all the infor­ma­tion we need.

Then, in our Freez­able sta­tic class we cre­ate a dic­tio­nary, that will map objects, to their freez­abil­ity state:

private static readonly IDictionary<object, IFreezable> _freezables = new Dictionary<object, IFreezable>();

With that, imple­men­ta­tion of Freez­able meth­ods should be really straightforward:

public static bool IsFreezable(object obj)
{
    return obj != null && _freezables.ContainsKey(obj);
}

public static void Freeze(object freezable)
{
    if (!IsFreezable(freezable))
    {
        throw new NotFreezableObjectException(freezable);
    }
    _freezables[freezable].Freeze();
}

public static bool IsFrozen(object freezable)
{
    return IsFreezable(freezable) && _freezables[freezable].IsFrozen;
}

Still how­ever, no word about DP, and we have imple­men­ta­tion of Make­Freez­able miss­ing. Also, a reader may point out, that by virtue of keep­ing some map­ping from objects to inter­face, objects won’t mag­i­cally gain behavior.

That is true, with a lit­tle bit of work how­ever, they will.

What we need to do, is to mon­i­tor calls to prop­erty set­ters, and if object is indeed frozen call­ing a set­ter should raise an excep­tion, as shown in the test. To do that we need to actu­ally inter­cept the call, and for that, we have IIn­ter­cep­tor interface.

IIn­ter­cep­tor has only one method:

Castle.Core.Interceptor.IInterceptor.Intercept(Castle.Core.Interceptor.IInvocation);

The IIn­vo­ca­tion is another inter­face that holds all the infor­ma­tion about the call.

dptutorial_1_iinvocation

We can query its Method prop­erty to get Method­Info object point­ing to the called method, Pro­ceed method, that invokes the method on tar­get object and few other meth­ods and prop­er­ties that we will exam­ine in forth­com­ing parts of the tuto­r­ial. With that, we have all we need to actu­ally imple­ment our freez­able logic:

internal class FreezableInterceptor : IInterceptor, IFreezable
{
    private bool _isFrozen;

    public void Freeze()
    {
        _isFrozen = true;
    }

    public bool IsFrozen
    {
        get { return _isFrozen; }
    }

    public void Intercept(IInvocation invocation)
    {
        if (_isFrozen && invocation.Method.Name.StartsWith("set_", StringComparison.OrdinalIgnoreCase))
        {
            throw new ObjectFrozenException();
        }

        invocation.Proceed();
    }
}

Our inter­cep­tor holds the freez­abil­ity state of the object. Since we cre­ate one inter­cep­tor per object, it will work. In the Inter­cept method, inter­cep­tor checks if the object is frozen, and if called method’s name starts with “set_”, as is the case for all prop­erty set­ters. If indeed that’s the case, it means that we’re try­ing to set a prop­erty of a frozen object, so a Object­FrozenEx­cep­tion is thrown. Oth­er­wise, we can pro­ceed with the call.

Now, it’s really easy to imple­ment Freezable.MakeFreezable method. we know how to inter­cept calls. The only piece miss­ing is – how do we actu­ally cre­ate the prox­ies. For that, we use the Prox­y­Gen­er­a­tor class. We only need one instance, so we may keep it as a sta­tic field in the Freez­able class

private static readonly ProxyGenerator _generator = new ProxyGenerator();

Prox­y­Gen­er­a­tor class is the heart of the DP library. It has numer­ous meth­ods for cre­at­ing dif­fer­ent kinds of prox­ies, but for now, we will only use one: Cre­ate­ClassProxy, that cre­ates a proxy for a class.

public static TFreezable MakeFreezable<TFreezable>() where TFreezable : class, new()
{
    var freezableInterceptor = new FreezableInterceptor();
    var proxy = _generator.CreateClassProxy<TFreezable>(new CallLoggingInterceptor(), freezableInterceptor);
    _freezables.Add(proxy, freezableInterceptor);
    return proxy;
}

We cre­ate a Freez­ableIn­ter­cep­tor to inter­cept the calls, ver­ify freez­abil­ity state of the con­nected object, and throw if nec­es­sary, then we cre­ate the actual proxy, add it along with its freez­ableIn­ter­cep­tor to the dic­tio­nary, and return.

In call to Cre­ate­ClassProxy generic method we pass one more argu­ment – a new instance of Cal­l­Log­ging­In­ter­cep­tor. It’s a sim­ple class that also imple­ments IIn­ter­cep­tor inter­face that logs all the inter­cepted calls to the con­sole. This also means that you can have more than one inter­cep­tor for a proxy which is a very pow­er­ful and handy capability.

With that, we basi­cally have out ini­tial imple­men­ta­tion com­plete, we only need to cre­ate miss­ing excep­tion classes and we are good to go. Indeed, all the tests should pass now.

dptutorial_1_tests_pass

We can cre­ate sam­ple con­sole appli­ca­tion to see how that works:

internal class Program
{
    private static void Main(string[] args)
    {
        var rex = Freezable.MakeFreezable<Pet>();
        rex.Name = "Rex";
        Console.WriteLine(Freezable.IsFreezable(rex)
                              ? "Rex is freezable!"
                              : "Rex is not freezable. Something is not working");
        Console.WriteLine(rex.ToString());
        Console.WriteLine("Add 50 years");
        rex.Age += 50;
        Console.WriteLine("Age: {0}", rex.Age);
        rex.Deceased = true;

        Console.WriteLine("Deceased: {0}", rex.Deceased);
        Freezable.Freeze(rex);
        try
        {
            rex.Age++;
        }
        catch(ObjectFrozenException ex)
        {
            Console.WriteLine("Oups. it's frozen. Can't change that anymore");
        }
        Console.WriteLine("--- press enter to close");
        Console.ReadLine();
    }
}

public class Pet
{
    public virtual string Name { get; set; }
    public virtual int Age { get; set; }
    public virtual bool Deceased { get; set; }

    public override string ToString()
    {
        return string.Format("Name: {0}, Age: {1}, Deceased: {2}", Name, Age, Deceased);
    }
}

The out­put of the appli­ca­tion looks like this:

dptutorial_1_app

Bah! We get the behav­ior we wanted, with­out actu­ally mod­i­fy­ing the Pet class, and with sur­pris­ingly few lines of code. It may be a lit­tle bit over­whelm­ing right now, but what we did, boils down to three things:

  1. We cre­ated IIn­ter­cep­tor imple­men­ta­tion, that over­rides Inter­cept method and keeps track of freez­able state of an object.
  2. We cre­ated a proxy object with proxyGenerator.CreateClassProxy method
  3. We cre­ated really sim­ple logic to cor­re­late out freez­able objects with inter­cep­tors, that keep their state.

And with all of that we barely scratched the sur­face of what can be done with DynamicProxy.

As a bonus, if you are curi­ous how the proxy type gen­er­ated by DP looks like, here’s what Reflec­tor shows:

dptutorial_1_reflector

If the last screen­shot left you with headache don’t worry, by the end of this tuto­r­ial it will be all crys­tal clear.

See you in part II, where we will intro­duce IProx­y­Gen­er­a­tionHook, to give us more fine-grained con­trol over our interceptors.

If you have any ques­tions or sug­ges­tions please, leave a comment.

The solu­tion with tests is avail­able here.

Dynam­icProxy I use is the trunk ver­sion. You can get the lat­est ver­sion here.

To run tests, you will also need xUnit frame­work, avail­able here.

Tech­no­rati Tags: , ,

Microoptimizations: foreach vs for in C#

Wednesday, November 19th, 2008

Patrick Smac­chia wrote a post where he com­pares exe­cu­tion time while using dif­fer­ent pat­terns to iter­ate over a col­lec­tion, namely List<int> and int[]. Since he pro­vided the code, I decided to give it a go as well. Only thing I did, was I added [MethodImpl(MethodImplOptions.NoInlining)] for each method, since they all were very sim­ple, and could eas­ily be inlined.

That said, here are my results (release build ran with­out debug­ger, out­side of Visual Studio):

iterate

If you com­pare those to Patrick’s results, you may notice few things:

  • Patrick has a faster PC (which only reminds me I really should start look­ing for a new one)
  • When you turn off inlin­ing results are much dif­fer­ent. First, fore­ach is as effi­cient on arrays as on lists (which is dif­fer­ent than Patrick’s results. My guess is, that since CLR has more inti­mate knowl­edge of arrays, it some­how opti­mized it when inlin­ing was turned on).
  • iter­at­ing with for loop is faster when you do the trick Patrick called “count opti­miza­tion”. This is quite the con­trary to what Eric Gun­ner­son said, and I’m puz­zled about it.
  • DO NOT all go and change your fore­ach­ing code to for loops! The num­bers you see are num­ber of ticks when iter­at­ing over a col­lec­tion of 100 000 000 ele­ments! That means that in each and every case, iter­a­tion is fast as hell, and it’s NOT your bot­tle­neck. To help you visu­al­ize that, here’s a pic­ture I bor­rowed from K. Scott Allen

You don’t get the C# 4.0, do you?

Saturday, November 15th, 2008

Sorry for the dar­ing topic, but that’s really what comes to my mind when I read or hear peo­ple whin­ing about C# loos­ing purity/object-orientation/strongly-typedness/goal/insert your favorite here, with the advent of ver­sion 4.0.

To sum it up, there are four major new areas of improve­ment com­ing up with the forth­com­ing ver­sion of the lan­guage, as out­lined by Char­lie Calvert in "New Fea­tures in C# 4.0".

  • dynamic key­word (type) along with all its implications.
  • Optional and named parameters.
  • Co/Contra-variance of generics
  • Few addi­tional fea­tures geared towards eas­ing the pain of deal­ing with COM

I don’t really care about COM, and covari­ance and con­travari­ance is not really con­tro­ver­sial (at most peo­ple will grum­ble that they have to learn how to use it prop­erly), so I’m going to leave those two out, and con­cen­trate on the first two features.

Optional and named para­me­ters wouldn’t prob­a­bly even make it into the lan­guage if it wasn’t for improv­ing inter­op­er­abil­ity with COM where they are heav­ily used. And I’m glad they did. Really. Major argu­ment peo­ple raise when it comes to them, is that they add no value to the lan­guage. Any­thing you can do with them, you can do with method over­loads. Yes you do, but step for­ward if you can tell me straight into my face, that you’d rather write this:

public virtual void AddComponent(String key, Type classType)
{
    AddComponent(key, classType, classType);
}
 
public void AddComponent(string key, Type classType, LifestyleType lifestyle)
{
    AddComponent(key, classType, classType, lifestyle);
}
 
public void AddComponent(string key, Type classType, LifestyleType lifestyle, bool overwriteLifestyle)
{
    AddComponent(key, classType, classType, lifestyle, overwriteLifestyle);
}
 
public virtual void AddComponent(String key, Type serviceType, Type classType)
{
    AddComponent(key, serviceType, classType, LifestyleType.Singleton);
}
 
public void AddComponent(string key, Type serviceType, Type classType, LifestyleType lifestyle)
{
    AddComponent(key, serviceType, classType, lifestyle, false);
}
 
public void AddComponent(string key, Type serviceType, Type classType, LifestyleType lifestyle,
                         bool overwriteLifestyle)
{
    /*actual code*/
}

than this:

public void AddComponent(string key, Type serviceType,
    Type classType: serviceType,
    LifestyleType lifestyle: LifestyleType.Singleton,
    bool overwriteLifestyle: false)
{
    /*actual code*/
}

It means less code to write, less code  to main­tain, less code that you’d do prob­a­bly copy/paste, which attracts bugs like a dead dog attracts flies. And while we’re talk­ing about bugs, think about meth­ods like this:

public XPathNodeInfoAtom(string localName, string namespaceUri, string prefix, string baseUri,
                         XPathNode[] pageParent, XPathNode[] pageSibling, XPathNode[] pageSimilar,
                         XPathDocument doc, int lineNumBase, int linePosBase)
 
 

What is really the chance that you’ll get all the para­me­ters right each time you call them, not mix­ing the order, and pass­ing local­Name instead of pre­fix, or the other way around? Think about how utterly hard to read the code is, espe­cially if you don’t have well named vari­ables you pass as para­me­ters. This can be fixed by explic­itly pass­ing each para­me­ter along with its name. And it’s not the case only for meth­ods that take that many para­me­ters. One com­mon mis­take I see is in con­struc­tors of Argu­mentEx­cep­tion and Argu­mentOut­OfRange excep­tion, both of which take para­me­ter­Name and mes­sage as a value, but in dif­fer­ent order.

The fea­ture that gets the most bad pub­lic­ity is the dynamic pro­gram­ming capa­bil­i­ties intro­duces thanks to dynamic key­word. That’s what makes peo­ple lament, that they will no longer be able to rely on Intel­liSense and the com­piler, and that this is the advent of apocalypse.

Well, rest assured – world will stand tomor­row, just like it stood yes­ter­day. The whole dynamic thing gives you three things:

  • Sim­pli­fied pro­gram­ming model for things you had to rely on strings (ergo, no com­piler check­ing any­way) in the past, so no harm done here.
  • Improved per­for­mance as com­pared to what you could achieve with reflec­tion thanks to smarter run­time resolution.
  • Less ugly code in those places, thanks to not hav­ing to use reflec­tion or any other crazy mech­a­nism to cir­cum­vent inabil­ity of mak­ing dynamic calls.

I hear that you say that this may be abused in the mul­ti­tude of ways. Well – yes, no com­piler or lan­guage let’s you stop think­ing (and if there were such com­pil­ers or lan­guages, we’d be out of job!). That is the case with every­thing though. C# has sup­port for point­ers, you know? It was added to deal with cer­tain nar­row range of sce­nar­ios, and it was there since v1.0 but I don’t see it used all over the place by any­one. Heck, there are fea­tures in the lan­guage many expe­ri­enced devel­op­ers didn’t even heard about, left alone used them. Exam­ple? – stack­alloc key­word. Did you know about it? Have you seen actu­ally code that uses it? I haven’t.

You can cut your­self with just about any­thing. We want more power in the lan­guage, but with power comes respon­si­bil­ity. The dynamic key­word hugely helps in cer­tain sce­nar­ios, and if used wisely can do you noth­ing but good.

To wrap it up, I think the whole sit­u­a­tion is best described by this quote from Andy Baio:

I'm sure that the moment man dis­cov­ered fire, there was some guy nearby say­ing, "Too smoky. Can burn you. Lame."

Tech­no­rati Tags: ,

Creating tree of dependencies with MEF

Thursday, November 6th, 2008

As a fol­low up to my pre­vi­ous post, here’s the sim­pli­fied – Con­sole based ver­sion of the code.

Dis­claimer.

This is a solu­tion. Not the best one, not rec­om­mended by any­one, just the one that hap­pened to solve my prob­lem. So take it with a (big) grain of salt, and if you know a bet­ter one, use the Leave your com­ment func­tion below.

using System;
using System.ComponentModel.Composition;
using System.Reflection;
 
[assembly:AllowNonPublicComposition]
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            ComposablePartCatalog catalog = new AttributedAssemblyPartCatalog(Assembly.GetExecutingAssembly());
 
            var container = new CompositionContainer(catalog.CreateResolver());
 
            var shell = new Shell();
 
            container.AddPart(shell);
            container.Compose();
            shell.View();
 
            Console.ReadKey(true);
        }
    }
 
    public class Shell
    {
        [Import("View")]
        private IShellView _view;
 
 
        public void View()
        {
            if (_view == null)
            {
                Console.WriteLine("view is null");
            }
            else
            {
                _view.Show();
            }
 
        }
    }
 
    public interface IShellView
    {
        void Show();
    }
 
    [Export(typeof(IMyView))]
    class ShellView : IShellView, IMyView
    {
        public void Show()
        {
            Go(this, EventArgs.Empty);
            Console.WriteLine(SomeProperty);
        }
        public event EventHandler Go;
        public string SomeProperty
        {
            set;
            private get;
        }
    }
 
 
    public interface IMyView
    {
        event EventHandler Go;
        string SomeProperty { set; }
    }
 
    public class Presenter
    {
        [Export("View")]
        private IMyView _view;
 
        [ImportingConstructor]
        public Presenter(IMyView view, IModel model)
        {
            this._view = view;
            _view.Go += delegate { _view.SomeProperty = model.Text; };
        }
    }
 
    public interface IModel
    {
        string Text { get; }
    }
 
    [Export(typeof(IModel))]
    class Model : IModel
    {
        public string Text
        {
            get { return DateTime.UtcNow.ToString(); }
        }
    }
}

The thing to note is, that the Export with the key “View” and of type IShel­lView is not pro­vided directly by any type imple­ment­ing the inter­face. Instead it its exported by the pre­sen­ter, as a field that gets set by MEF via con­struc­tor. That way, when the Shell needs the “View” MEF sees that it needs to cre­ate a Pre­sen­ter for that, and in order to cre­ate pre­sen­ter it needs to use the Import­ing­Con­struc­tor, and pro­vide it with IMyView and IModel. Since the type imple­ment­ing the IView is IMyView it gets injected into the Pre­sen­ter. Also, since it imple­ments IShel­lView as well, it sat­is­fies the needs of Shell and gets injected into it.

Pretty sweet, and no code was required to achieve this (except for some Attribute magic).

Tech­no­rati Tags:

.NET 4.0 and Visual Studio 2010

Monday, October 27th, 2008

I’m down­load­ing .NET 4.0 and Visual Stu­dio 2010. Cur­rently it looks like this:

vs2010

It looks like I will have to wait till tomor­row to play with par­tial local types, dynamic objects, and what­ever Anders is announc­ing right in this very moment.

Good night.

Slower than Reflection; meet StackTrace

Monday, October 13th, 2008

I was enter­tain­ing the idea of con­tex­tual com­po­nents that would act dif­fer­ently depend­ing on who called them. System.Diagnostics.StackTrace is the class that allows you to tra­verse the call stack, and see who called your method. There’s one catch though – it is painfully slow. And by painfully, I mean this:

StackTrace

Those two meth­ods are by no means com­pa­ra­ble in regard of what they’re doing. They are mere exam­ples of sim­ple tasks: one involv­ing Reflec­tion, and one involv­ing Stack­Trace. The fact that the dif­fer­ence in per­for­mance is nearly two orders of mag­ni­tude, should make you think twice before you go down the Stack­Trace path. Espe­cially con­sid­er­ing the fact, that you can’t really cache it.

Tech­no­rati Tags: , ,

Framework Tips XI: What is this?

Wednesday, September 24th, 2008

Lately while going through the code of lat­est MEF release, I stum­bled upon a piece of code that used a very lit­tle known fea­ture of .NET

Just take a look:

public struct Tuple<TFirst, TSecond>
{
    public Tuple(TFirst first, TSecond second)
    {
        this = new Tuple<TFirst, TSecond>();//looks strange?
        this.First = first;
        this.Second = second;
    }
    //[...]
}

I myself was shocked at first. “Hey! You can’t assign to this! It’s against the nature and com­mon sense.” Then I went to C# lan­guage spec­i­fi­ca­tion to look for expla­na­tion and indeed I’ve found it.

The key here is the fact that Tuple is a struct, not a class. As it turns out, the mean­ing of this dif­fers between those two.

The expla­na­tion comes from chap­ter 11.3.6 – Mean­ing of this


Within an instance con­struc­tor or instance func­tion mem­ber of a class, this is clas­si­fied as a value. Thus, while this can be used to refer to the instance for which the func­tion mem­ber was invoked, it is not pos­si­ble to assign to this in a func­tion mem­ber of a class.

Within an instance con­struc­tor of a struct, this cor­re­sponds to an out para­me­ter of the struct type, and within an instance func­tion mem­ber of a struct, this cor­re­sponds to a ref para­me­ter of the struct type. In both cases, this is clas­si­fied as a vari­able, and it is pos­si­ble to mod­ify the entire struct for which the func­tion mem­ber was invoked by assign­ing to this or by pass­ing this as a ref or out parameter.

It makes total sense when you think about it, still – I think many expe­ri­enced peo­ple can be sur­prised by that.

Tech­no­rati Tags:

Testing collections with NUnit

Saturday, August 2nd, 2008

How do you test col­lec­tions for equal­ity of their ele­ments? I often used to write my own cus­tom assert for that, some­thing like:

public void AssertCollectionElementsAreEqual<T>(IEnumerable<T> expected, IEnumerable<T> actual)
{
    var first = expected.GetEnumerator();
    var second = actual.GetEnumerator();
    int count = 0;
    while(first.MoveNext())
    {
        if(second.MoveNext())
        {
            Assert.AreEqual(first.Current,second.Current);
        }
        else
        {
            throw new AssertionException(string.Format("Collection has less elements than expected: {0}", count));
        }
        count++;
    }
    if(second.MoveNext())
    {
        throw new AssertionException(string.Format("Collection has more elements than expected."));
    }
}

I thought it’s just plain to com­mon task to not be included in the frame­work itself, so I read the man­ual, and I found CollectionAssert.AreEqual() method that does exactly that.

Then Char­lie Poole, made me real­ize there is even sim­pler way.

using System.Collections.Generic;
using NUnit.Framework;
 
namespace NUnitAreEqualSample
{
    [TestFixture]
    public class CollectionsEqualitySampleTests
    {
        [Test]
        public void DifferentTypesOfCollectionsShoudBeEqualIfElementsAreEqual()
        {
            var list = new List<string> {"foo", "bar"};
            var array = new[] {"foo", "bar"};
            Assert.AreEqual(list, array);//notice this
        }
    }
}

This pro­duces fol­low­ing result:

nunit_areEqual_passed

Sim­ple Assert.AreEqual() does the job. Sweet.

Tech­no­rati Tags: , ,