# Friday, January 29, 2010

In WPF, one needs to implement the DependencyProperty pattern to make properties bindable. It usually involves a lot of boiler plate code:

  • adding a static field that names the depency property,
  • adding the instance property to the type (and make sure you follow the naming convention),
  • add validation methods and wire them in the dependency constructor

These are a number steps that need to be done again and again if you are building new WPF controls.

This is where a little transformation using CciSharp really helps with such boiler plate code. Using the DependencyAutoProperty mutator, you can define dependency properties with a single attribute. The rest is taken and validated by the compiler.

The simple scenario: Add [DependencyAutoProperty]


The rewritten code will contain a dependency property for the Value property, and will rewrite the value property getter and setters to use GetValue, SetValue instead.


Supporting default values

Default values can be specified in the DependencyProperty register method, so we want to support this as well through the DependencyAutoProperty constructor.


Supporting validation

Callbacks can be passed in the constructor of DependencyProperty to validate the values of the property. To support this, we use a simple naming convention: if you specify the Validate = true constructor argument, the rewritter will look for a static “Validate” + property name method whose signature is Func<T, bool>, where T is the property type. The rewritter will make sure this method is used – or raise a compilation error if it is missing.


An interresting point here is that the callbacks passed in the DependencyProperty.Register method are untyped (Func<object, bool>) and the user needs to make the appropriate casts himself. This is taken care of by the rewritter:


Have fun!

posted on Friday, January 29, 2010 9:11:50 AM (Pacific Standard Time, UTC-08:00)  #    Comments [0]
# Friday, January 01, 2010

In the previous post the fun of enhancing assertion messages, I eluded about CciSharp… but what is it really?

CciSharp is a post-compiler framework for .NET. (In a sense, it is just a sample of things that can be done with  Common Compiler Infrastructure (CCI) ). CciSharp was designed with the following idea in mind: enable to easily write assembly mutators and integrate them into the build. In that sense, CciSharp provides

  • A minimalistic layer on top of the CCI mutable source model.
  • Provide the MSBuild ‘plumbing’ to integrate into a build so you don’t have to worry about it.

Do you have some Mutators examples?

Are you wondering the kind of problems can you solve with a post-compiler? Let’s take a look at a bunch of example (the full source of those samples is available at http://ccisamples.codeplex.com):

  • Lazy Property: A lazy property computes its result once and caches it. Since it is not supported out of the box by C# or VB.NET, it requires boiler plate code to implement it. I’ve written mutator that takes a property makred with a [Lazy] attribute and implements this pattern. Here’s an example before and after of a property that returns the Environment.TickCount.
    image image
  • Weak Lazy Property: The way we cached the property result above has a dangerous side-effect: it bloats your memory. Instead of storing the result has a ‘hard’ reference, one can use a WeakReference instead. That way, the GC can reclaim the cached references whenever memory pressure becomes too high (the GC is really a great built-in caching mechanism in .NET). Again, it takes a bunch of boiler plate code to implement this pattern, which is generated automatically by the another CciSharp mutator. Here’s another before/after example:
    image image
  • ReadOnly Auto Property: Auto-properties are a great feature of C# but somehow I miss the ‘readonly’ keyword. The best that C# gives us is an auto-property with a private setter, which is not quite the same as ‘readonly’ fields. CciSharp contains a mutator that, given an auto-property with a getter and private setter,  (1) deletes  the setter, (2) makes the backing field readonly and (3) updates all the calls to the setter to direct access to the backing field. That way I get exactly what I want: a truly readonly auto-property. The snippet below shows the before/after transformation.
    image image

Those are a couple scenarios that tools like CciSharp enable. In the next post, we’ll look at the DependencyProperty pattern and how CciSharp can really help there.


posted on Friday, January 01, 2010 10:35:54 AM (Pacific Standard Time, UTC-08:00)  #    Comments [0]
# Wednesday, December 30, 2009

It is holiday time so I could spend some time to play with CCI. The result is a bunch of interesting assembly mutators. Let’s start with the first one: automatic rich assertion messages.

The problem with Assertions

When an assertion fails, the error message is usually insufficient to understand failure. The problem is that we are usually lacking the values in the expression to immediately diagnose the problem. Consider this example,

Assert.True(x == 123);

When this assertion fails, one would like to know what was the value of ‘x’. Of course, that value of x is not serialized in the test output since the assertion method only sees the ‘false’ value. What we would really like to get is something like ‘x (64) != 123’. A number of techniques have been developed to work around this issue.

Solution #1: Specialized Assertions

A common approach is to provide specialized assertion methods with enhanced logging. For example, a special method to test equality:

Assert.Equal(x , 123);

When this assertion fails, the Equal method has the value of both sides of the equality and can render it in the message: ‘expected 123, actual 64’. Unfortunately, expressions are more readable when you write them, and specialized assertions cannot cover all scenarios. This takes us to the next solution.

Solution #2: Expression Trees at Run time

Jafar Husain wrote a very interresting post on how to use Expression Trees to generate rich assertion messages (this is also supported in MbUnit).

Assert.True(() => x == 123);

Instead of taking a bool, the assert method takes an expression tree (Expression<Func<bool>>). Thus, when the expression evaluates to false, the expression tree can be traversed to extract interesting values (such as x) and generate a rich log of the failure.

Unfortunately, there is a major drawback to this technique: what used to be 3 MSIL instructions (ldloc.1, ldc.i4 123, ceq) to evaluate the condition becomes hundreds of methods calls, millions of instructions executed through the System.Linq namespaces. This performance is a overhead on the Pex whitebox analysis.

Jafar considers unit test frameworks as an extension of the compiler and uses expression trees to access what the compiler knows: expression and statements. Following his idea takes us to the CCI based solution.

Solution #3: Assembly Rewritter at Compile time

In the previous approach, expression trees were used to build a little compiler at runtime. A better solution would be to rewrite the expressions at compile time. In other words, we want to build an assembly mutator that takes the original method call and appends code that generates the logging:

Assert.True(x == 123, String.Format(“x == 123 where x = ‘{0}’”, x));

The assembly mutator extracts the expression sources from the pdb (‘x == 123’), collect the local/variable/field references by traversing the expression tree, generate a String.Format friendly message and replace the assertion method call to the assertion method that takes the additional string.

Hello Common Compiler Infrastructure (CCI) and CciSharp

Of course, to rewrite an assembly at compile time, we need a framework that can read and write MSIL, decompile expressions etc… This is where CCI (from http://ccimetadata.codeplex.com ) comes. It allows to manipulate .NET assemblies using an object model and save them back to disk. The assertion message mutator is just one of other mutations that have been or will be implemented as part of CciSharp, a post compiler for .NET that is built on top of CCI.

(There’s already a bunch of useful operators in CciSharp that i’ve been coding over the holidays: assigning the value of auto-properties, making auto-properties readonly or lazy (or weakly lazy), or even implementing the DependencyProperty stuff automatically. We’ll talk about this later.)

Where can I find it?

CciSharp binaries and sources are avaiable on http://ccisamples.codeplex.com/wikipage?title=CciSharp. Grab it!

posted on Wednesday, December 30, 2009 8:45:27 PM (Pacific Standard Time, UTC-08:00)  #    Comments [0]