Stories about Software


Getting Started With Moles

Microsoft Moles seems pretty cool, so I’ve decided to set it up and play with it. However, because it’s a research project, the documentation isn’t exactly thorough. I found some videos and various tutorials but nevertheless had a lot of digging in order to get it working. I’m going to document some of the hurdles here for posterity and for myself, in case I need to do this again.


First off, I’ve been using Pex for a while now, so I just assumed that I’d have Moles installed. It appeared as though this wasn’t the case when I watched a Moles startup video. You see, I didn’t have the template that he references in the video, and I got no joy from doing “devenv /installvstemplates” (which, by the way, is very handy if you find that you’re missing some template that should be installed for whatever reason). As it turns out, the reason I don’t have it is because it’s apparently now deprecated and not the way things are done. I didn’t find this out until after I had un-installed and re-installed Pex and Moles, so I don’t know whether or not Moles was originally functioning with Pex. Probably, but who knows?

Getting Started

After that, I browsed a few posts like this one and saw that the thing I should be going for is getting these M types up and recognized by Intellisense. For instance, I want to test a class that’s using the System.IO.Directory class, so what I want is “MDirectory” for creating Moles. I got the sense that the thing to do here was to right-click on the library reference in question (i.e. “System”) and add a Moles assembly. This is wrong. Very wrong. I got about 25 compiler errors after I tried to build.

By trial and error (read: luck), I discovered that you want to right-click on “References” in your test project and “Add Moles Assembly For mscorlib.”

Adding Moles for mscorlib

Type was not instrumented…huh?

Once I’d gotten my M types in place, I was set to go. So I coded up a test that should pass if I implemented the delegate logic correctly, and I ran it. At this time, I got an exception in the test run. In opening the test result details, the Moles team was actually helpful enough to include this comment in the results:

“To resolve this issue, add the following attribute in the test project:

using Microsoft.Moles.Framework;
[assembly: MoledType(typeof(System.IO.Directory))]”

That’s pretty helpful. So, okie-dokie…and, viola! It passed.

Actual Use

If you understand functions and delegates, there’s not a lot to actual use. Once I’d gotten the annoyances out of the way, using this was actually very easy, and I found it to be quite powerful.

One thing I noticed is that it does introduce a bit of overhead when you start your test run. I’m keeping my eye on this to see if it’s a one-time, up-front cost, or if it scales and causes your test runs to be slower as you use it more.

Moling your own classes

This was fairly straightforward if you’re moling your public classes. You just right-click on your project under test in the test project’s references and select “Add Moles Assembly.” It gets a little more interesting if you want to mole internal classes.

To do this, open up the AssemblyInfo.cs class of your project under test and add an [assembly: InternalsVisibleTo(“{YourProjectNamespace}.Moles”)]. In order to know exactly what to add, just mimic the new reference that appears in your test project after you add a new moles assembly.

Moling constructors

For most instance based methods, the declaration looks something like:

That is, you’ll get pretty used to the “AllInstances,” it appears. But one gotcha is that you mole a constructor like this:

That’s not really that big of a gotcha, but I’m just kind of documenting here all the things that I had to go poking around to figure out.


Directory Browser Dialog

One of the things that’s always surprised me about WPF is the lack of any kind of out-of-the-box file/directory browser dialog. It seems as though every time this comes up, I poke around the internet, hoping that it’s been added in some kind of update somewhere, but it never is. At least, it never is in the scope and skill of my google skills, anyway.

So, I wrote one for WPF. There’s nothing particularly hard about this, and I don’t view it as some kind of breakthrough. The reason that I’m making this post is that I noticed a trend that I find rather irritating. Whenever I’m searching for something like this, I seem to encounter two kinds of posts: posts that offer some zipped Visual Studio project I can download and plugin or else some vague, incomplete suggestion of what to do.

As for me personally, I’m just looking for functional code that I can slam right into my project. I don’t really want to download things and I don’t really want to spend the effort coding up something that I think should already exist. That is to say, I have no issue getting my hands dirty when I can learn something or customize, but I’m also not a big proponent of reinventing the wheel.

I’m posting here to break this trend that I noticed. This is a completely functional solution that exists not at all beyond what you see here. I’m hoping this appeals to people with tastes like mine. I like to see all the code but without downloading things.

So, without further ado:

Above is the XAML for the user control and below is the code behind

An example user of this is here:

As you can see, this is about as simple as it gets. If I have use for it, I’ll probably later rename the control to something like ChooserDialog and allow it to have modes of “File” and “Directory” which pop up their respective kinds of dialogs. This could certainly be extended and made snazzier, and maybe I’ll do that with time. And, maybe when I do, I’ll post a link allowing people to download it, but I will also post the code so that you can inspect it without jumping through hoops, and you can see if it suits your needs.


MS Test Report Generator

I’ve been working on a side project for a while, and today I uploaded it to Source Forge. The project is a tool that takes XML results generated by MS Test runs and turns them into HTML-based reports. I believe that TFS will do this for you if you have fully Microsoft-integrated everything, but, in the environment I’m currently working in, I don’t.

So I created this guy.

Back Story

I was working on a build process with a number of constraints that predated my tenure on the process itself. My task was to integrate unit tests into the build and have the build fail if the unit tests were not all in a passing state. The unit test harness was MS Test and the build tool was Final Builder.

During the course of this process, some unit tests had been in a failing state for some period of time. Many of these were written by people making a good faith effort but nibbling at an unfortunate amount of global state and singletons. These tests fail erratically and some of the developers that wrote them fell out of the habit of running the tests, presumably due to frustration. I created a scheme where the build would only run tests decorated with the “TestType” attribute “Proven”. In this fashion, people could write unit tests, ‘promote’ them to be part of the build, and have it as an opt-in situation. My reasoning here is that I didn’t want to deter people who were on the fence about testing by having them be responsible for failing the build because they didn’t know exactly what they were doing.

After poking around some, I saw that there was no native final builder action that accomplished what I wanted– to execute a certain subset of tests and display a report. So I created my own batch scripts (not included in the project) that would execute the MS Test command line executable with filtering parameters. This produces an XML based output. I scan that output for the run result and, if it isn’t equal to “Passed”, I fail the build. From there, I generate a report using my custom utility so that people can see stats about the tests.

Report Screenshot


During the course of my spare time, I decided to play around with some architectural concepts and new goodies added to C# in the .NET 4.0 release. Specifically, I added some default parameters and experimented with co-variance and contra-variance. In terms of architecture, I experimented with adding the IRepository pattern to an existing tiered architecture.

On the whole, the design is extensible, flexible, and highly modular. It covered about 99.7% by unit tests and, consequently, was complete overkill for a little command line utility designed to generating an HTML report. However, I was thinking bigger. Early on, I decided I wanted to put this on Source Forge. The reason I designed it the way I did was to allow for expansion of the utility into a GUI-driven application that can jack into a server database and maintain aggregate unit testing statistics on a project. Over the course of time, you can track and get reports on things like test passing rate, test addition rate, which developers write tests, etc. For that, the architecture of the application is very well suited.

The various testing domain objects are read into memory, and the XML test file and HTML output file are treated as just another kind of persistence. So in order to adapt the application in its current incarnation to, say, write the run results to a MySQL or SQL server database, it would only be necessary to add a few classes and modify main to persist the results.

Whether I actually do this or not is still up in there air, and may depend upon how much, if any, interest it generates on Source Forge. If people would find it useful, both in general and specifically on projects I work on, I’m almost certain to do it. If no one cares, I have a lot of projects that I work on.

How to Access

You can download a zipped MSI installer from SourceForge.

If you want to look at the source code, you can do a checkout/export on the following SVN address: https://mstestreportgen.svn.sourceforge.net/svnroot/mstestreportgen

That will provide read-only access to the source.



Quick Information/Overview

Pattern Type Structural
Applicable Language/Framework Agnostic OOP
Pattern Source Gang of Four
Difficulty Relatively simple

Up Front Definitions

There are no special definitions that I’ll use here not defined inline.

The Problem

In keeping with the vehicle theme from the previous post, let’s say that we have an application that models vehicle operation. Among other things, we have an abstract base vehicle class and some concrete vehicles, “car” and “boat.” The base class defines an abstract “Start()” method and the inheritors override this to define their own starting logic. For the sake of discussion, let’s say the purpose of this application is to graphically model wear and tear on vehicles as they make their way around. That is, we need to be able to move the vehicles around and simulate their internal components in terms of how they do over the course of time. A “Start()” method is vital to this.

Here is a very simple view of what this might look like:

As you can see, the details of everything but this inheritance relationship are omitted. Now, let’s say that this code was written a while ago, and all of the internal vehicle logic resides in an assembly that compiles to Vehciles.dll. Your company builds this and deploys it, and hundreds of users in the field are using it.

The client code for this is in another assembly or assemblies, and it contains various code and classes that do things like this:

In other words, the client code is using the vehicle code polymorphically. Let’s also impose some political constraints here. Let’s say that the client code that you deploy is written by Group A in your department and the car code written by Group B. Group B is in high demand and can’t be bothered to change the Vehicles.DLL unless it’s absolutely necessary and unavoidable. Let’s say that we’re part of group A, and a new requirement comes in.

The bigwigs at the company have just purchased a smaller company that models tanks for the military in the same sort of way that we do with other vehicles. We need to incorporate their Tank implementation into our vehicle modeling software. The now-defunct company has Tank.DLL, and Tank.DLL contains the following code:

Let’s also say that the bigwigs laid off everybody in the now acquired company, so there’s no real reliable access to their source code and build in the short term. In other words, because of the logistics of the acquisition, we’re stuck with the Tank.cs class as-is, and because of internal politics, we’re stuck with the Vehicle class as-is. We have to use those classes, and the only thing we can change is our client code. (This may be a little contrived, but it’s surprising how often things work out exactly this way in real world coding environments–the arbitrary and silly is often a fact of life.)

So we need to deploy our fleet, which now includes a tank. Let’s see how that looks:

Well, there you have it. We’ve doubled our code and gotten the job done. Now, every time we add new functionality, we’ll just have to add it in parallel for vehicle and tank. So, let’s build and ship this thing, and… wait a second! That’s absolutely ridiculous. We’re rampantly duplicating logic and creating a maintenance nightmare. We’re completely defeating the purpose of the polymorphism of vehicle. There has to be a better way to do this.

So, What to Do?

This is where the Adapter pattern comes in. What we really want here is a way to trick the existing API into thinking that Tank is just another vehicle. That shouldn’t be too hard, since Tank is just another vehicle.

So let’s try something. We’ll just create our own Tank called “TankAdapter” and include it in our client code assembly. We have access to the public members of Vehicle.DLL, so we’ll just define our own inheritor:

Now we’ve partially solved the problem. We can create a vehicle simulator as follows:

This keeps our polymorphism intact and restores the Simulator class’s internals to sanity. With TankAdapter, we have no need to create and maintain the special case for Tank.cs. However, it doesn’t actually do anything yet.

Pulling back and looking at the adapter metaphor in general, adapters are used to hook up two pipes or cords that don’t fit together in and of themselves. So you get thingamajig a with two sides: one that fits with your first pipe, and one that fits with your second. What we’ve done here is craft a TankAdapter part that fits onto the Vehicle “pipe.” We now need to make it fit on the Tank “pipe.”

To do that, we simply give the TankAdapter a Tank object and map the Vehicle methods to the appropriate Tank methods. In this case, it would look like this:

And, there you have it. The adapter fits both “pipes,” and we had no need to change either one to make this happen. You’ve met your external requirements without compromising the design of the code that you do control. Now you can ship it.

A More Official Explanation

An implementation of the Adapter pattern is going to consist of a few basic entities. The Client is a class or piece of code that is using some Target. A desire to add to the functionality of the Target emerges, but the new class to be used, the Adaptee, is not compatible with the Client. The Client expects a different interface from the one that the Adaptee provides. So an Adapter is introduced that understands what the Client wants and what the Adaptee provides, and it maps Client desires to Adaptee functions.

In our example, VehicleSimulator is the Client, Vehicle is the Target, Tank is the Adaptee, and TankAdapter is the Adapter. VehcileSimulator wants to use Tank, but it can’t, given Tank’s interface. We explored the possibility of changing VehicleSimulator, but decided that the needed changes were simply too burdensome if there were another way. So, not wanting to change Client, and not being able to change Target or Adaptee, we introduced Adapter.

Other Quick Examples

  1. One place you may see this a lot is code that deals with a GUI. For instance, let’s say that you have a bunch of controls that you hide when something happens behind the scenes. Let’s also say you’ve inherited some kind of custom control that you now want to hide, but it doesn’t expose a “Visibility” property. A very common solution here would be to define your own custom control that wraps the existing one and figures out how to hide it.
  2. We’ve talked about this in the context of inheritance, but this also applies to interface polymorphism. Let’s say you have a series of classes that implement IDisposable and that is how you clean up after yourself in some presentation layer code–aggregate the controls and invoke their “Dispose()” methods. If you’re then offered a one-off that doesn’t implement IDisposable, you can define a class that does and wrap your one-off in it to keep with the pattern.
  3. The null object pattern is a very specific example of the Adapter pattern.

A Good Fit – When to Use

The Adapter pattern makes sense when you have two components that need to interact with one another and you’re limited or even prohibited in terms of your ability to change either component. This limitation may be the result of things that we’ve discussed, such as requirements, politics, and good design practices.

Square Peg, Round Hole – When Not to Use

The Adapter Pattern is a hack. Make no mistake about that. It’s a pretty hack, and it’s in the GOF book, but it’s a hack nonetheless. I would advise against using it when you have the ability to change the components that you’re contemplating adapting.

For example, if in our example, we had the ability to modify Tank.cs, it would have made a lot more sense to have it inherit from Vehicle. Even if legacy code depended on its method names, we could simply have defined “Start()” in Tank.cs that called “FireUpTheTank()”. Alternatively, if we had access to Vehicles.DLL, it might have made sense to define our own Tank class and port the functionality from Tank.cs.

In my estimation, either of those options is better than using the Adapter pattern. This mimics adapters in the pipe analogy too–if you bring in a plumber and he’s rebuilding a whole piping system from scratch, why bother cobbling a bunch of old pipes together when they aren’t designed for that? Better just to get the right pipe in the first place.

So What? Why is this Better?

The Adapter Pattern is a better alternative to littering some client code with a bunch of conditional logic. As you saw in the example above, introducing a one-off can create havoc in client code. In our example that maintained a parallel set of Vehicles and Tanks, imagine the maintenance on that class if Vehicle had many methods and many clients. You would have to do that doubling of effort each and every place any method or property on Vehicle was invoked.


Abstract Factory


This is going to be the first post in a new series that I’m doing on design patterns. Now, I’m certainly not the first person to post a taxonomy of design patterns and explain them, but I would like to put a different spin on the usual. Normally, I see postings that contain a UML diagram and then verbiage like “encapsulates indirection in a creational paradigm between concrete implementers and….” To put it another way, I see definitions that are useful if and only if you already know the definition. So, my idea here is to relate the design patterns in the context of a sto Read More