Archive for the ‘c#’ Category

Behaviour driven development on user interfaces with Automation peer

Testing user interfaces is usually a pain in the butt. No matter how cool your UI is, it will often boil down to a brain-cell killing process clicking the same buttons over and over again. Thanks to the Geek Gods of .Net though, there are ways to automate this, and it’s not even that tough to do.

In this post, we’re going to use Automation peers to expose a button to a unit test, and have the test start the application, click the button, and confirm that the button does what it’s meant to do. We’re going to use MbUnit to write the test, and NBehave to make the tests nice and clear.

Continue reading


Is this thing on?

Download sample code here (New window)

There’s been a project knocking around the back of my head for a while. I keep putting it off, doing some work on it now and again but never really settling down to really do it. This long weekend turned out to be one of those occasions; I’ve just finished playing Fallout 3 (Awesome game, the ending left a slightly bitter taste in my mouth though) and ended up with nothing to do. Visual Studio to the rescue…

Now what?

If you ever worked on an application that requires Internet connectivity, you will have had to handle situations where the connection may be unavailable for certain periods of time. Sometimes you can get by that by trapping an exception; I know I have, though I still find that particular solution to be somewhat inelegant. What I wanted was some way to monitor the state of the connection and keep track of it. This way, if you need to send a message for example, you can have your application decide whether it should try to send it right away, or whether it should stash it away till the connection becomes available. This post is about how to determine whether a connection is up or down, and notify the application when the state changes.

Doing it the managed way

There is a method in .net, NetworkInterface.GetIsNetworkAvailable(). This method will tell you whether there is a connection going out of the machine, and it seemed to be the ticket. Unfortunately (or fortunately – this would have been a really short post otherwise), in my case, it wasn’t. You see, when we’re working off a LAN, we can have local only connectivity, or low connectivity. This means that the machine can talk to the router, but cannot access the Internet at large; the method still returns true in this case. If you’re working on an intranet application, this may be ok for you, but I wanted something bigger.

Going native

My friends have a long standing joke. It goes something like, “If someone invents a piece of hardware to wipe your bottom, the Windows API probably already supports it.” (The exact quote is unsuitable for mixed company). The windows API does, indeed, grant you nearly god-like powers over your system, and nearly anything Windows can do, the API can too. Since Windows can tell when there is no connectivity to the web (the dreaded “local only” icon), I figured that would be the next port of call in my search. Sure enough, wininet.dll defines a function InternetGetConnectedState

Ouch. We still have the same issue… it doesn’t really care about the “local only” business. At least, it gives us some additional information, such as whether the connection is through a modem or a LAN.

Hackety-hack-hack time

I’m still fairly confident that there’s a direct way to get to this information, but since I just want to get this to work right now, I’ll fudge it up a bit.

Using the wininet.dll function, we can tell whether we’re connected to a modem, connected to a LAN, or not connected at all. Not connected means just that, so that’s easy. For modem connections, I’ll assume that it’s either connected to the Internet, or not connected at all (You’ll have to excuse my blatant ignorance of networking hardware. Drop me a comment if you know this is the case). This just leaves us with the LAN condition to deal with.

The machine that goes PING!

When we know we’re connected to a LAN, but not how far we can go, we have to resort to the time honoured mechanism of the PING. All hail the mighty PING.

A ping is simply a very short message that’s sent to the server. If the server accepts the ping, it just echoes it back. It’s a protocol for machines to determine if they can see each other over a network. In .net, the ping is represented by a Ping class, and returns a PingReply:

   1: if (isLan)
   2: {
   3:     PingReply reply = pingOfLife.Send(PingTarget, 3000);
   4:     return reply.Status == IPStatus.Success;
   5: }

This sends a ping to a URL identified by the PingTarget property, and waits up to 3 seconds for a reply. The URLs for Ping don’t take a protocol specifier, so you’d use, say, rather than

You will notice that in the sample code and the example above, we’re only assuming a successful connection if the reply to the ping is successful. This is a simplification. In reality, the ping is checking whether we can access the ping target, irrespective of whether the rest of the Internet is accessible. If the target server is down, you’ll get a “No connection” result.

When you think about it, it doesn’t matter in most cases. You only care about whether your application can reach its server, not whether it’s got access to random web pages.

What else?


This seemed to sort it out for me. You can find the entire source code in the sample project. The ConnectionState class in the sample also contains events you can hook into so your application will get notified of state changes.

Download sample code here (New window)

kick it on

Entity framework learning guide

Christmas is here early this year! Zeeshan Hirani has released his 514 page pdf guidebook about the Entity Framework. Thanks!

Keep code behind clean

Download the sample code here

Last week, Marlon blogged about how to avoid adding command binding code to code-behind files. The idea is both simple and great, and allows you to keep your code behind nice and clean, and your layers separated. There’s only one (and yes, I’m being very anal here) thing that bugged me with it:

DataContext = new ViewModel(new SampleModel());

or, for that matter, “DataContext = anything”, is still in the code behind class. This can easily be sorted out with some easy data binding and a supporting class.

First, create a class that will contain your controllers. You can create a factory class, or, simply a class which exposes your controllers. To demonstrate this, I’m only using a class with a static property:

public class ControllerProvider
    static ControllerProvider()
        WindowController = new WindowController();
    public static WindowController WindowController { get; private set; }

They don’t get much simpler than that.

Next, bind the data context in your window:

<Window x:Class="Commands.Window1"
    DataContext="{x:Static local:ControllerProvider.WindowController}"
    Title="Commands" Height="200" Width="200">
        <Button Command="{Binding MyCommand}" Content="Execute command"/>

If we look at the codebehind for this, we have only the usual, Visual Studio generated code:

public partial class Window1 : Window


    public Window1()


Is this really worth it?

Yes. No. Maybe. I think it is, because I prefer to keep everything together. Besides, the idea is to keep the code behind as clean as possible. If people have to touch this class to add the data context, they may be tempted to add more stuff in there. Then again, it’s very probably a matter of preferences.

Download the sample code here

Dynamic proxies using Castle

The sample code can be downloaded here

This week I found myself with some time on my hands, so I knocked up a simple object pool. It’s fairly standard stuff… you call Fetch to get something out of the pool, and Return to put it back. Fairly standard.

The problem

The call to Return felt a bit annoying. If we forget to call that, we end up leaking resources as we create more and more objects, or get an exception thrown at us. Not good. I wanted something like the using (whatever) syntax, which I think is the most awsome thing ever.

To do that, we’d have to ensure that all the items in the pool implement IDisposable, have a reference back to the pool, and call Return in their dispose method. This isn’t really feasible; for starters, it would tightly couple everything with the pool, which is, like, all sorts of bad. A far better approach is, in my opinion, to wrap the object being pooled to add whatever behaviour I need. Not necessarily a great idea if you don’t know what’s going to be pooled beforehand.

The solution

Luckily, the good folk of the Castle Project came to the rescue with their Dynamic Proxy API. This API is used by several great open source projects out there, so it comes in very well recommended.

Castle Dynamic Proxy create wrappers around your object. The wrapper intercepts calls to the object, allowing you to redirect them as needed. The first thing you’d need to set up is an Interceptor class; the thingy that will handle calls before they are passed to your object. In our case, the basic form of the interceptor would be dead simple.

Intercepting calls

First of all, the interceptor needs to know about the pool, so it can call methods on it. Passing it in via a constructor does the job:

private class CallInterceptor
    private Pool<T> Parent { get; set; }

    public CallInterceptor(Pool<T> parent)
        Parent = parent;

All run-of-the-mill so far. Next, we have to implement the Intercept method in IInterceptor
to get this thing to work:

private class CallInterceptor : IInterceptor

    public void Intercept(IInvocation invocation)
        if (invocation.Method != null && invocation.Method.Name.Equals("Dispose"))

That tells the proxy to check whether the call it just caught was bound for the Dispose method.
If that is the case, the pool’s Return method will be called with the invocation target as the
argument: in this case, the object being disposed.

All well and good, but what if the object needs to be disposed after used? Since we’re pooling,
we don’t want to dispose of the pooled object while the pool is still hanging around. That makes
things easier for us, as we just have to see if the pool is disposed, and Proceed invocations
to Dispose if it is. This variation is the one being used in the sample code.

Creating an instance of a proxy

To create a proxy in the pool, we need to create an instance of ProxyGenerator. The rest is dead

T proxy = proxyGenerator.CreateClassProxy<T>(interceptor);

Where interceptor is an instance of our interceptor class, above. Like I said, dead easy.

And the result

We can now use the following syntax with our pool:

using (MyPooledResource r = pool.Fetch())
    // Do stuff with the resource.

There are obviously some restrictions to this method. The pooled class needs to implement
IDisposable, and the Dispose method needs to be marked virtual so that Castle can create
the proxy to it. The last point is important; if it’s not virtual, it will compile fine,
but your application will then call the method directly, not the proxy. Boom.

As you can see in the sample code, the generic type parameter must have a default constructor,
but this is a requirement of the Pool, not of the dynamic proxy API.

Since we’re adding another layer, there will also be a slight performance hit.


This was my first brush with dynamic proxies, and I have to say it looks real interesting. It’s
probably more useful when writing generic APIs than actual applications; you can work out some
really clean APIs this way. I’ll need to explore it further though, as I expect there are more
efficient ways to use it than the simple example presented here.

The sample code can be downloaded here