Category: Framework Tips

How to make sharing code between .NET and Silverlight (a little) less painful

Windsor ships for both .NET and Silverlight. However working with the codebase in such a way that we can target both runtimes at the same  time with the least amount of friction possible proved to be quite a challenge.

Problem

We’re using single .sln and .csproj files to target both runtimes (actually 5 of them, as we ship for 3 versions of .NET and 2 versions of Silverlight, but I digress) with some heavy (and I mean-  really heavy) Jedi trickery in MsBuild by Roelof.

We’re using conditional compilation to cater for incompatibilities between frameworks. For example, SerializableAttribute and NonSerializedAttribute are not present in Silverlight, so many of our classes look like this:

#if !SILVERLIGHT
   [Serializable]
#endif
   public class ParameterModel
   {
      // some code here
   }

This is quite cluttering the code making it harder to read. It adds friction to the process, since I have to remember each time to exclude the attribute from Silverlight build. Even more annoying is the fact, that ReSharper is not very fond of pre-processor directives in code, and certain features, like code clean up and reordering don’t really work the way they should.

Solution

I figured out a way to cut the need to use conditional compilation in this case. So that I can write the code like this:

[Serializable]
public class ParameterModel
{
   // some code here
}

and still have it compile properly under Silverlight, outputting exactly the same code as the first sample. How you ask? – using a not very well known feature of .NET BCL – ConditionalAttribute.

Entire trick works like this: I replicate the Attributes conditionally for Silverlight builds, applying ConditionalAttribute on top of them with some fake condition that never will be true. That way the compiler will not complain when I compile the code, because the attributes types will be defined and visible, however thanks to ConditionalAttribute they won’t be applied to any of my types. To make them not visible to the outside world, I make them internal. Here’s what it looks like:

#if SILVERLIGHT
namespace System
{
    using System.Diagnostics;

    [Conditional("THIS_IS_NEVER_TRUE")]
    internal class SerializableAttribute : Attribute
    {
    }

    [Conditional("THIS_IS_NEVER_TRUE")]
    internal class NonSerializedAttribute : Attribute
    {
    }
}
#endif

I am on a horse.

ConcurrentDictionary in .NET 4, not what you would expect

.NET 4 brings some awesome support for multithreaded programming as part of Task Parallel Library, Concurrent collections and few other types that live now in the framework.

Not all behaviour they expose is… not unexpected thought. What would be the result of the following code:

        
private static void ConcurrentDictionary()
{
	var dict = new ConcurrentDictionary<int, string>();
	ThreadPool.QueueUserWorkItem(LongGetOrAdd(dict, 1));
	ThreadPool.QueueUserWorkItem(LongGetOrAdd(dict, 1));
}
 
private static WaitCallback LongGetOrAdd(ConcurrentDictionary<int, string> dict, int index)
{
	return o => dict.GetOrAdd(index,i =>
										{
											Console.WriteLine("Adding!");
											Thread.SpinWait(1000);
 
											return i.ToString();
										}
					);
}

We call GetOrAdd method from ConcurrentDictionary<, > on two threads trying to concurrently obtain an item from the dictionary, creating it using provided delegate in case it’s not yet present in the collection. What would be the result of running the code?

Surprisingly both delegates will be invoked, so that we’ll see the message “Adding!” being printed twice, not once. This unfortunately makes the class unusable for a whole range of scenarios where you must ensure that creation logic is only ran once. One scenario where I wished I could use this class was Castle Dynamic Proxy and its proxy type caching. Currently it uses coarse grained double checked locking. The code could benefit from more elegant API like the one exposed by ConcurrentDictionary and fine grained locking.

However looks like ConcurrentDictionary is not an option, not unless coupled with Lazy<>, which while I suppose would work, is far less elegant and would not perform so good, since both classes would use their own, separate locking, so we’d end up using two locks instead of one, and having to go through additional, unnecessary layer of indirection.

So the message of the day is – new concurrent classes in .NET 4 are awesome but watch out for issues anyway.

On C# 4, co/contra-variance and generic constraints

While trying to clean up some code today, I stumbled upon interesting result of certain refactoring.

Given the following covariant interface and its implementation:

 

public interface IReference<out T> { }

public class ComponentReference<T> : IReference<T> { }

and the following usage:

public static IReference<IInterceptor> ForType<T>() where T : IInterceptor

{

    return new ComponentReference<T>();

}

the code won’t compile. However, not all is lost – if you cast explicitly, everything will work just fine:

public static IReference<IInterceptor> ForType<T>() where T : IInterceptor

{

    return (IReference<IInterceptor>)new ComponentReference<T>();

}

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

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:

MEF is not a dependency injection framework

Part of a project I’m working on, has strong extensibility requirements, so for last two days I’ve been working on a proof of concept prototype for it, using MEF.

Not only do we need plug-ins, but also there will be at least two client applications using them (one in WPF, and the other one in Silverlight), so we decided to decouple the view of the plug-in from the logic behind it using something along the lines of MVP (Presenter First would be the closest).

That is where I hit the wall. I decorated my classes and interfaces with appropriate Import and Export attributes, to tell MEF how I want it to inject my dependencies, just as if it was a regular dependency injection framework. The problem is, it isn’t, and it took me a while to let this thought drill down into my mind.

I mean – I knew that it’s now, I’ve read the introduction, and even Ayende’s post, but subconsciously I kept thinking of it in terms of resolving dependencies. This was not allowing me to think outside the box, when I hit the wall.

MEF_MVP 

The situation looked like on the picture: I had a shell that contained the collection of View parts (WPF UserControls for WPF client actually, but I’ll refer to it as IShellView) that were the V in my MVP triad. The shell was built up by MEF, and MEF injected the View instance as required. This was however far from what I wanted it to do, because it created only the view, because this was all the Shell (explicitly) needed. This is logical of course, not that it was any consolation for me.

The problem was, as you may have guessed by now, in my wrong approach towards MEF. I was looking along the lines of ISubDependencyResolver, but since it’s not a DI nor IoC framework, there wasn’t any.

When I finally acknowledged it aloud (while talking to a colleague) I created a working solution in a matter of minutes, using field Export, something that no Dependency Injection framework would allow you to do. While maybe not an ideal solution – it works and finally helped me overcome the MEF-as-DI-framework subconscious mindset.

Technorati Tags: , ,

Framework Tips XI: What is this?

Lately while going through the code of latest MEF release, I stumbled upon a piece of code that used a very little known feature 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 common sense.” Then I went to C# language specification to look for explanation 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 meaning of this differs between those two.

The explanation comes from chapter 11.3.6 – Meaning of this


Within an instance constructor or instance function member of a class, this is classified as a value. Thus, while this can be used to refer to the instance for which the function member was invoked, it is not possible to assign to this in a function member of a class.

Within an instance constructor of a struct, this corresponds to an out parameter of the struct type, and within an instance function member of a struct, this corresponds to a ref parameter of the struct type. In both cases, this is classified as a variable, and it is possible to modify the entire struct for which the function member was invoked by assigning to this or by passing this as a ref or out parameter.

It makes total sense when you think about it, still – I think many experienced people can be surprised by that.

Technorati Tags:

Framework Tips X: More on enums

Yes, I know that previous Framework Tips had number VIII, but I didn’t notice that I already had VIII, so this makes this part 10th in the row.

Each enum, is a named collection of flags, that mask a numeric type. For example:

public enum ErrorCodes
{
    FileNotFound = 0x12,
    OutOfDiskSpace = 0x14
}

You could use this enum in an error handling method like:

public void HandleError(ErrorCodes errorCode)
{
    switch(errorCode)
    {
        case ErrorCodes.FileNotFound:
            Console.WriteLine("File not found!");
            break;
        case ErrorCodes.OutOfDiskSpace:
            Console.WriteLine("No disk space left!");
            break;
    }
}

Very simple method, that you can now call from other code, like this:

HandleError(ErrorCodes.FileNotFound);

HandleError method however (as well as ErrorCodes enum, but we’ll get to that in a second) has an issue.

You can call it with code like:

HandleError((ErrorCodes)3);

What now? The cast will succeed (remember that enum is just a mask on an int). You should always put a default clause in such switch, to defend yourself from such malicious input.

 

Now, what will happen if I write:

HandleError(default(ErrorCodes));

What is the default value for ErrorCodes enum? If you keep in mind that ErrorCodes is really an int, the answer is obvious – 0. It is even more obvious, if you notice, that 0 is the only value you don’t have to cast explicitly where ErrorCodes is expected!

HandleError(0); //this will compile
HandleError(5); //this will NOT compile
HandleError((ErrorCodes)5); //this will compile just fine

That’s why it’s always a good idea to have meaningful default value for your enums.

public enum ErrorCodes
{
    NoError = 0,
    FileNotFound = 0x12,
    OutOfDiskSpace = 0x14
}

Technorati Tags:

Framework Tips VIII: Enums and Extension Methods

I have somewhat mixed feelings towards enums in C#. On the one hand, they can greatly improve readability of your code, but on the other hand, they are not much more than textual masks on numeric values. You can’t inherit from them, you can’t use enum as generic constraint (for which I see no good reason), and you can’t extend them… Or can you?

With the addition of Extension Methods in C# 3.0 you finally have the tools to put some life in them. Consider you have an enum like this:

public enum Mp3Player
{
    IPodClassic,
    IPodTouch,
    Zune,
    Zen
}

And you want to extend it to, for example, be able to tell if a player was made by Apple.

private static void Verify(Mp3Player player)
{
    if(player.IsMadeByApple())
        Console.WriteLine("It's made by Apple!");
    else
        Console.WriteLine("Someone else made it.");
}

Now, you can see that I call IsMadeByApple() on a Mp3Player instance. Here’s the piece of code that made it possible:

public static class Mp3PlayerExtensions
{
    public static bool IsMadeByApple(this Mp3Player player)
    {
        return player == Mp3Player.IPodTouch ||
               player == Mp3Player.IPodClassic;
    }
}

There’s no magic here, just a plain extension method, but with it, you can greatly improve readability of your code, by extending your enums with helper methods.

 

Framework Tips VIII: Initializing Dictionaries and Collections

In .NET < 3.5 the only collections you could initialize inline were arrays. So this was legal:

public class CollectionTest

{

    public static readonly ICollection<string> _list = 

        new string[]{"one","two","three"};

}

However if you wanted to have List instead of array, you had to use a trick and pass array as constructor parameter:

public static readonly ICollection<string> _list = 

    new List<string>(new string[]{"one","two","three"});

Not the most elegant piece of code, but at least it works. So far so good. What if you wanted to have a IDictionary instead of ICollection? Well… in this case you’re out of luck, at least partially. To have a dictionary initialized, you’d have to use explicit static constructor, and it means – performance hit. Still, it’s better than nothing.

public class CollectionTest

{

    public static readonly IDictionary<string,int> _dictionary = 

        new Dictionary<string,int>();

    static CollectionTest()

    {

        _dictionary.Add("one",1);

        _dictionary.Add("two",2);

        _dictionary.Add("three",3);

    }

}

But this all was in medieval timessmile_wink. Now, with object and collection initializers you can initialize any ICollection, the way you could with Arrays.

private static readonly ICollection<string> _list = 

    new List<string> {"one", "two", "three"};

This is neat, but even better stuff, is that you can do similar thing with Dictionaries, which means, no explicit static constructor required anymore.

private static readonly IDictionary<string, int>

    _data = new Dictionary<string, int>

            {

                {"one", 1},

                {"two", 2},

                {"three", 3}

            }:

Technorati Tags: