# 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;
        this.Multiline=true; 
    }
    public IAssemblyBrowser AssemblyBrowser
    {
        get
        {
            return this.assemblyBrowser; 
        }
        set
        {
            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)
            this.Text=assembly.Name;
        else
            this.Text=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)
    {
        this.windowManager=(IWindowManager)serviceProvider.GetService(typeof(IWindowManager));
        IAssemblyBrowser assemblyBrowser = (IAssemblyBrowser)serviceProvider.GetService(typeof(IAssemblyBrowser ));

        // create window
        AssemblyNameWindow anw = new AssemblyNameWindow();
        anw.AssemblyBrowser=assemblyBrowser;
        // 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
        this.windowManager.Windows.Remove("AssemblyName");
        // remove button
        this.assemblyMenu.Items.Remove(this.button);
    }
    private void button_Click(Object sender, EventArgs args)
    {
        this.windowManager.Windows["AssemblyName"].Visible=true;
    }
}

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;}
       set
       {
            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")]
    [ReflectorCommandBar(CommandBarTarget.Assembly)]
    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:

ldarg.1
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:

Gotcha!

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!

Conclusion

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

Screenshot:

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]

Yesterday, I started reading Using Production Grammar for Software Testing (UPGS) for Emin Sirer and N. Bershad (found on ModelBasedTesting site), the authors describes a method for generating test automaton based on "inversed" grammars. Following their ideas, I have designed a little framework, the Production Grammar Framework for .NET (PGF).

Introduction

In this blog, I will present a framework for defining and executing production grammars. The production grammars described in UPGS are very similar to classic "LALR" grammars, in terms of understanding and semantics. The difference is that production grammars reversed the work of grammar, since they are used to produce output instead of analyse input.

Production grammars can do anything, ranging form generating data, piloting your application and generating test case, ... Since we are looking at testing applications, here are a few application that we will be interrested on:

  • manipulate the Implementation Under Test (IUT),
  • generate test case that manipulate the IUT. In this case, the grammar is a code generator,
  • if you want to test IUT against input data, generate a wide range of possible inputs,
  • etc...

Oracle problem

"Production grammars are well-suited for test generation not only because they can create diverse test cases effectively, but also because they can provide guidance on how the test cases they generate ought to behave. It is often hard to determine the correct system behavior for automatically generated test cases -- a fundamental difficulty known as the oracle problem. In the worst case, automated test generation may require reverse engineering and manual examination to determine the expected behavior of the system on the given test input."  The authors propose two ways of dealing with the oracle problem:

  • comparing difference with another implementation,
  • generating verification code along with the test code.

Since the PGF is based .NET code, you can theoretically add any verification code and if available, compare with any other implementation. This will be illustrated in the example

What is a Production Grammar:

"A production grammar is a collection of non-terminal rules to terminal rules that resembles a regular parsing grammar, but is used “in reverse.” That is, instead of parsing a sequence of tokens into higher level constructs, a production grammar generates a stream of tokens from a set of non-terminals that specify the overall structure of the stream".

Let's see that on a simple example. Consider the following comma separated list of names:

John,Paul,Marc

An valid EBNF grammar to parse this stream would be ([A-Z] designs capital letters, [a-z] lower case letters, + one or more occurence, * zero or more occurence):

name := [A-Z] [a-z]+
names := name (',' name)*

In the case of production grammar, we want to create that list of name. In C#, a possible implementation of the production grammar would be as follows:

public class NamesGrammar
{
   public string Name()
   {
        int count = nextRandom(); // gets a random int
        return getUpper() + getLowerString(count); // getUpper return upper case, getLowerString returns lower cased string
   }
   public string Names()
   {
        int count = nextRandom();
        string names = Name();
        for(int i=0;i!=count;++i)
           names += ',' + Name();
        return names;
   }
}

The example will generate a list name when the Names method is called, we have production :). This is just a dummy example, it is 100% hard-coded and very difficult to maintain. 

Production Grammar Framework

Before starting to work on an example (guess which), let us define important notations/interfaces of the PGF:

  • a rule (IRule) is an object that produce something. A rule can be terminal, it does not have any sub-rules, or non-terminal. Example of non-terminal rule is the + operator, terminal rule would be writing a string to a stream.
  • a production (IProduction) represents a production process (you can think of it as batch). It is passed on between the rules and can be stored to transmit the context or finish production,
  • Each time a rule wants to produce, it asks the production for a production token (IProductionToken). If the request is succesfull, the production goes on; otherwise, the production finishes. Using this mechanism, you can easily design production that will stop on a finite number of rule production.
  • a grammar (IGrammar) encapsultates a start rule and is used to launch the production process,

Those 5 interfaces form the kernel of the PGF, the rest of the framework is built on top and around them to help the user implement grammars.

The working example: a Stack

In order to crystilase the ideas presented here, we will consider the problem of testing a Stack (as in Test Driven Developement in .NET). A simple unbounded stack can be formalized by the following interface:

public interface IStack
{
    void Push(Object);
    Object Pop();
    Object Peek(); // equivalent to Pop() in TDD
    bool IsEmpty {get;}
}

The grammar

Before writing down the grammar in C#, it is useful to formalize it in a "pseudo" EBNF-like notation. In this example, there are 3 terminals: Push, Pop, Peek (we omit IsEmpty for now):

push := stack.Push(...)
pop := stack.Pop()
peek := stack.Peek()

 Since Pop and Peek can throw if the stack is empty, we create a special non-terminal rule  that guards production agains a specific exception type. This gives us the 2 following non-terminal rules:

gardedPop := gard( pop, InvalidOperationException )
gardedPeek := gard( peek, InvalidOperationException )

Of course, we need to be able to decided wheter we want to execute the guarded rule or the non guarded. Again, we define a new non-terminal rule that works as a "if-then-else". This gives us 1 more non-terminal rule:

nonEmpty := push | pop | peek
empty := push | gardedPop | guardedPeek
stackRule := if(isEmpty) { empty } else { nonEmpty }

The final step is to decide how many execution we want. Since we can break the production at the IProduction level, we go for infinite:

stackGrammar := stackRule*

The full grammar can be summarized as

push := stack.Push(...)
pop := stack.Pop()
peek := stack.Peek()
gardedPop := gard( pop, InvalidOperationException )
gardedPeek := gard( peek, InvalidOperationException )
nonEmpty := push | pop | peek
empty := push | gardedPop | guardedPeek
stackRule := if(isEmpty) { empty } else { nonEmpty }
stackGrammar := stackRule*

At this point, we have define a grammar for piloting the stack written in a "pseudo"-EBNF language. The simplicity of the notation let us concentrate on the problem and not on the tool to solve it. However, as it is, the grammar is pretty much useless, since it is missing verification code. We will see that the verification code can be easily added while writing the grammar in C#.

Rewriting the grammar in C# with PGF

The PGF contains a bunch of built-in non-terminal rules and helpers that will help you translate a grammar into functional C# code. In this example, we will encapsulate the grammar in a StackFixture class that contains a stack field:

public class StackFixture 
{
    private Stack stack = new Stack();
}

Step 1: Creating the terminal methods

Following the way we constructed the grammar, we begin by defining the terminals. The easiests solution is to define one method for each terminal and then wrap it into a IRule. For example, the push terminal is implemented as follows:

public class StackFixture 
{
    private Stack stack = new Stack();
    private IRule push;

    public void Push()
    {
        this.stack.Push(null);
    }

    public void CreateGrammar()
    {
        this.push = Rules.Method(new DefaultMethodDelegate(this.Push));
    }
}

We have added 3 things: a IRule field member to store the "push" terminal, a Push method that actually pushes something on the tested stack and a CreateRules method that will be used to creates the grammar. The Rules.Method is a static helper class that encapsulate the call to a member method into a rule. The same operation can be repeated for pop and peek.

Step 2: Adding code for the Oracle problem

In order to be able to verify assertion on the fixture, we need to solve the Oracle problem. For this specifiy case, we can do the Comparaison testing approach where we execute the operations on another implementation and verify that outputs are different (NC, not NSC). 

public class StackFixture 
{
    private ArrayList list = new ArrayList();
    private Stack stack = new Stack();
    private IRule push;

    public void Push()
    {
        this.stack.Push(null);
        this.list.Add(null);
        Assert.AreEqual(list.Count==0, stack.IsEmpty);
        Assert.AreEqual(list[list.Count-1], stack.Peek());
    }
    ...
}

Step 3: Creating the non-terminal rules

From this step, the PGF provides the "classic" non-terminal rules and helper classes to create them (Rules) that makes the rest of the implementation straightforward:

public class StackFixture
{
    ...
    IRule push, pop, peek;
    IRule guardedPop, guardedPeek;
    IRule empty, nonEmpty;
    IRule stackRule;
    IRule stackGrammar;
    ...

    // returns true if stack is empty
    public bool IsEmpty()
    {
         return this.stack.IsEmpty;
    }

    public void CreateGrammar()
    {
        push = Rules.Method(new DefaultMethodDelegate(Push));
        pop = Rules.Method(new DefaultMethodDelegate(Pop));
        peek = Rules.Method(new DefaultMethodDelegate(Peek));

        guardedPop = Rules.Guard( pop, typeof(InvalidOperationException) ); // gard( pop, InvalidOperationException)
        guardedPeek = Rules.Guard( peek, typeof(InvalidOperationException) );// gard( pop, InvalidOperationException)

        nonEmpty = Rules.Alt( push, pop, peek); // push | pop | peek
        empty = Rules.Alt( push, guardedPop, guardedPeek);
 
        stackRule = Rules.If(new ConditionDelegate(IsEmpty), empty, nonEmpty); // if(IsEmtpy) empty else nonEmpty

        stackGrammar = Rules.Kleene(stackRule); // stackRule*
    }
}

Step 4: Creating a grammar and executing a production

In order to simplify our lives, we make StackFixture inherit from the Grammar class (which implement IGrammar) provided by the PGF. This class takes care of setting up the production factory and launching productions. Of course, this part of the framework can be easily customized and extended to plugin into your existing test automaton (MbUnit, NUnit, csUnit, ...).

public class StackFixture : Grammar
{
    public StackFixture()
    { 
        this.CreateRules();
    }
    public void CreateRules()
    {
        ...
        // required for Grammar
        this.StartRule = this.stackGrammar;
    }
}

A production can then be executed by launching the Produce method:

StackFixture fixture =new StackFixture();
fixture.Produce();

Conlusion

Production Grammar Framework is an effective tool to create and implement production grammar. Production grammar are used to model the complex behavior of application and automate the creation of complex test case. In fact, you could easily reuse your existing Unit Test cases with a production grammar! Of course, PGF will be part of MbUnit in the next release. Moreover, since the "hard" work is done by the machine, you can expect to get much better code coverage using Production Grammar (or MBT) than with classical unit tesing.

Future directions and the quizz

This post is already long so I will stop here. However, you can start to think about other interresting use of this technique:

  • database testing,
  • data generation for user input testing,
  • unit test case generation using CodeDom,
  • etc...

The quizz question: How does this relates to model based testing ?

posted on Wednesday, June 09, 2004 11:54:00 AM (Pacific Daylight Time, UTC-07:00)  #    Comments [15]
# Sunday, June 06, 2004

With the growing need for a decent .NET wrapper of LAPACK and since there exists no free wrapper around it (commercial version here), I have decided to take a try at this adventure (working with managed C++ is always an adventure). To help me in the task, Lapack++ a C++ wrapper around LAPACK: simple and very well done, should speed up things... (to be continued)

posted on Sunday, June 06, 2004 10:42:00 PM (Pacific Daylight Time, UTC-07:00)  #    Comments [7]