Friday, 5 February 2016

Why TypeInitializationException has Null inner Exception?

This TypeInitializationException occurs when a Type is failed to load because during Type initialization. Normally, When this exception occurs the InnerException property contains the actual exception details about why the initialization failed. But sometime it happens to be Null and so we have Questions about the same.

Let’s take an example –

 class Program


    static Program()


        var initialBootDrive = Directory.Exists("C:\\logs\\BootLogs");



            throw new IOException("Directory does not exist");




    static void Main(string[] args)


      Console.WriteLine("Press any key");



This will cause the exception to occur. Because the static constructors can not be called explicitly but will execute when the Type will be first accessed. In this case the Type will be accessed for initialization.

The above case is special case which I want to discuss in this post. The TypeInitialization will occur with null InnnerException.

There is no “View Detais” options. Moreover if click “Copy exception detail to the clipboard”.

You’ll get this –

System.TypeInitializationException was unhandled Message: An unhandled exception of type 'System.TypeInitializationException' occurred in mscorlib.dll Additional information: The type initializer for 'TypeInitializationExceptionTest.Program' threw an exception.

Not much details. Right? There’s no Inner Exception so you’ll never know what causes this exception to occur.

The reason, is that TypeInitializer of Entry method(Main) class is failed. Since no type was initialized at this very moment, so the TypeInitializer has no type information to report about the failed type in TypeInitializationException.

As explained more by Jon Skeet,Once a type initializer has failed once, it is never retried. The type is dead for the lifetime of the AppDomain. (Note that this is true for all type initializers, not just for types with static constructors. A type with static variables with initializer expressions, but no static constructors, can exhibit subtle differences in the timing of the type initializer execution - but it'll still only happen once.

But if you remove the static constructor from the Entry Type (i.e. Program) to other class and then refer that class in Entry method. you'll get the InnerException on TypeInitialization exception.

static class BootStrapper
    public static bool Initializing;
    static BootStrapper()
        var initialBootDrive = Directory.Exists("C:\\logs\\BootLogs");
        if (!initialBootDrive)
            throw new IOException("Directory does not exist");
    class Program
    static void Main(string[] args)
        // The first access to the class will cause the static constructor to execute.
        BootStrapper.Initializing = true;
        Console.WriteLine("Press any key");

Now if you run it you’ll get the expected behavior.

Final Remark – Keep the Entry (Main) class as clean as possible from Static member or constructor initialization that throws exception.
If necessary either avoid throwing exception, or only throw exception when those member are being accessed in during execution of application.

Monday, 1 February 2016

Create Dynamic Linq using Expressions– Basic to Advance

In previous post we learnt basic understanding of Expression and few insights how Expression represents the code as Data. Also we learn how to compile and invoke an Expression.
In this post you’ll learn

- Creating a simple lambda expression

- Createing a dynamic Linq expression

Before moving ahead I want to mention the MSDN documentation of Expression class to go through for its methods and properties available to build code.

Creationg a simple lambda expression

Let’s take a sample expression which adds up two numbers using a delegate.

Expression<Func<int, int, int>> sumExpr = (a, b) => a + b;

This is how we can write it in the code but it’s possible to build such expressions on the fly. The non-generic Expression class provides a lots of methods and properties.

If we parse this expression, (see previous article) we’ll get something like below:

Parameters = {a, b}

Body = a + b

NodeType = Lambda

So we would need to declare two parameters first. Which we can do like below:

var paramExprA = Expression.Parameter(typeof(int), "a");
var paramExprB = Expression.Parameter(typeof(int), "b");

Now let’s build the body, as we can see the body is a binary operation being performed with add operator. So it will be a binary expression, with Add method and pass those parameters expression to it.

var body = BinaryExpression.Add(paramExprA, paramExprB);

So now we have our parameters and body. Node type will stick them together:

var lambda = Expression.Lambda<Func<int, int, int>>(body, paramExprA, paramExprB);

We have defined the Lambda type as Func with two argument of int and return type int. Then supply the body and parameters expression. And the expression is complete. Now if you look at the lambda in debug mode it will look like exactly that it supposed to be.
Now to execute it, we have to do the same as declared Expressions.

var result = lambda.Compile()(2, 3);

The method can be generalized with generics and then it can be called with any types:

You can call it like:
var res = BuildIt<int>().Compile()(2, 3);
var res = BuildIt<decimal>().Compile()(2.4, 3.5);
var res = BuildIt<string>().Compile()(“Jones”, “Smith”);

I hope you must be comfortable building the expressions, so let’s move on and build a little complex and useful expression which would help reducing the duplicate code.

Creating a simple dynamic Linq expression

Now we have a class ‘TestDemo’ and we want to convert the list of objects of `TestDemo` to another list of objects of class ‘SelectListItem’. This is a class in MVC which represents the items source of HTML Dropdownlist and its very common case. So assuming that we have 10-11 types of such classes like `TestDemo` which would get converted to Dropdownlist to show on view. In real scenario, let’s assume these classes are DbContext entities pulling data from DB and converting them to Dropdownlist compatible objects.

For multiple classes the LINQ would go like:

This code is one of the question from SO. Where the person asked to refactor this code. And ofcourse this looks bit awkward to have same LINQ select criteria repeated to all classes. Now assume if you have such 10-12 classes how the method would look.

So the solution was to create a Generic method which can supply the expression and return the list of ‘SelectListItem’.

Let’s define the signature of the generic method –

public static IEnumerable<SelectListItem> GetList<T>(this IQueryable<T> source)

This is a generic Extension method for IQueryables so it can be invoked via any IQueryable type. And T is the Type of entity on which this will be invoked. In our case T will be TestDemo, TestDemo1 etc..

To start building the expression we will again break it down to it’s expression tree.

i => new SelectListItem { Text = i.Name, Value = i.Id.ToString() };

So we have following items so far:

Parameters = i

Body = new SelectListItem { Text = i.Name, Value = i.Id.ToString() }

NodeType = Lambda

So let’ start with creating the parameters first:

var paramExpr = Expression.Parameter(typeof(T), "i");

Now we’ll create the body as second step. But I’ll discuss the body part in details because it has a couple of things to perform.

- Create a new object of SelectedListItem

- Fill the properties of the object by parameter i.e. i

- Call ToString() method on i.Id property.

First we need information about the properties of both source and target classes which will get mapped during object creation. Below we have used Reflection to get the property info of both classes and create a map so that we can easily identify the mapping between properties.

KeyValuePair<PropertyInfo, PropertyInfo> sourceDestPropMap1
                                = new KeyValuePair<PropertyInfo, PropertyInfo>(
                                    // Text prop of selected item
                                    // Name prop of T class
KeyValuePair<PropertyInfo, PropertyInfo> sourceDestPropMap2
                                = new KeyValuePair<PropertyInfo, PropertyInfo>(
                                        // Value prop of Selected Item
                                        // Id prop from T class


Now let define the property Map first.

var propertyA = Expression.Property(paramExpr, sourceDestPropMap1.Value);
var propertyB = Expression.Property(paramExpr, sourceDestPropMap2.Value);

Since we need to invoke the ‘ToString’ method on second property.

var propertyBToString = Expression.Call(propertyB, typeof(object).GetMethod("ToString"));

Now let’s define the object creation of `SelecListItem` class and property initialization.

var createObject = Expression.New(typeof(SelectListItem));
var InitializePropertiesOnObject = Expression.MemberInit(
                                                    new[] {
                                       Expression.Bind(sourceDestPropMap1.Key, propertyA),
                                       Expression.Bind(sourceDestPropMap2.Key, propertyBToString)

Now we have almost defined the object creation, property initialization and property mapping from parameter Expression of Type T to SelectListItem. The final step is to build the expression.

var selectExpression = Expression.Lambda<Func<T, SelectListItem>>(InitializePropertiesOnObject, paramExpr);

Let’s see how our expression look like with Debugger visualizer.
Well looks good. Now all we have do is supply this express to Select and everything will be done by LINQ. Add below line to invoke the Expression on Select and return the List.

return source.Select(selectExpression).ToList();

Here’s a complete method source,
Now instead of all the if..else from our sample snippet we can simple call this method like:





Similarly you can build any type of Expression and use it for Dynamic Linq. The objects mapping tool Automapper is using Expressions to build dynamic projection to map objects.

Hope you enjoyed reading this post. Don’t forget to like/comment/share about posts to support the blog.

Sunday, 31 January 2016

Beginners guide-Expression Trees in Csharp

Expressions and Func & Action are generic classes and often developers gets confused with them. E.g. which one to use and when. As most of C# developer are familiar with LINQ (Language Integrated Query) so they’re familiar with Lambda Expressions. In this post we’ll not be discussing Func<> and Action<>, Long time back I already wrote a post about LambdaExpression and Delegate templates.
We’ll be focusing on How Expressions is different from Delegate templates and what benefits you can get by learning and getting familiar with it.

Expression Tree

Expression and Expression<> are basically classes that can represent the CSharp code as Data. Really? Yeah really. Unlike Func<> or Action<> Expressions are non-compiled Data about the code. Most of LINQ Providers has been built using Expressions. Let’s get started with a sample Expression and try to understand it.

Walkthrough of a sample expression

Expression can be parsed, analyzed in the program. Have you wondered how Linq to Sql works? How those Linq statements get converted to Sql? How Linq is a deffered execution? Let’s not get into complex example. Let start with “Show me with Code” stuff:

Let’s create a simple Expression:

// A simple delegated operation which perform string join.

Func<string, string, string> StringJoin = (str1, str2) => string.Concat(str1, str2);

Now I want to parse it analyze it or may be doing some more but for that I need to treat this code as Data. Now let’s write an Expression for the above lambda expression:

Expression<Func<string, string, string>> StringJoinExpr = (str1, str2) => string.Concat(str1, str2);

The Expression Tree can be visualize as with it’s major properties:

Let’s analyze our Expression according to above figure, and see what values are populated to understand the break of Expression statement:


So it’s parsed like a tree with NodeType, Left, Right and Body. Which means it can be written as:

Parameters(Left) -> (Root)NodeType -> (Right)Body

Now we have the data, so one can perform operation based on its values. That’s how Linq2Sql works. It analyzes the Expression, Convert the Expression Tree to SQL statements and prepare the query. Expression are major building blocks of any Linq providers.

Compile and Invoke the Expression

Unlike Func<> and Action<> expression are not compile time unit. They need to be compiled before executing the underlying instruction. So to execute the our Expression we must first compile it.

var func = StringJoinExpr.Compile();
var result = func("Smith", "Jones");

or you can write in single statement like:

var result = StringJoinExpr.Compile()("Smith", "Jones");

So we have used Expression to represent a Lambda and it’s body. We looked into the details of how it’s represented as Expression Tree. And how to compile and invoke the code represented by Expression tree.

In the next post we’ll see how to create a custom expression. And how you can build a Dynamic Linq query on the fly?

Thursday, 28 January 2016

Attach process at runtime for debugging in Visual Studio

With Integration tests a common scenario comes into picture. Integration tests always depend on system components e.g. Database, Services etc. If the Integration test is failing un-expectedly then it might require to debug the test including that component which are usually part of the same VS solution. Recently I came across this SO question Question seemed legit because while debugging a test, attaching a process again and again to debug becomes really annoying.
To make dependent components like services, I usually invoke the process to launch e.g. ConsoleApplication project in same solution. Its like simply Add a helper class to invoke the process.

Now in the TestInitialize and TestCleanup methods (I’m using NUnit in this sample code so it would be TestFixtureSetup and TextFixtureTearDown methods) I would start the process and kill the respective process. Here the Integration test is a sample from one of my Github project WCFDynamicProxy. In this Test I’ll be invoking a Dummy service instance hosted in a Console application. Then completion of test just kill the process.

Now, Comes the part to attach this process for debugging. This is pretty tricky one. I found an VS Addin from Visual studio team to attach child process automatically to current debugger but it seems it only works with "F5" debugging.

Then I found this SO post and It really worked amazingly. I have done a little customization to get the process Id as argument:

Note: You need to add the the VS automation library EnvDTE from AddReference -> Extentions. Also the VS version might be different. I was using Visual Studio 2013 so it’s ‘VisualStudio.DTE.12.0’. Change it as per your need.

Now in the ProcessInvoker class Add the call to AttachDebugger utility class after the process launch statement.

When I launched a test for debugging it worked like charm. The process was invoked, attached to VS and was able to debug other process code. You can verfiy it from menu –> Debug –> Attach to process –> Locate the process expected to be attached.

Checkout the working code here. specially WcfDynamicProxy.Tests in the solution. If you like this post please share, like to support this blog.

Wednesday, 13 January 2016

Let’s Try Again!! RetryPolicy using Microsoft Practices Enterprise Library

In today’s software development world almost all applications are connected applications. In some or many ways they’re connected to network based services. Internet is a one of such network and which sometimes is not reliable due to slow connections, timeouts and other connection un-availability issues. This is most important for any application to handle such situations in a graceful manner. Means these things happens and are mend to happen so how application should response to these scenarios without reducing “Reliability” factor.

An example scenario
Let’s take an example of an application which displays some information from an RSS/Atom feed. Now once in a while RSS/Atom host server become un-reachable for a short span of time (Say 10-20 sec.) due to above mentioned reasons. We have couple of options to deal with such situations, Try reading from feed and when there’s an error show the user that feed is not available and try again. User tries again and application successfully reads the feed and displays the information to user. Or Application can retry the fetch operation couple of times and when it’s available displays the information to the User without any user interaction. This depends on business scenario but it increases the Reliability.

A high level view of Retry mechanism

When to apply the Retry mechanism?
In most scenarios at least important read operation can be marked to engage the server with Retry operation for specific errors like network timeout, connection un-reachable etc. Another example that I assume everybody have seen while downloading something from Internet, and connection goes down, browser waits and retry sometime before actually aborting the download.

To introduce this behavior I preferred TrasientFaultHandling from Microsoft Practice Enterprise library. It’s available as individual nuget package so you won’t need to install the whole Enterprise Library monster project. Although you can use any other utility which provides Retry mechanism or implement your own. IMO if something is already there, well tested and optimized then why wasting time re-inventing the wheel.

Installing Nuget package
Add the nuget package TransientFaultHandling.Core in your project to have the required library classes and method available for usage.

Implementing Transient Fault detection policy/strategy
Transient fault/exception are identified as temporary errors and probably can be fixed by retrying the operation. To introduce such types of fault/exception we need to implement the policy/strategy by implementing the interface ITransientErrorDetectionStrategy.

A straight forward usage of Retry utility -
Code Explanation –
The RetryPolicy is a class from TransientFaultHandling namespace.

this.retryPolicy = new RetryPolicy<DownloadFeedTrasientErrorDetectionStrategy>(new Incremental(3, TimeSpan.FromSeconds(0), TimeSpan.FromSeconds(1.5)) { FastFirstRetry = true });

The above snippet is interesting one. Here we’ve used the Generic constructor of RetryPolicy. The class Incremental is RetryStrategy which takes similar arguments as defined in RetryPolicy class constructor.

this.retryPolicy.ExecuteAction(() => this.DownloadFeed(feed_source));

The ablove line shows how the actual network based method call is wrapper with Retry logic. It takes simple void Action delegate which is represented as LambdaExpression.

This is a simplest usage of RetryPolicy. Really easy isn’t it? But this all you need to do to introduce Retry stuff in your application. Who else is using – Entity Framework, Windows Azure service and many other important products is using this library.