# Wednesday, June 16, 2004

This is a preview of a new Addin in the next Reflector.Graph release: Type Tree Map.

A TreeMap is special 2D visualzation of a tree. Since, Reflector provides a tree (Assembly -> Module -> Namespace -> Type -> Members), I wondered if it was possible to visualize with a TreeMap. In .Net, there are 2 controls available that can render treemaps:

I decided to use the later for creating the addin.


Note (1): The nodes represent each part of the type tree from assembly to the class members. Each node is clickable and brings the tree focus to the clicked element.
Note (2): Look at the treemap, and image the nodes are you Namespace/TestFixture/TestCase hierachy. Failed test in red, successfull test in green. Just imagine, that would be the ultimate progress bar for MbUnit!
Note (3): Thanks to Jamie (NUnitAddin) for the idea sharing on this.

posted on Wednesday, June 16, 2004 12:52:00 PM (Pacific Daylight Time, UTC-07:00)  #    Comments [2]

Jamie Cansdale, NUnitAddIn man, pointed out to me that I was cited (very briefly) on .Net rocks.  Here's the summary

John and Barry talk with us about Test-Driven Development, Unit Testing, and other aspects of Extreme Programming that are being used today. We had given lip service to unit testing in past shows, but John and Barry were able to explain the benefits as well as the how-to of test-driven development

http://www.franklins.net/dotnetrocks/, number 67, at 1:27 or so. This deserves a couple beers for me.

posted on Wednesday, June 16, 2004 12:36:00 PM (Pacific Daylight Time, UTC-07:00)  #    Comments [7]
# Tuesday, June 15, 2004

This entry is a little tutorial on how to write your own Reflector Addin. For the past weeks, I have been playing a lot with those and Lutz Roeder was backing me up on MSN for quick questions, so it's my time to return him the favor and write a tutorial about it. So let's get started.A Reflector Addin is basically only a control that gets notified when the browser changes of active items. Of course, the tricky part is to "inject" your Addin into Reflector and to "clean" up when it is unloaded. Once, you're addin is injected, the control you provided takes care of the rest. I will not focus on writing controls here but rather on the procedure to load and unload packages.

Reflector API is rather big, so this tutorial is just the "immerged" part of the iceberg.

Quick Semantics

In Reflector, an Addin is called a Package (IPackage interface). Each package can add multiple Windows (IWindow), which are the control appearing on the right, can add CommandBar items (ICommandBarItem, ICommandBarButton) to the context menus, and attach listeners to the event trigerred when the AssemblyBrowser changes of ActiveItem (IAssemblyBrowser.ActiveItemChanged). The ActiveItem is the item selected in the reflection tree.

Building a simple package (hard way)

The IPackage interface is defined as follows:

public interface IPackage
   void Load(IServiceProvider serviceProvider);
   void Unload();

As may already know, the Reflector API is exposed through a set of interfaces. The actual implementations are obfuscated. The IServiceProvider instance is a "facade" against the implementations and can be used to retreive IAssemblyBrowser instance (and others). 

The Load method is where you will inject your Addin, while the Unload method is for cleaning. Implementing IPackage is rather boring and bug prone because you need to track all the window, menu item, etc.. that you inject to later remove them. Forgetting to remove a menu item is likely to happen often if you are in a rush. Moreover, using the serviceProvider is verbose in the sense that you access elements through a dictionary:

IAssemblyBrowser ab = (IAssemblyBrowser)serviceProvider.GetService(typeof(IAssemblyBrowser));

Let's implement a small package that displays a text box for assemblies. As mentionned above the steps are:

  • create your control and add it to the IWindowManager instance (retreive from serviceProvider),
  • add menu item and event handler,
  • set control to visible when menu is clicked,
  • add IAssemblyBrowser.ActiveItemChanged handler in your control
  • Don't forget to prepare cleaning up!

The control: this control display the name of the assembly, otherwise nothing.

public class AssemblyNameWindow : TextBox
    private IAssemblyBrowser assemblyBrowser=null;
    public AssemblyNameWindow()
        this.Dock = DockStyle.Fill;
    public IAssemblyBrowser AssemblyBrowser
            return this.assemblyBrowser; 
            if (this.assemblyBrowser!=null)
                this.assemblyBrowser.ActiveItemChanged -= new EventHandler(activeItemChanged);
            this.assemblyBrowser = value;
            if (this.assemblyBrowser!=null)
                this.assemblyBrowser.ActiveItemChanged += new EventHandler(activeItemChanged); 
    private void activeItemChanged(Object sender, EventArgs args)
        // testing if current item is an assembly
        IAssembly assembly = this.assemblyBrowser.ActiveItem as IAssembly;
        if (assembly!=null)

And now the package, which creates a window, and some menu items:

public class AssemblyNamePackage : IPackage
    private IWindowManager windowManager=null;
    private ICommandBar assemblyMenu=null;
    private ICommandBarButton button=null;

    public void Load(IServiceProvider serviceProvider)
        IAssemblyBrowser assemblyBrowser = (IAssemblyBrowser)serviceProvider.GetService(typeof(IAssemblyBrowser ));

        // create window
        AssemblyNameWindow anw = new AssemblyNameWindow();
        // inject window into reflector
        this.windowManager.Windows.Add("AssemblyName",anw,"Assembly Name");

        // create menu item and attach handler
        ICommandBarManager cbm = (ICommandBarManager)serviceProvider.GetService(typeof(ICommandBarManager));
        // get assembly context menu
        this.assemblyMenu = cbm.CommandBars["Browser.Assembly"];
        // add button
        this.button = this.assemblyMenu.Items.AddButton("Assembly name",new EventHandler(button_Click));

    public void Unload()
        // remove window
        // remove button
    private void button_Click(Object sender, EventArgs args)

That's it. You have built your first Reflector Addin:

Now this is a lot of code to get thigs up and moreover, it is quite errorprone, so let's us another easier method.

Building a simple package (easier way)

This solution uses a few classes that I have written in order to handle all the "load/unload" code. The new way is mainly based on custom attributes. [Update:]Firstly, you need to make your controls implement IServiceComponent where you can register to Reflector events:

public class AssemblyNameWindow : UserControl, IServiceComponent
    private ReflectorServices services = null;
    public ReflectorServices Services
       get { return this.services;}
            if (this.services!=null)
            { ... (detach events)}
            this.services = value;
            if (this.services!=null)
            { ... (attach events)}

For example, the AssemblyPackage is rewritten as follows:

public class AssemblyPackage2 : BasePackage
    [ReflectorWindow(Caption="Assembly Name II")]
    private AssemblyNameWindow assemblyName = new AssemblyNameWindow();
[Updated: no need to implement a property]
[Updated: no need to implement Load anymore]

This looks much nicer. BasePackage will self inspect and load all properties tag will ReflectorWindow attribute. For each one of those, it will add a menu entry to the corresponding menu using the information in ReflectorCommandBar attribute. A property can have multiple command bar targets and a package can have multiple windows. The example above gives as expected a new menu item:

Where's that package ?

The helper classes are not part of Reflector but you can get them from the MbUnit CVS (look in Samples/Reflector.Graph direcotry).

posted on Tuesday, June 15, 2004 10:12:00 AM (Pacific Daylight Time, UTC-07:00)  #    Comments [6]
# Sunday, June 13, 2004

This release was sick so I removed from the server...

There is a new release of MbUnit available for download at tigris. The main change in this release is the support for separate AppDomain (which was really painfull to get).

New Features:


posted on Sunday, June 13, 2004 9:55:00 PM (Pacific Daylight Time, UTC-07:00)  #    Comments [9]

In a previous post, I showed how you could use the IL graph to do static fault detection (at least for simple but recurrent faults). Since the code was using Reflector API, but it was more the job for FxCop rules. I started to port the code to FxCop.

As you can see on the screenshot below it is working, at least on my simple examples. In fact, it seems that FxCop decompiler is still a little buggy because it returns erroneous target offset for brtrue.s or brfalse.s IL instruction. Therefore, you will have to wait to play with this new toy :)

The figure below shows the FxCop rule applied to the test class showed in the previous post. As expected, ArgumentNotChecked fails, but the 2 others succeed the tests.

posted on Sunday, June 13, 2004 2:09:00 PM (Pacific Daylight Time, UTC-07:00)  #    Comments [0]
# Saturday, June 12, 2004

New features:

Warning: This release has been compiled agains .NET v1.1 (because System.Drawing is buggy in v1.0), therefore you must create a Reflector.exe.config file in the directory of Reflector and add the following:

About bug reports:

Please, DO NOT post bugs in the blog. It is much more easy for me to monitor bugs through the http://mbunit.tigris.org issue tracking system. :)

Download Now on www.dotnetwiki.org

posted on Saturday, June 12, 2004 12:55:00 PM (Pacific Daylight Time, UTC-07:00)  #    Comments [16]
# Friday, June 11, 2004

I've been reading lately about PreFast, a tool for detecting fault in applications based on static analyis. Sadly, PreFact is for C++, so I wondered: can we do the same in C# ?

The test fault:

So I started with simple fault: a method that uses nullable argument and that does not check for nullity -> the NullReferenceException fault (NRE). Here are three method that illustrate the problem:

public class MyClass
    public void ArgumentNotChecked(Object arg)
        string s=arg.ToString(); // if arg is null, NRE

    public void ArgumentChecked(Object arg)
        if (arg==null)
            throw new ArgumentNullException("arg");
        string s=arg.ToString(); // ok, we know arg is not null

    public void ArgumentGuarded(Object arg)
        if (arg!=null)
            string s=arg.ToString(); // ok, we know arg is not null

Sketch of the solution

The solution (I found) to this problem can be understood as taking all the possible path in the IL graph, while keeping track of the current state of the argument: Null, NonNull or Uncertain. When starting, the argument is uncertain, it could be null or not. If a method instance of the argument is called 3 things can happen:

  1. the argument is Null: we have found a bug,
  2. the argument is Uncertain: we have a possible bug. If by design, you always check parameters, this is a bug,
  3. the argument is NonNull: that's ok :)

In terms of graph theory (and QuickGraph), we need to apply the EdgeDepthFirstSearch algorithm using a visitior (IEdgeColorizerVisitor) that the job  described above. More that words, let's explain this on schemas.

Checking the ArgumentNotChecked method

This methods is very simply. In IL, it looks like this:

call Object.ToString()

The corresponding graph is the following (ColorCode: Orange=Uncertain, Red=Null, Green=NonNull)

The EdgeDepthFirstSearch has only one step: it explorezs the ldarg.1 -> ToString() edge. Since the ldarg.1 status when calling ToString is Uncertain, it should output a warning. So in Reflector I get:


Checking the ArgumentChecked method

This method is already a bit more complicated since there is a branch. The IL is:

L_0000: ldarg.1 
L_0001: brtrue.s L_000e
L_0003: ldstr "arg"
L_0008: newobj instance void [mscorlib]System.ArgumentNullException::.ctor(string)
L_000d: throw 
L_000e: ldarg.1 
L_000f: callvirt instance string object::ToString()
L_0014: stloc.0 
L_0015: ret

and the IL graph looks like this:

The EdgeDepthFirstSearchAlgorithm starts by examining the ldargs.1 -> brtrue.s edge.

If we find a brtrue.s, we can easily check if it is applied to ldarg1. If yes, then we should update the argument state in the child edges. The "then" branch will be tagged Null, the "else" branch will be tagged NonNull  as depicted in the figure below: 

Now, when we encounter the ToString() call on the argument, it's state is set to NonNull, so that's ok. 

Now, in Reflector, the fault analysis on the method should not find any warnings:

It worked!


Fault analysis can be seen as a natural application of graph theory and QuickGraph is a good for doing this. Although Reflector is a great tool, I think fault detection needs to be implemented as FxCop rules.... so stay tuned for new adventures.

posted on Friday, June 11, 2004 5:25:00 PM (Pacific Daylight Time, UTC-07:00)  #    Comments [5]
# Thursday, June 10, 2004

TypeGraph Addin:

This is the first preview of the next killer Reflector addin: Type Graph. The addin visualizes the type inherance thourgh a graph. If a namespace or a type is selected in the Reflector tree, the corresponding graph nodes are highlighted in green.

Why such an add-in ?

Besides outputing nice graphics, Type Graph has real software analysis potential (to my point of view). For example, it can be used to visualize Code Coverage: each day, your automated test automaton creates a big poster of the application, gray nodes are not covered, red have failed some tests and green are ok. You could even make a movie and play smart at the next TechEd :) And that's just the beginning...

Thanks to Jamie (NUnitAddin) suggested me the coverage application


mscorlib graph with System.Reflection namespace highlighted

The algorithm are based on force directed layout which I found in Maxime Melchior final work (one of our student).

posted on Thursday, June 10, 2004 9:44:00 PM (Pacific Daylight Time, UTC-07:00)  #    Comments [14]

This is a new add-in related to the ILGraph addin for Reflector. Basically I use the IL graph to extract all the path to cover the entire graph (and get full coverage). Each path then generates an empty Unit Test Case (using Refly) that the user will have to write. Better than words, the schema below is straightforward:

The addin can generate Unit Test cases for methods, types, namespaces or even full assemblies! Since it is based on CodeDom, it supports output to any .NET language.

The output

posted on Thursday, June 10, 2004 6:00:00 PM (Pacific Daylight Time, UTC-07:00)  #    Comments [30]
# Wednesday, June 09, 2004

For those who want to play with a preliminary version of the PGF, here it goes:

Download PGF v1.0 (beta)

Update: the PGF is now part of TestFu.

posted on Wednesday, June 09, 2004 2:37:00 PM (Pacific Daylight Time, UTC-07:00)  #    Comments [6]