Calling private members in unit tests without specifying the name as a string

In my previous post  I mentioned the PrivateObject class to call private fields or properties in unit tests. PrivateObject expects a string to specify the name of the private member.
What bothers me about this approach is that you have to change all the usages of the string if you rename the private property. I hate to put these strings in my code and lose all the compile time advantages, so I went for a different approach.

First of all I created a static generic NameOf class with a method named Member, which accepts a lambda expression pointing to a field or property and returns the name of the field or property.

public static class NameOf<T>
{
    public static string Member(Expression<Func<T, object>> expression)
    {
        var memberExpression = expression.Body as MemberExpression;
        if (memberExpression == null)
        {
            var unaryExpression = expression.Body as UnaryExpression;
            if (unaryExpression == null)
                throw new ArgumentException("memberExpression");

            memberExpression = unaryExpression.Operand as MemberExpression;
            if(memberExpression == null)
                throw new ArgumentException("memberExpression");
        }

        return memberExpression.Member.Name;
    }
}

This already solves the need to use strings when getting the name of a public property with a private setter. The UnaryExpression is used for boolean members, in which the operand delivers us the eventual MemberExpression. Suppose there is an Employee class with a public Property IsActive, but a private setter, then we can fetch the name of the IsActive property like this:

var name = NameOf<Employee>.Member(x => x.IsActive);

But how can we use the NameOf class for private properties or fields? It is only possible to access the properties directly when we use them inside the class, so the only way to expose their names is to declare them inside the class. Suppose the Employee class has a private field lastName, then the name can be exposed like this:

public static readonly string lastNameFieldName = NameOf<Employee>.Member(x => x.lastName);

This is a very invasive way to expose private member names and it doesn’t make your classes look very neat. Let’s clean that up a little.

First of all, the name field can be made internal, so other assemblies can not access it. To use the lastNameFieldName in a Unit Test project I made the internals visible to it by using the InternalVisibleToAttribute in the AssemblyInfo file of the assembly of the Employee class:

[assembly: InternalsVisibleTo("--Your Unit Test assembly--")]

Secondly I wanted to move the private field names to a separate file, the only way to do this (correct me if I’m wrong) is to make use of partial classes. I have made the following directory structure:

UnitTestHelp - Microsoft Visual Studio (Administrator)_2012-05-24_07-29-23

Finally, I declared an internal static class to expose these fields, so the final implementation of my private member partial class for Employee looks like this:

public partial class Employee
{
    internal static class PrivateMemberNames
    {
        internal static readonly string Name = NameOf<Employee>.Member(x => x.Name);
        internal static readonly string lastName = NameOf<Employee>.Member(x => x.lastName);
    }
}

To access the name of the lastName field I can now simply use the following statement:

Employee.PrivateMemberNames.lastName

To make the use of PrivateObject even more simple, I created 2 extension methods on object to get and set private members:

public static T GetMemberValue<T>(this object objectWithMember, string memberName)
{
    PrivateObject privateObject = new PrivateObject(objectWithMember);
    var value = ValidateMemberName<T>(memberName, privateObject);
    return (T)value;
}

public static void SetMemberValue<T>(this object objectWithMember, string memberName, T value)
{
    PrivateObject privateObject = new PrivateObject(objectWithMember);
    ValidateMemberName<T>(memberName, privateObject);
    privateObject.SetFieldOrProperty(memberName, value);
}

Both were made generic, which enables me to work more type safe. The ValidateMemberName method validates if the member your are setting is of the type specified in te generic argument.

To round things up: getting and setting private members on the Employee class now works like this:

employee.SetMemberValue(Employee.PrivateMemberNames.lastName, "Boonen");
var lastName = employee.GetMemberValue<string>(Employee.PrivateMemberNames.lastName);

I find this solution pretty neat, although it is still invasive. You should probably avoid calling private members in unit test code as much as possible. But in a DDD context or when using legacy code you sometimes have no other choice.

I uploaded the source code, together with some basic unit tests to GitHub. Feel free to use it, extend it or comment on it!

Calling private methods and properties in unit tests with PrivateObject

Sometimes you have to write a unit test that has to set a private property or call a private method of an object. When applying DDD, property setters can be made private. Off course you can set them public in some cases, but most of the time there will be a good reason for using private properties or methods and if you are using some external library you simply can’t change the accessibility of the class members.

The most used option I saw in previous projects is to use reflection to call private members. But why should you reinvent the wheel? Since Visual Studio 2005, Microsoft provided us with the PrivateObject class. This class also uses reflection to manipulate private members and has a very simple syntax.

An instance of PrivateObject wraps a ‘normal’ object and exposes some interesting methods:

  • GetField, GetProperty and GetFieldOrProperty provides the value of the private field or property.
  • SetField, SetProperty and SetFieldOrProperty are used to set these values.
  • The different overloads of the  Invoke method allow to call private methods.

As an example I created a simple Calculator class, which  encapsulates a private field _memory. Setting and getting the value of the _memory field by making use of PrivateObject is shown in the following code.

         [TestMethod]
        public void TestCalculatorMemory()
        {
            var calculator = new Calculator();
            var privateCalculator = new PrivateObject(calculator);
            privateCalculator.SetField("_memory", 2);

            Assert.AreEqual(2, privateCalculator.GetField("_memory"));
        }

			

Passing method info with lambda expressions

These days we see a lot of Lambda expressions popping up in code. Lambda expressions are indeed a great way of defining and passing “method information” to other classes and methods. I define them as “method information”, because there are in fact a couple of .NET types that accept a lambda expression as their value.

As an example I want to pass method information about a method, which accepts a string as input parameter and returns a number, as a parameter for another method.
The invocation of this method can look like this:

MethodInvoker.GiveMeTheMethod((s) => s.Length);

But which type can we use for the parameter of this method?

Define the parameter as a specific delegate

The most traditional way of defining the type of the parameter is to create a specific delegate:

public delegate int TheMethod(string parameter);
public static void GiveMeTheMethod(TheMethod theMethod)
{
    int result = theMethod("some string");
}

Define the parameter as a Func Type

Defining specific delegates can be timeconsuming.
Since .NET 3.5 we can make use of Func. This generic type can be used to define a delegate which can accept up to 8 parameters and off course one return type (for void delegates you should use the Action delegate).
The implementations of the method can look like this:

public static void GiveMeTheMethod(Func<string,int> theMethod)
{
    int result = theMethod("some string");
}

Define the parameter as an Expression Tree

I will not go in detail on Expression Trees. You can read a lot of articles about this already.
If we define the method parameter as an Expression type, the method definition could look like this:

public static void GiveMeTheMethod(Expression<Func<string, int>> theMethod)
{
    int result = theMethod.Compile()("some string");
}

You just wrap the Func delegate in an Expression object (you could also pass a specific delegate off course).
The Compile method converts the Expression Tree to a delegate, which we can invoke.
So, why should we use an Expression Tree? There are probably a lot of reasons, but for me the following 2 reasons are the most important.

  • You want to get the name of the method or property, which is used in the lambda expression without executing it. This is used to implement a type safe PropertyChanged notification method.
    On an Expression type you can call the Name property to achieve this information.
  • If you have a reference in to the input argument of your method, but the argument is not yet instantiated at that moment, you have to use an Expression Tree. If you use a delegate type, this will throw a null reference exception, because it expects an instance of the object to retrieve the pointer to the method of this object.

How to mess up Visual Studio intellisense: a recipe

The next blog post is just a fun post which shows how you can totally mess up the intellisense in Visual Studio.

Result

So what do we want to achieve in this recipe?
Have you ever seen your intellisense displaying a list like this one?

Mess up result

No, dear reader, you are not drunk: FirstName and LastName are displayed twice in the intellisense suggestions.
Let’s see how we can produce this strange behavior.

Step 1

Start by creating two classes that both have a FirstName and a LastName property. In this case I created an Employee and a Person class. The Employee class also has a MiddleName property.
All properties are of type string and the Employee and Person class are in the same namespace.

Employee and Person class

Step 2

Create a (static) class which has two methods with the same name.  Both methods expect one parameter of a generic Func type (or a delegate) which returns a string. The first method wants a first parameter of type Person, the other one expects an Employee as first parameter.
I ended up with the following static MessUp class:

  
public static class MessUp
{
      public static string HereYouGo(Func<Person, string> pFunction)
      {
           //Do something here     
      }
      public static string HereYouGo(Func<Employee, string> eFunction)
      {
          //Do something here
      }
}

  

Step 3

The only thing we now have to do is call the HereYouGo method on the MessUp class (or whatever you called it) and pass the generic Action with a lambda expression.

So start with typing something like this:

MessUp.HereYouGo(whoAmI => whoAmI.)

If you arrive at the dot after whoAmI, the compiler still doesn’t know which method it needs to call: both methods have the same name and at the moment of typing the dot to address a property of Employee or Person, the compiler has no clue which type you want to use, so it just displays all the properties of both types, which is pretty weird off course!

If you select the FirstName property, you cannot compile this code, because the compiler doesn’t know which FirstName property (the Employee.FirstName or the Person.FirstName) it must use.

Ambiguous reference for FirstName property

So how can we produce a work around for this issue?

  • Use property names which are not present in both classes: in this case the Employee.MiddleName property will not pose any problem for the compiler.
  • Define a strong typed method in which you fetch the desired property:
     
    private static string EmployeeFirstName(Employee employee)
    {
        return employee.FirstName;
    }
               

    Then you can just rewrite the code like this (no lambda expression needed):

    MessUp.HereYouGo(EmployeeFirstName); 

Microsoft TechEd Europe 2010(#tee10): my report

After being at Microsoft TechEd Europe for the second time in Berlin,
it’s time for a report and now I can also make a comparison with my previous TechEd.

Location and organization

As cities usually don’t change a lot in one year, I didn’t spend a lot of time in the Berlin city center this year, but Berlin is still a nice city.
Messe Berlin is still huge, but Microsoft did a better job this year to point attendees in the right direction with arrows and signs all over the place. The organization was definitely great, but the goodie bag of this year was a big disappointment, compared to last year. Also the food wasn’t always what it should be.

The keynote

One advice I can give to a developer after following the TechEd keynote for the second time is: don’t go there!
About 90% of the keynote contains IT pro content. As a developer I remember only one word from this year’s keynote: the Cloud! Microsoft wants to deliver Software as a Service (SaaS), Infrastructure as a Service (IaaS) and Platform as a Service (PaaS).

Sessions I followed

This year I didn’t schedule a lot of sessions in advance as I always made last minute changes to my planning.
I also didn’t write recaps of the sessions this year as anyone can view them online for free.
List of sessions I followed (mainly in the development track) with links to the online screencast:

November 9

November 10

November 11

November 12

Awards

To review the sessions I followed from a different approach, I invented awards (just to be clear: these awards are just fictions, nobody will receive some kind of price 🙂 )

Killer session award

This award rewards the session with the best overal content. This one goes to:

WEB401 – Code Like a Pro: Tips, Tricks and Techniques for Writing Killer Silverlight Applications (Jeff Prosise)
This session contains everything a good session at TechEd needs to have:

  • Really nice content: I saw some Silverlight features I never heard off.
  • Outstanding speaker: I was already convinced from Jeff Prosise’s speaker skills last year and this year he did another great job!

Go home session award

This award points to the most boring or annoying session I attended:

ARC303 – Architecting Claims-Aware Applications (with the Windows Identity Foundation and Active Directory Federation Services) (Dominick Baier)
I just found this session very boring. Maybe this is due to my lack of knowledge of WIF, but I also have my doubts about Dominick Baier’s speaker skills.

Fun session award

This one is for the session with the most pleasant content or most funny speaker:

WEB201 – Nine Things I Hate About your website (Pete LePage)
Pete LePage must have a great job at Microsoft, looking for the most ugly and inefficient websites on the internet. Laughing with another one’s crappy website: I must admit it was fun!

Murphy session award

We all know Murphy’s law, so this award is for the session where a lot of things went wrong:

ASI201-LNC – Windows Workflow Foundation Futures (Ron Jacobs)
A lot of things went wrong in this session:

  • Ron Jacobs got lost in Messe Berlin, which caused this session to start 5 minutes to late
  • When connecting to his remote desktop machine in Redmond, the internet connection just seemed way to slow!
  • Some demos from PDC couldn’t be showed, because they were already working with a new build of WF.
  • A lot of ugly messages popped up when opening new examples of Windows Workflow Foundation

Belgian session award

As there is a little chauvinism left in me, I must have an award for the best Belgian session at TechEd:

WEB311 – What You, as an ASP.NET Developer, Need to Know About jQuery (Gill Cleeren)
This one was easy of course, because I only went to 1 Belgian session at TechEd (I don’t know if there were others?) I must say this was definitely a really interesting session if you want to have some basic knowledge about jQuery. There are not a lot of speakers who have filled their rooms completely at TechEd and did their session for a second time!

Euricom, here I come!

The hardest thing about blogging is keeping your blog up to date!
I must say I wasn’t a good blogger the last months. But, guess what, I have some good reasons!

First of all I had a really nice vacation, travelling all around the USA for 4 weeks.
I’ve visited some big cities (Seattle, Salt Lake City, Las Vegas, San Francisco,…) and national parks (Yellowstone, Canyonlands, Death Valley, Yosemite,…).
And yes, I also took a look around at the Microsoft campus in Redmond, which was definitely not the most interesting place to visit in the United States (sorry Microsoft people 🙂 )


After my vacation I  almost immediately started looking for a new job. Because I wanted to increase my technical knowledge about the latest Microsoft technology, I decided to look for a job in consultancy. Among 6 other companies who liked to offer me a new position, I chose Euricom. Euricom is located in Mechelen and only hires senior Microsoft consultants. I will not only be able to work with some of the best .NET professionals in Belgium, also a high-tech programming environment lies in front of me. I’m really looking forward to this new challenge, which will start at the end of November.
As an advanced .NET developer you will probably find me participating in top .NET projects in Belgium.

Visual studio Tip #5: “Surround with…” in ASP.NET 4.0

As an ASP.NET developer, you certainly found yourself in the following situation.
You have a number of mark-up elements in your page which should be hidden/updated/… all at once.
The solution is to put them in a panel or updatepanel.

In previous versions of Visual Studio you had to manually type the tags to surround your mark-up with, causing a lot of copy pasting and scrolling sometimes.
Visual Studio 2010 now offers the “Surround with…” option in your ASP.NET mark-up.
We already knew this feature from VB.NET or C#.

Let’s say you have a panel which has to be placed in an updatepanel:

After selecting the panel mark-up you can right click on it (or use the shortcut CTRL + K, S) to show the following context menu:

You can chose which snippet needs to be used for the surrounding.
Selecting the “updatepanel” snippet gives the following result:

It’s just a small feature, but it should already have been in Visual Studio for a long time!

Visual studio tip #4: Generate method stub in VB.NET 2010

I am not a big fan of VB.NET, but for some reasons I will not explain in this post, I have to code in it (lucky me 🙂 ).
Microsoft is always claiming that C# and VB.NET are equally evolving, but some changes only appear in VB.NET one or more releases after they have been implemented in C#.
In C#, previous versions of Visual Studio already offered the ability to generate a method definition that didn’t exist already.
In VB.NET you had to write your method stubs first by yourself.
The little dash that appeared under your method didn’t know what to do with it in Visual Studio 2008:

Visual Studio 2010 now offers a change. Typing CTRL + . or clicking on the little dash now results in this:

When you click on generate, this results in a method definition which is basically the same than in C#:

I was always wondering why Microsoft didn’t implement this feature in previous releases, but finally it’s there!
Only one thing that annoys me is that the little dash doesn’t pop up directly while you are typing, as in C#.
If you are coding VB.NET you have to put your have to move your cursor to another line (or something else that changes the focus of the current line)   before Visual Studio wants to help you.
As I work in a mixed environment, I must say the intellisense and little help features as the one described above are still better implemented in C#, but you can’t always compare both languages as the syntax is totally different.

Office 2010: choose your default open standard

Where Office 2007 introduced Microsoft’s new Open XML format, Office 2010 (which RTM’d last week) goes even further in its support for open standards.
When you first open an application from the Office 2010 suite: the following window appears:

Microsoft definitely adds more flexibility with this feature, enabling Open Office users to open their ODF files in Microsoft Office and vice versa.