Category: c#

Framework Tips XII: Advanced .NET delegates

All .NET delegates inherit (indirectly) from System.Delegate class (and directly from System.MulticastDelegate) which has a static CreateDelegate method. The method has two powerful characteristics that are not widely known.

All delegate types are implemented by the runtime. What do I mean by that? Let’s have a look at how any delegate type looks at the IL level:

delegateInIL

All methods are runtime managed, meaning that, in a similar fashion you provide implementation for interface methods, runtime provides implementation for delegate methods. Take a look at the constructor. Regardless of delegate type it always has two arguments: object (on which a method will be invoked via the delegate) and a handle to that method.

While trying (with great help of Kenneth Xu) to find a way of providing proxying of explicitly implemented interface members in Dynamic Proxy, I saw this as a possible way of being able to implement the feature. The problem in this case is, that proxy is an inherited class, that has to call a private method on the base class. So given that Dynamic Proxy works in IL, I tried to call that constructor in IL passing required parameters, but unsurprisingly, runtime does access checks so what I got instead of working delegate was this:

MethodAccessException

 

 

Kenneth suggested another approach – using Delegate.CreateDelegate, because as it turns out, you can successfully use that method to bind delegates to private methods. That is the first important characteristic that may be a life saver in certain 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 compile 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 drawback though – it’s order of magnitude slower than creating the delegate via its constructor. Solution brings us to the second characteristic I wanted to talk about – open instance methods.

Each instance method at IL level has an additional argument, implicitly passed this pointer. Armed with this knowledge, let’s read what MSDN says about Delegate.CreateDelegate and open instance methods:

If firstArgument is a null reference and method is an instance method, the result depends on the signatures of the delegate type type and of method:

  • If the signature of type explicitly includes the hidden first parameter of method, the delegate is said to represent an open instance method. When the delegate is invoked, the first argument in the argument list is passed to the hidden instance parameter of method.

  • If the signatures of method and type match (that is, all parameter types are compatible), then the delegate is said to be closed over a null reference. Invoking the delegate is like calling an instance method on a null instance, which is not a particularly useful thing to do.

This basically says that we can bind method to delegate that passes the ‘this’ argument explicitly, so that we can reuse the delegate for multiple 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 delegate creation only once per lifetime of the type.

I was curious how all these approaches would perform, so I created a quick poor-man’s benchmark.

I invoked an instance method 100 times using four approaches:

  1. directly
  2. via delegate created using its constructor
  3. via delegate created using CreateDelegate passing first argument explicitly (not null).
  4. via delegate created once using CreateDelegate and then reusing it for subsequent 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 performance as when using the delegate’s constructor, which, given we can use in broader spectrum of cases, is pretty amazing.

If you want to run the tests for yourself, the code is here.

Technorati Tags: ,,,

On self-documenting code

Take this piece of code:

public int Count(string text)
{
    Console.WriteLine("Counting...");
    // simulate some lengthy operation...
    Thread.Sleep(5000);
    return text.Length;
}

What’s wrong with it?

It’s not very obvious what the magic number 5000 means? Does it mean 5000 years? 5000 minutes? 5000 the time it takes to run around Main Market Square in Kraków?

Sure, you can hover over the invocation (if you’re in Visual Studio) and see the tooltip

selfdocumentingcode

and see that the number denotes milliseconds, but then you (as well as the junior programmer who will maintain the codebase) have to remember what a millisecond is, and what it means to wait 5000 milliseconds.

The problem is, that millisecond is not the most natural unit of time for humans, so I can assure you that the first thing the aforementioned junior programmer will do when he inherits the code will be “refactoring” it, to this:

public int Count(string text)
{
    Console.WriteLine("Counting...");
    // simulate some lengthy operation...
    Thread.Sleep(5000);// waits 5 seconds
    return text.Length;
}

What this means, is not that junior developer is not very bright – no. Quite the contrary – he would be doing the right thing, only the wrong way. He would be increasing the readability of the code by documenting it. However, he would not have to do that, if the code was self documenting.

So how do we fix that? For example, like this:

public int Count(string text)
{
    Console.WriteLine("Counting...");
    // simulate some lengthy operation...
    Thread.Sleep(TimeSpan.FromSeconds(5));
    return text.Length;
}

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

Castle DynamicProxy tutorial part I: Introduction and ProxyGenerator

I’ve been experimenting lately quite a lot with Castle Dynamic Proxy, creating prototype for a project I’m working on at work and I even implemented a small feature that was missing from it. Generally, Dynamic Proxy (DP from now on) is a great, lightweight framework, but it’s greatest downside is lack of documentation. It’s surprisingly logical and 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 tutorial series of posts, that will introduce various features of DP while working on a simple sample project.

The project is to build the ability to freeze objects, so that from the point in time where object has been frozen, its state cannot change. AFAIK there’s a similar feature in WPF, but since my knowledge of WPF is very limited, I don’t know how that works. The project itself is not important (nor the usefulness of its implementation). It’s only purpose is to serve as an excuse to explore various DP features. I am also aware that the state of the project shown here is far from what good code should look like. We will evolve the implementation in future parts of the tutorial, as we introduce other concepts and features of DP.

Basically here’s what we want to achieve:

  • Be able to use non-frozen freezable 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 freezable object
  • NOT be able to change state of the object after it has been frozen

How do we do that? DP creates a transparent proxy for the real object at runtime for us, and we can intercept the calls to it, and add logic to the objects. This is a very powerful capability.

To specify our requirements, 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.Age = 3;
    pet.Deceased = true;
    pet.Name = "Rex";
    pet.Age += pet.Name.Length;
    Assert.NotNull(pet.ToString());
}

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

    Freezable.Freeze(pet);

    Assert.Throws<ObjectFrozenException>(() => 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);

    var age = pet.Age;
    var name = pet.Name;
    var deceased = pet.Deceased;
    var str = pet.ToString();
}

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

We use static class Freezable to create freezable objects, and to query their state. This allows us to have really simple API (and implementation), and encapsulate all (well, not all – yet) freezable logic in one place. This implementation has one shortcoming that you may have spotted – the class we want to make freezable instance of, has to have a default, parameterless constructor.

This is not a DP limitation however, and further along the way, we will remove it.

The way DP works, is by subclassing given class and overriding its methods. This approach has a few limitations:

  • you obviously can’t proxy a sealed class, since it can’t be inherited from
  • you can only override virtual methods, so for non-virtual methods there’s nothing you can gain

Ok, so how do we go about implementing the whole thing?

First we need some way of tracking which objects are freezable and their freezability state. For that we create an interface:

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

It will help us by providing all the information and functionality we need.

Then, in our Freezable static class we create a dictionary, that will map objects, to their freezability state:

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

With that, implementation of Freezable methods should be really straightforward:

public static bool IsFreezable(object obj)
{
    return obj != null && InstanceMap.ContainsKey(obj);
}
 
 
public static void Freeze(object freezable)
{
    if (!IsFreezable(freezable))
    {
        throw new NotFreezableObjectException(freezable);
    }

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

Still however, no word about DP, and the implementation of MakeFreezable is missing. Also, a reader may point out, that by virtue of keeping some mapping from objects to interface, objects won’t magically gain behaviour.

That is true, with a little bit of work however, they will.

What we need to do, is to monitor calls to property setters, and if object is indeed frozen calling a setter should raise an exception, as shown in the test. To do that we need to actually intercept the call, and for that, we have the IInterceptor interface.

IInterceptor has only one method:

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

The IInvocation is another interface that holds all the information about the call.

dptutorial_1_iinvocation

We can query its Method property to get MethodInfo object pointing to the called method, Proceed method, that invokes the method on target object and few other methods and properties that we will examine in future parts of the tutorial. With that, we have all we need to actually implement our freezable logic:

internal class FreezableInterceptor : IInterceptor, IFreezable
{
    public void Freeze()
    {
        IsFrozen = true;
    }

    public bool IsFrozen { get; private set; }

    public void Intercept(IInvocation invocation)
    {
        if (IsFrozen && IsSetter(invocation.Method))
        {
            throw new ObjectFrozenException();
        }

        invocation.Proceed();
    }

    private static bool IsSetter(MethodInfo method)
    {
        return method.IsSpecialName && method.Name.StartsWith("set_", StringComparison.OrdinalIgnoreCase);
    }
}

Our interceptor holds the freezability state of the object. Since we create one interceptor per object, it will work. In the Intercept method, interceptor checks if the object is frozen, and if called method is a property setter. If indeed that’s the case, it means that we’re trying to set a property of a frozen object, so an ObjectFrozenException is thrown. Otherwise, we can proceed with the call.

Now, it’s really easy to implement Freezable.MakeFreezable method. We know how to intercept calls. The only piece missing is – how do we actually create the proxies. For that, we use the ProxyGenerator class. We only need one instance, so we may keep it as a static field in the Freezable class

private static readonly ProxyGenerator Generator = new ProxyGenerator();

ProxyGenerator class is the heart of the DP library. It has numerous methods for creating different kinds of proxies, but for now, we will only use one: CreateClassProxy, that creates 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);
    InstanceMap.Add(proxy, freezableInterceptor);
    return proxy;
}

We create a FreezableInterceptor to intercept the calls, verify freezability state of the connected object, and throw if necessary, then we create the actual proxy, add it along with its FreezableInterceptor to the dictionary, and return.

In call to CreateClassProxy generic method we pass one more argument – a new instance of CallLoggingInterceptor. It’s a simple class that also implements IInterceptor interface that logs all the intercepted calls to the console. This also means that you can have more than one interceptor for a proxy which is a very powerful and handy capability.

With that, we basically have our initial implementation complete, we only need to create missing exception classes and we are good to go. Indeed, all the tests should pass now.

dptutorial_1_tests_pass

We can create sample console application to see how that works:

class Program
{
    static void Main()
    {
        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)
        {
            Console.WriteLine("Oops. 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 $"Name: {Name}, Age: {Age}, Deceased: {Deceased}";
    }
}

The output of the application looks like this:

dptutorial_1_app

Bam! We get the behavior we wanted, without actually modifying the Pet class, and with surprisingly few lines of code. It may be a little bit overwhelming right now, but what we did, boils down to three things:

  1. We created an IInterceptor implementation, that overrides Intercept method and keeps track of freezable state of an object.
  2. We created a proxy object with ProxyGenerator.CreateClassProxy method
  3. We created really simple logic to correlate out freezable objects with interceptors, that keep their state.

And with all of that we barely scratched the surface of what can be done with DynamicProxy.

As a bonus, if you are curious how the proxy type generated by DP looks like, here’s what Reflector shows:

dptutorial_1_reflector

If the last screenshot left you with headache don’t worry, by the end of this tutorial it will be all crystal clear.

See you in part II, where we will introduce IProxyGenerationHook, to give us more fine-grained control over our interceptors.

If you have any questions or suggestions please, leave a comment.

The solution with tests is available here.

To run tests, you will also need xUnit framework, available here.

Microoptimizations: foreach vs for in C#

Patrick Smacchia wrote a post where he compares execution time while using different patterns to iterate over a collection, namely List<int> and int[]. Since he provided 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 simple, and could easily be inlined.

That said, here are my results (release build ran without debugger, outside of Visual Studio):

iterate

If you compare those to Patrick’s results, you may notice few things:

  • Patrick has a faster PC (which only reminds me I really should start looking for a new one)
  • When you turn off inlining results are much different. First, foreach is as efficient on arrays as on lists (which is different than Patrick’s results. My guess is, that since CLR has more intimate knowledge of arrays, it somehow optimized it when inlining was turned on).
  • iterating with for loop is faster when you do the trick Patrick called “count optimization”. This is quite the contrary to what Eric Gunnerson said, and I’m puzzled about it.
  • DO NOT all go and change your foreaching code to for loops! The numbers you see are number of ticks when iterating over a collection of 100 000 000 elements! That means that in each and every case, iteration is fast as hell, and it’s NOT your bottleneck. To help you visualize that, here’s a picture I borrowed from K. Scott Allen

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

Sorry for the daring topic, but that’s really what comes to my mind when I read or hear people whining about C# loosing purity/object-orientation/strongly-typedness/goal/insert your favorite here, with the advent of version 4.0.

To sum it up, there are four major new areas of improvement coming up with the forthcoming version of the language, as outlined by Charlie Calvert in “New Features in C# 4.0”.

  • dynamic keyword (type) along with all its implications.
  • Optional and named parameters.
  • Co/Contra-variance of generics
  • Few additional features geared towards easing the pain of dealing with COM

I don’t really care about COM, and covariance and contravariance is not really controversial (at most people will grumble that they have to learn how to use it properly), so I’m going to leave those two out, and concentrate on the first two features.

Optional and named parameters wouldn’t probably even make it into the language if it wasn’t for improving interoperability with COM where they are heavily used. And I’m glad they did. Really. Major argument people raise when it comes to them, is that they add no value to the language. Anything you can do with them, you can do with method overloads. Yes you do, but step forward 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 maintain, less code that you’d do probably copy/paste, which attracts bugs like a dead dog attracts flies. And while we’re talking about bugs, think about methods 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 parameters right each time you call them, not mixing the order, and passing localName instead of prefix, or the other way around? Think about how utterly hard to read the code is, especially if you don’t have well named variables you pass as parameters. This can be fixed by explicitly passing each parameter along with its name. And it’s not the case only for methods that take that many parameters. One common mistake I see is in constructors of ArgumentException and ArgumentOutOfRange exception, both of which take parameterName and message as a value, but in different order.

The feature that gets the most bad publicity is the dynamic programming capabilities introduces thanks to dynamic keyword. That’s what makes people lament, that they will no longer be able to rely on IntelliSense and the compiler, and that this is the advent of apocalypse.

Well, rest assured – world will stand tomorrow, just like it stood yesterday. The whole dynamic thing gives you three things:

  • Simplified programming model for things you had to rely on strings (ergo, no compiler checking anyway) in the past, so no harm done here.
  • Improved performance as compared to what you could achieve with reflection thanks to smarter runtime resolution.
  • Less ugly code in those places, thanks to not having to use reflection or any other crazy mechanism to circumvent inability of making dynamic calls.

I hear that you say that this may be abused in the multitude of ways. Well – yes, no compiler or language let’s you stop thinking (and if there were such compilers or languages, we’d be out of job!). That is the case with everything though. C# has support for pointers, you know? It was added to deal with certain narrow range of scenarios, and it was there since v1.0 but I don’t see it used all over the place by anyone. Heck, there are features in the language many experienced developers didn’t even heard about, left alone used them. Example? – stackalloc keyword. Did you know about it? Have you seen actually code that uses it? I haven’t.

You can cut yourself with just about anything. We want more power in the language, but with power comes responsibility. The dynamic keyword hugely helps in certain scenarios, and if used wisely can do you nothing but good.

To wrap it up, I think the whole situation is best described by this quote from Andy Baio:

I’m sure that the moment man discovered fire, there was some guy nearby saying, “Too smoky. Can burn you. Lame.

Technorati Tags: ,

Creating tree of dependencies with MEF

As a follow up to my previous post, here’s the simplified – Console based version of the code.

Disclaimer.

This is a solution. Not the best one, not recommended by anyone, just the one that happened to solve my problem. So take it with a (big) grain of salt, and if you know a better one, use the Leave your comment function 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 IShellView is not provided directly by any type implementing the interface. Instead it its exported by the presenter, as a field that gets set by MEF via constructor. That way, when the Shell needs the “View” MEF sees that it needs to create a Presenter for that, and in order to create presenter it needs to use the ImportingConstructor, and provide it with IMyView and IModel. Since the type implementing the IView is IMyView it gets injected into the Presenter. Also, since it implements IShellView as well, it satisfies the needs of Shell and gets injected into it.

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

Technorati Tags:

.NET 4.0 and Visual Studio 2010

I’m downloading .NET 4.0 and Visual Studio 2010. Currently it looks like  this:

vs2010

It looks like I will have to wait till tomorrow to play with partial local types, dynamic objects, and whatever Anders is announcing right in this very moment.

Good night.

Slower than Reflection; meet StackTrace

I was entertaining the idea of contextual components that would act differently depending on who called them. System.Diagnostics.StackTrace is the class that allows you to traverse 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 methods are by no means comparable in regard of what they’re doing. They are mere examples of simple tasks: one involving Reflection, and one involving StackTrace. The fact that the difference in performance is nearly two orders of magnitude, should make you think twice before you go down the StackTrace path. Especially considering the fact, that you can’t really cache it.

Technorati Tags: , ,