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

Error 1001: Service has been marked for deletion

Another of those stupid windows errors!

I was working on this windows service recently. While developing this I code the changes, build the app and run the service installer. (The service installer project is quite cool. I admit). But every now and then when I uninstall the service and try to reinstall it I get this error:

Error 1001: Service has been marked for deletion

I know its marked for deletion. But why is it not deleted yet? I used to restart the system as a solution to this problem. But soon enough I began to see the stupidity behind some of the windows apps. I had the Service Control Manager running to start/stop the service. After uninstalling the service if you happen to open the SCM window, it gets a lock on the service entity and marks it as ‘Disabled’. Now when you try to install the service again Error 1001 pops up.

The solution to this was to just close the SCM and install the service. SCM is one of the core windows utilities. You expect it to behave right?

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);
    }
}