Unity – per thread lifetime manager

While working with multi-threaded applications build over a DI framework it would be extremely useful to have objects that are specific to the context of a thread. My most favorite IoC framework, Unity, provides awesome lifetime managers that can be used to handle situations like these.

Scenarios

The most common scenario where I came across this is to group application logs by a specific thread. Each thread does a specific job and I wanted to prefix specific attribute to the log. A smart lazy person would probably just start logging the thread ID. I know that is quite simple for you to understand the logs. But when a somewhat non-technical person (project managers) wish to see the logs, you might want to make the logs more meaningful.

I once worked on this application that performed a lot of calculations on separate threads. A complex calculation was forked into multiple threads. I wanted to store the output for reuse within a thread. (Lets skip the nitty-gritties of
the app). In that situation a ‘PerThreadStore’ came in extremely handy.

ThreadStatic attribute

There is a very simple way to create thread specific properties. Just use the [ThreadStatic] attribute. Quite common among the multi-threaded developers. But using this as an extension of your IoC framework makes the application quite cool to develop.

PerThreadLifetimeManager with Unity

    /// <summary>
    /// Extends the LifetimeManager to define a class that provides a lifetime per thread
    /// </summary>
    public class PerThreadLifetimeManager : LifetimeManager
    {
        /// <summary>
        /// Overridden method that returns the value of the stored object
        /// </summary>
        /// <returns>The value of the object</returns>
        public override object GetValue()
        {
            return PerThreadStore.Item;
        }

        /// <summary>
        /// Overridden method that removes the value for the stored object
        /// </summary>
        public override void RemoveValue()
        {
            PerThreadStore.Item = null;
        }

        /// <summary>
        /// Overridden method that adds a value to the stored object
        /// </summary>
        /// <param name="newValue">The value to be stored</param>
        public override void SetValue(object newValue)
        {
            PerThreadStore.Item = newValue;
        }
    }

    /// <summary>
    /// A store that stores a static object that has a single value per thread
    /// </summary>
    public class PerThreadStore
    {
        [ThreadStatic]
        private static object _Item;

        /// <summary>
        /// Gets or sets any value to be stored per thread
        /// </summary>
        public static object Item
        {
            get
            {
                return _Item;
            }
            set
            {
                _Item = value;
            }
        }
    }

Peace

System.Xml.XmlSerialization – Assembly bind failure (MDA Error)

When Im debugging my application I ask Visual Studio to throw all exceptions in my code. (I do this by checking everything in Debug > Exceptions) It seems like a good thing to have while debugging applications – to know the exceptions you’re getting even if you’re catching them and handling them. This setting in combination with the use of System.Xml.Serializers seems to constantly throw this error in my application:

System.Xml.Serialization assembly binding failure

This gets annoying after a while as my code seems to be perfectly alright, no errors, but this window keeps popping up at this line:

XmlSerializer xmlSerializer = new XmlSerializer(type);

I looked at the error in detail and it seems to be looking for an assembly named My.Namespace.XmlSerializers. Of course there’s no such assembly and the compiler will get a System.IO.FileNotFoundException. The best solution I could Google out was to uncheck the BindingFailure and prevent the exception from showing up every time.

This worked only in stopping me from getting annoyed, whenever that error showed up, but I knew there still was some error and it was being handled somewhere! I had to figure out what was going on…

Enter Reflector (Now a RedGate product. An addition a cool line up of .NET tools)

I have a trial version of Reflector on my machine and this is an excellent opportunity to figure out what in the world is happening in System.Xml.Serialization. I disassembled the entire System.Xml assembly and searched for the keywork ‘XmlSerializers’.

Looks like there is code to generate a custom assembly to handle type passed to the current serializer. Every call to this creates this assembly in a temp location and runs the deserialization through this assembly. There seems to be multiple options for the ‘temp location’ to generate this assembly. Once the assembly is generated, it is delay loaded at runtime. During this the assembly loader searches for all the possible temp locations and each time it fails to find the assembly in one of the temp locations, it throws a FileNotFoundException. This exception is rethrown as a bind failure.

So… I don’t know why the serialization/deserialization logic needs to be this complicated. But, in case of the core .NET library, it just is. I also have noticed that the memory footprint of System.Xml.Serialization classes to be quite big. This whole process of creating a temp assembly probably adds to it. I know there are better solutions for XML deserialization out there. I will soon get onto searching for one and evaluating it against System.Xml.Serialization methods. I’ll add an update to this post when I do find one (eventually…)

In conclusion, System.Xml.Serialization classes and methods are an expensive way to serialize objects to XML or to deserialize XML to objects. This throws a BindingFailure exception as the library internally uses a try catch to handle delay loading a temp assembly. Though this code is internal to the assembly, this error shows up if we enable throwing all exceptions as the delay load is happening in the context of our application.

So, the best solution to avoid (seeing) this error is what’s been suggested by many – in Visual Studio uncheck BindingFailure in Debug > Exceptions under ManagedDebuggingAssistants

Get current application directory

Often when I write apps, I come across a situation where in I need to store some temporary files. Say, I need to run a command through System.Diagnostics.Process. This command requires a path to store the output as a file though an /o: parameter. For ages I used to use Assembly.GetExecutingAssembly().Location to get the directory of the current app.

This often gets very hairy as the current executing assembly will change if you are invoking your application through an external service. Running unit test cases on this app gets trickier as testing frameworks like NUnit create temporary DLLs at temporary locations. I saw this post that uses Assembly.GetExecutingAssembly().CodeBase to make the application behave better.

Simple code but very effective:

static public string AssemblyDirectory
{
    get
    {
        string codeBase = Assembly.GetExecutingAssembly().CodeBase;
        UriBuilder uri = new UriBuilder(codeBase);
        string path = Uri.UnescapeDataString(uri.Path);
        return Path.GetDirectoryName(path);
    }
}

Configuring WCF services programmatically for Silverlight

So, like always there was this rather strange problem I came across a couple of days ago. For most normal applications I would be more than happy to just configure my WCF services in the web.config/app.config file. The annoying XML for System.ServiceModel has become quite friendly with me. But the situation now was that I was working on a silverlight application and I had to modify the binding dynamically. Some crazy requirements require my Silverlight application to start using a different service endpoint based on some internal events. The first thing I had to do was shoot out the idea of having the nice friendly config file, delete it off my project and create a code to generate an impromptu binding each time the service is requested.

My normal way of creating a binding configuration is to set all the string and buffer lengths to maximum. (Atleast, the application Im working on requires this). One of the important things that need to be set to max value is the ReaderQuota:

[XML config sample]

So I tried to do this programmatically and guess what?! In Silverlight the XmlDictionaryReaderQuotas object that is required to define the ReaderQuota cannot be instantiated. Now, how the heck am I supposed to create it? Not just that, there is not direct way to set the “ReaderQuota” property of the BasicHttpBinding. The only way to set that property is to use Reflection!

First of all creating a decent configuration file in Silverlight is a pain and on top of that you can even set the values programmaticaly. Were the creators of Silverlight 4.0 drunk when they designed the configuration module?

Anyway, here is how you set up the ReaderQuotas with “MAXIMUM” reader sizes for a WCF binding in Silverlight:

BasicHttpBinding binding = new BasicHttpBinding(BasicHttpSecurityMode.None);
binding.CloseTimeout = new TimeSpan(00, 05, 00);
binding.OpenTimeout = new TimeSpan(00, 05, 00);
binding.ReceiveTimeout = new TimeSpan(00, 05, 00);
binding.SendTimeout = new TimeSpan(00, 05, 00);
binding.TextEncoding = System.Text.Encoding.UTF8;
binding.MaxReceivedMessageSize = int.MaxValue;
binding.MaxBufferSize = int.MaxValue;             

binding.GetType().GetProperty("ReaderQuotas").SetValue(binding, XmlDictionaryReaderQuotas.Max, null);

Hopefully this will help someone out. In fact it was not that tough to Google this solution out, but the implications of this solution just irked me into writing this post.

Extending C# Object to make safe type-conversions

In C# one of the most commonly used convert functions is the Convert.To<Type>(object value). Usually when we need to convert an object to a string we just use .ToString() as its to easy to use. But the problem with ToString is that it cannot handle nulls, DbNulls, etc. To handle this, we can very easily extend the methods associated with the C# Object.

To do this all you need to do is create a Static Class, and have Static Functions where the first argument is the type of object that you want to extend. Here’s how its done:

public static class Utils
{
    /// <summary>
    /// Converts an object safely to string or assigns an empty string
    /// </summary>
    /// <param name="obj"></param>
    /// <returns></returns>
    public static string ToStringSafe(this Object obj)
    {
        try
        {
            return Convert.ToString(obj);
        }
        catch
        {
            return null;
        }
    }

    /// <summary>
    /// Converts an object safely to integer or assigns 0
    /// </summary>
    /// <param name="value"></param>
    /// <returns></returns>
    public static int ToInt(this Object obj)
    {
        try
        {
            if (obj.GetType() == typeof(int?)) return ((int?)obj).Value;
            if (obj.GetType() == typeof(DBNull)) return 0;
            return Convert.ToInt32(obj);
        }
        catch
        {
            return 0;
        }
    }

    /// <summary>
    /// Converts an object safely to bool or assigns false
    /// </summary>
    /// <param name="value"></param>
    /// <returns></returns>
    public static bool ToBool(this Object obj)
    {
        try
        {
            if (obj.GetType() == typeof(bool?)) return ((bool?)obj).Value;
            if (obj.GetType() == typeof(DBNull)) return false;
            return Convert.ToBoolean(obj);
        }
        catch
        {
            return false;
        }
    }
}

Once this is done, you can do things like this easily:

NOTE: You CANNOT use this concept to extend instance methods. In the above sample I could not extend the .ToString() method, so I used a new name called ToStringSafe(). The reason is that instance methods have a higher priority than extension methods. Because of this, all the compiler will use the instance method even if there is a matching extension method. (You cannot use override functions here)

Starting Prism in Silverlight

So I got my hands onto Prism and I found it extremely intriguing. I created a bunch of applications on that and its been a fun learning experience. Though its very interesting, the scarcity of reference material on Internet forced me to create a tutorial here.

There will be a couple of posts on this following this one. I’ll update the links to them later on.


The following code is rough and can be ignored completely
xmlns:Regions=”clr-namespace:Microsoft.Practices.Composite.Presentation.Regions;assembly=Microsoft.Practices.Composite.Presentation”

Custom event handlers in C# (3.5 style)

Here is a code for custom events in C#. Note the 3.5 style code that involves Lambda expressions and Anonymous types.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    using TestNamespace;

    class Program
    {
        static void Main(string[] args)
        {
            Test t = new Test();

            t.TestStarted += (object sender, Test.TestStartedEventArgs e) =>
                {
                    Console.WriteLine("First event handler");
                    Console.WriteLine(sender.ToString());
                    Console.WriteLine(e.ToString());
                };

            t.TestStarted += (object sender, Test.TestStartedEventArgs e) =>
                {
                    Console.WriteLine("Second event handler @ " + e.StartedTime);
                };

            t.DoTest();

            Console.ReadLine();
        }
    }
}

namespace TestNamespace
{
    class Test
    {
        public delegate void TestStartedHandler(object sender, TestStartedEventArgs e);

        public event TestStartedHandler TestStarted;

        public class TestStartedEventArgs : EventArgs
        {
            public string StartedTime { get; set; }
        }

        public void DoTest()
        {
            if (this.TestStarted != null)
            {
                this.TestStarted(this,
                    new TestStartedEventArgs
                    {
                        StartedTime = DateTime.Now.ToString()
                    });
            }
        }
    }
}