Skip to content


Automated “Unit” Testing – It’s Not Just for TDD, It’s for Bug Fixing Too!

Disclaimer – What I’m discussing here isn’t unit testing (hence the quotes), it’s more functional or integration testing; but as the term “Unit Testing” is often “abused” to mean “anything that uses a (unit) testing framework” so I’ve included it in the title to avoid confusion.

Introduction

I’m currently using TinyIoC in my first forays into MonoTouch development, and my initialisation code was throwing a resolution error on starup:

var container = TinyIoCContainer.Current();
var mainView = new MainView();
container.Register<IViewManager>(mainView);
container.Register<IView, MainView>(mainView, "MainView");
container.Register<IView, SplashView>("SplashView").UsingConstructor(() => new SplashView());
container.Resolve<IView>("MainView");
container.Register<IStateManager, StateManager>();
// Code was blowing up here..
var stateManager = container.Resolve<IStateManager>();
stateManager.Init();

The Exception that was given was that IStateManager could not be resolved, which was odd given that the StateManager was registered against IStateManager, and everything in its constructor was also registered:

public StateManager(IViewManager viewManager, Func<string, IView> viewFactory)

To The Debugger.. Right?!

So at this point your immediate reaction may be to fire up the debugger, trace into the code and start hacking around, debugging and hacking around some more until it works. Sure, that’s an approach, and one I’m sure we’ve all used in the past; but as I was pretty sure the issue was in TinyIoC itself I took a slightly different tack.

To The Test Runner!

With the approach above I would have to build and run my app every time I wanted to check if my “fix” had actually worked – and even if it had, how would I know it hadn’t broken something else? The solution is quite simple – recreate the conditions of the bug in a unit test, using stubs/mocks to replace your real classes, and make sure it fails in the same way:

[TestMethod]
public void Dependency_Hierarchy_With_Named_Factories_Resolves_All_Correctly()
{
    var container = UtilityMethods.GetContainer();
    var mainView = new MainView();
    container.Register<IViewManager>(mainView);
    container.Register<IView, MainView>(mainView, "MainView");
    container.Register<IView, SplashView>("SplashView").UsingConstructor(() => new SplashView());
    container.Resolve<IView>("MainView");
    container.Register<IStateManager, StateManager>();
    var stateManager = container.Resolve<IStateManager>();
    stateManager.Init();

    Assert.IsInstanceOfType(mainView.LoadedView, typeof(SplashView));
}

I’ve added an Assert to show what behaviour I think it *should* have. It’s a pretty horrible looking test, but it accurately represents what my failing code was doing, and the test fails as I expected it to. Now I can attach the debugger and find out what’s going on, safe in the knowledge I have a fast executing test available to verify my fix, and the rest of my test suite there to ensure I haven’t broken anything else.

After a very brief investigation it turned out that there was a bug in registration when *just* an Interface type was registered with an concrete instance (the IViewManager registration above). The “InstanceFactory” it was using hadn’t set the “AssumeResolves” flag, so TinyIoC was actually trying to find a valid constructor for IViewManager – which obviously wasn’t going to succeed. It’s a scenario I probably should have factored into my Unit Tests, but hey, nobody is perfect :-)

Conclusion

This post is aimed at covering two points:

  1. Test aren’t just for TDD. If you find a bug, isolate it with a test and you have a quick and easy way to verify a fix, and verify you haven’t broken anything else.
  2. Code Coverage isn’t everything. Apart from a few “defensive coding” null checks, the core of TinyIoC has pretty much 100% code coverage with its tests, but it didn’t help me with this issue. Although the code path was covered, the exact input (Interface type, concrete instance) wasn’t in my unit tests, so don’t assume 100% code coverage means 0 bugs in the code, there may well be a scenario you missed!
Share:
  • Twitter
  • DotNetKicks
  • DotNetShoutout
  • Google Bookmarks
  • Digg
  • del.icio.us
  • Live
  • Technorati
  • StumbleUpon
  • E-mail this story to a friend!
  • Netvibes
  • Ping.fm
  • Print this article!
  • Reddit

Technorati Tags: , , , , ,

Posted in .Net, CSharp, MonoTouch, Rambling, Software, TinyIoC.

Tagged with , , , , , .


Announcing: TinyIoC – An Easy to Use, Hassle Free, Inversion of Control Container

Introduction

Whenever I start a new “pet” project I usually *want* to use IoC, but I don’t really want the hassle of taking a dependency on a container, or adding another binary to my project. Usually this leaves me using “poor man’s IoC”, whereby I define dependencies in my constructors, but I pass them in manually or construct them using constructor chaining.

I’ve thought for some time that it would be useful to put together a container that fits the bill for that scenario, but also attempts to “lower the barrier of entry” for developers that are new to IoC, and may be scared off by the “big boys”. A couple of weeks ago @DotNetWill posted his simplified container, and that gave me the kick up the backside I needed to create my own :-)

Introducing TinyIoC

Now you might ask “do we really need *another* IoC container?” – and it’s a reasonable question. We already have Unity, Ninject, StructureMap, AutoFac.. the list goes on. TinyIoC makes no attempt to go “head to head” with any of these other containers, instead TinyIoC has been designed to fulfil a single key requirement:

To lower the “level of entry” for using an IoC container; both for small projects, and developers who are new to IoC.

To that end, TinyIoC attempts to stick the following core principals:

  • Simplified Inclusion. No assembly to reference, no binary to worry about, just a single cs file you can include in your project and you’re good to go. It also works on Mono, and on MonoTouch for the iPhone / iPad.
  • Simplified Setup. With auto-resolving of concrete types and an “auto registration” option for interfaces, setup is a piece of cake. It can be reduced to 0 lines for concrete types, or 1 line if you have any interface dependencies.
  • Simple, “Fluent” API. Just because it’s Tiny, doesn’t mean it has no features. A simple “fluent” API gives you access to the more advanced features, like specifying singleton/multi-instance, strong or weak references or forcing a particular constructor.

The following snippet gives an example of the simplified setup:

// TinyIoC provides a lazyily constructed singleton
// version of itself if you want to use it.
var container = TinyIoCContainer.Current;

// By default we can resolve concrete types without
// registration
var instance = container.Resolve<MyConcreteType>();

// We can automatically register all concrete types
// and interfaces with a single call.
container.AutoRegister();
var implementation = container.Resolve<IMyInterface>();

So Where Now?

If you want to grab the source, read the tests, or take a look at some more complex examples of the API, wander on over to the homepage on bitbucket. I’m happy to take comments and suggestions – just grab me on Twitter or ping me an email from the contact form.

Over the next few weeks I will be posting a series of “beginners” articles on the hows and whys of IoC. I will be using TinyIoC specifically, but the majority of concepts and content can equally apply to other containers. I may even do a “File, New” screencast to show how “un-scary” this stuff is, and how it doesn’t really add any extra development effort,

Share:
  • Twitter
  • DotNetKicks
  • DotNetShoutout
  • Google Bookmarks
  • Digg
  • del.icio.us
  • Live
  • Technorati
  • StumbleUpon
  • E-mail this story to a friend!
  • Netvibes
  • Ping.fm
  • Print this article!
  • Reddit

Technorati Tags: , , , , ,

Posted in .Net, CSharp, Software, TinyIoC.

Tagged with , , , , , .


Moving a Repository from SVN to Mercurial With Full History

Disclaimer

Let me start with a disclaimer. I’ve only been using Mercurial for 2 days so my nomenclature may be completely wide of the mark. Hopefully this post will help other hgnewbies with what is probably a common requirement.

Introduction

I keep all of my pet projects in my own Subversion repository but I’ve recently decided to give this distributed version control shenanigans a whirl. I ummed and arred about Git or Mercurial, but in the end I plumped for Mercurial, with a bitbucket account, as it seems to have more ubiquitous support. I’m about to release a project I’ve been working on for the last week or so and thought it would be nice to release it via bitbucket – complete with the version history I’d build up in Subversion.

Turns out, it’s really rather easy!

I’m Converted!

I’m assuming at this point you have the commandline version of Mercurial (hg) installed and working. If you don’t then you should probably go and do that first :-) I’ve also assumed you’ve already created a mercurial repository (bitbucket or elsewhere) called “myproject”.

In my scenario I was converting a single project with no trunk, branch or tag directories. The convert command is capable of handling much more advanced scenarios – take a look at the documentation for more infomation.

First things first you need to edit your Mercurial settings (.hgrc for *nix, Mercurial.ini in your user dir for Windows) and add the following lines:

[extensions]
hgext.convert=

This will add the “convert” command extension to our client. Next up we clone our repository and use the new convert command to add the SVN changesets into it:

hg clone https://bitbucket.org/myuser/myproject

hg convert http://mysvn.server.com/svn/myproject/ myproject

The convert command will now start counting down the revisions and adding each one to our local hg repository. This may well take some time :-)

Potential gotcha: it appears that the convert extension doesn’t work properly with Subversion repositories over http that require authentication. If you get multiple “http authorization required” messages and prompts for your username/password then you have a problem. The only solution I found was to temporarily disable authentication while I did the conversion :-(

Once the conversion had finished we push our changes back:

cd myproject

hg push

Now at this point for me the push worked fine but my local repository had no files in it – despite insisting it was up to date. This may be my lack of knowledge on Mercurial, or it might be a bug, but deleting the myproject directory locally and cloning the remote repo again sorted things out.

Conclusion

All in all a pretty trivial task, albeit one that takes a while with a large repository. The only big issue is the authentication one I mention above – this may well be a showstopper for you if you can’t control the ACL on your Subversion repository.

Share:
  • Twitter
  • DotNetKicks
  • DotNetShoutout
  • Google Bookmarks
  • Digg
  • del.icio.us
  • Live
  • Technorati
  • StumbleUpon
  • E-mail this story to a friend!
  • Netvibes
  • Ping.fm
  • Print this article!
  • Reddit

Technorati Tags: , , , , ,

Posted in .Net, Mercurial, Software.

Tagged with , , , , , .


So What Is This “Thread Safe” Thing Anyway?

Introduction

Following on from my previous post about a “Thread Safe” Dictionary, and the subsequent comment from Rajeesh, made me think that perhaps a general post on “thread safety” was in order.

Stop With the Quotes Already!

The astute amongst you may notice I always try and put the phrase “thread safe” in quotes; and there is a good reason for that! “Thread safe” is a pretty horrible term (although I can’t think of a better one) that doesn’t really give enough detail for what exactly we mean when we express that a class is “thread safe”. As far as I’m concerned, my “library” classes are thread safe if:

“All public static and instance methods and properties on the class are safe to be called concurrently from multiple threads.”

What this certainly does *not* mean is:

“You do not have to consider thread safety or concurrency issues in your own code that uses this class.”

So in the instance of our dictionary if you get/set a value and then in subsequent lines of code you *assume that the value you got or set hasn’t changed* then you have a concurrency issue in *your* code and you will *need to address it, likely using the same synchronisation primitives we used internally in our SafeDictionary class.*

Some Examples

As an example we can take similar code to the snippet that Rajeesh posted:

// Check the item exists and process
// if it does
if (mySafeDictionary["Testing"] != null)
{
    // Process element
    ProcessElement(mySafeDictionary["Testing"]);
}

Although each of those calls to the SafeDictionary are themselves threadsafe, we are making an assumption in *our code* that those value won’t change between the “if” statement and our call to ProcessElement. This particular scenario is one reason why we should always try to use TryGetValue, rather than the “if it exists do this with it” approach above. To this end we should probably alter our SafeDictionary to explicitly deny gets:

public class SafeDictionary<TKey, TValue>
{
    private readonly object _Padlock = new object();
    private readonly Dictionary<TKey, TValue> _Dictionary = new Dictionary<TKey, TValue>();

    public TValue this[TKey key]
    {
        set
        {
            lock (_Padlock)
            {
                _Dictionary[key] = value;
            }
        }
    }

    public bool TryGetValue(TKey key, out TValue value)
    {
        lock (_Padlock)
        {
            return _Dictionary.TryGetValue(key, out value);
        }
    }
}

If you now try and access a member using the array syntax, rather than through TryGetValue you will get a compile time error like:

The property or indexer ‘Variabler.this[string]‘ cannot be used in this context because it lacks the get accessor.

From that simple example you may think that TryGetValue solves all our problems; but unfortunately it still isn’t able to save your from yourself! To reiterate what I said earlier, you need to consider concurrency yourself if you *assume that the value you got or set hasn’t changed*. Assuming we expand our SafeDictionary to include all of the options that the normal Dictionary supports, take the following horribly contrived example:

public List<String> GetKeysToProcess()
{
    object myObject;
    List<String> keysToProcess = new List<String>();

    // Check to see if the type is valid for
    // processing
    foreach (var currentKey in myDictionary.Keys)
    {
        if (myDictionary.TryGetValue(currentKey, out myObject))
        {
            if (myObject.GetType() == typeof(ProcessorClass))
                keysToProcess.Add(currentKey);
        }
    }

    return keysToProcess;
}

Now there’s a chance that a key might have been removed between the start of the foreach and us actually using it; but as we use TryGetValue that doesn’t matter – the value just won’t resolve. The key here (pardon the pun) is that we are building and returning a list that *makes assumptions about the contents of the dictionary*. Even if in our consuming code we stick to TryGetValue to handle items being deleted, there’s nothing in this example preventing another thread changing any of the items to be a different type – effectively rendering our List of “Keys to process” completely invalid.

Conclusion

The examples above are very contrived, and I’d hope nobody would ever write those exact pieces of code; but hopefully it illustrates the point that *just because you are working with a “Thread safe” object doesn’t mean you can ignore thread safety concerns in your own code*.

Share:
  • Twitter
  • DotNetKicks
  • DotNetShoutout
  • Google Bookmarks
  • Digg
  • del.icio.us
  • Live
  • Technorati
  • StumbleUpon
  • E-mail this story to a friend!
  • Netvibes
  • Ping.fm
  • Print this article!
  • Reddit

Technorati Tags: , , , ,

Posted in .Net, CSharp.

Tagged with , , , , .


“Thread safe” Dictionary(TKey,TValue)

Update : Based on a comment on this post I’ve added a follow up post that covers the question: What is This “Thread Safe” Thing Anyway?

Introduction

A pet project I’m currently working on requires the use of an internal Dictionary to store “registered” data, which is a pretty common requirement. For this particular project I’d like to at least *attempt* to make it “thread safe” on .NET 3.5, with an eye to moving it to the ConcurrentDictionary in .NET 4 which promises not only thread safety, but more granular locking to increase multi-threaded performance.

A simple enough task, but one that I’ve seen many people make mistakes implementing.

Just Locking Writes?

It’s obvious we need to do some kind of syncronisation primitive around our writes, but first impressions might make you think that read should be ok – especially if we stick to the preferred TryGetValue pattern instead of “if it exists then get the value”:

object myValue;

// This is obviously not thread safe.
// Something else can alter the collection
// between ContainsKey and reading the
// value.
if (dictionary.ContainsKey("Testing"))
{     myValue = dictionary["Testing"];
}

// Using TryGetValue looks safe though?
// Doesn't it?!
if (!dictionary.TryGetValue("Testing", out myValue))     throw new KeyNotFoundException();

Unfortunately if we fire up Reflector, and take a look at how TryGetValue is implemented, it’s pretty obvious it has exactly the same concurrency problem as the first method above:

public bool TryGetValue(TKey key, out TValue value)
{
    int index = this.FindEntry(key);
    if (index >= 0)
    {
        value = this.entries[index].value;
        return true;
    }
    value = default(TValue);
    return false;
}

Ok, So I Will Lock Reads and Writes?

The next obvious approach would be to find everywhere in our code where we access the Dictionary, for either reading or writing, and use a syncronisation primitive, such as lock, to ensure we’re only accessing it from a single thread at any one time:

private readonly object padlock = new object();
private readonly Dictionary<string, object> dictionary = new Dictionary<string, object>();

private void Test()
{
    object myValue;

    // Now we lock before we do anything
    lock (padlock)
    {
        if (dictionary.ContainsKey("Testing"))
        {
            myValue = dictionary["Testing"];
        }
    }

    lock (padlock)
    {
        if (!dictionary.TryGetValue("Testing", out myValue))
            throw new KeyNotFoundException();
    }
}

Simple enough, but you’re relying on locking around every access, which is not only ugly, but also potentially prone to errors if you miss one. Also, once we move our code to .NET 4, and the new ConcurrentDictionary, we will have to go through the code and remove each lock in turn – pretty laborious!

Composition, Composition, Composition!

In this approach we wrap our nasty non-thread safe dictionary in our own class, expose the methods we want to use, and take any locks accordingly. This class only implements “array” access and TryGetValue, but is sufficient to show the approach:

public class SafeDictionary<TKey, TValue>
{
    private readonly object _Padlock = new object();
    private readonly Dictionary<TKey, TValue> _Dictionary = new Dictionary<TKey, TValue>();

    public TValue this[TKey key]
    {
        get
        {
            lock (_Padlock)
            {
                return _Dictionary[key];
            }
        }
        set
        {
            lock (_Padlock)
            {
                _Dictionary[key] = value;
            }
        }
    }

    public bool TryGetValue(TKey key, out TValue value)
    {
        lock (_Padlock)
        {
            return _Dictionary.TryGetValue(key, out value);
        }
    }
}

As we prevent any direct access to the Dictionary, and use our lock internally whenever we need to access it, we can now use our SafeDictionary in code without worrying about concurrency issues – both for reading and for writing!

To .Net 4 ?

As I mentioned earlier .Net 4 will be shipping with several “thread safe” collections, including a dictionary, in the new System.Collections.Concurrent namespace. As we have our own SafeDictionary implementation we have a few options here:

  • We could go through our code and replace all references to SafeDictionary with ConcurrentDictionary. We don’t have any locks in our main code so we could do this with a direct replacement.
  • We could alter our SafeDictionary to use a ConcurrentDictionary internally, and remove all of our internal locks.
  • If we don’t mind exposing extra methods we can remove all of the implementation from SafeDictionary and just derive it from ConcurrentDictionary:
public class SafeDictionary<Tkey, TValue> : ConcurrentDictionary<Tkey, TValue>
{
}

Conclusion

Quite a long blog post for quite a simple issue, but even simple concurrency can be the source of mistakes and headaches. Once .NET 4 arrives with its concurrent collections, parallel extensions and parallel debugging options hopefully at least *some* of this headache will go away.

Share:
  • Twitter
  • DotNetKicks
  • DotNetShoutout
  • Google Bookmarks
  • Digg
  • del.icio.us
  • Live
  • Technorati
  • StumbleUpon
  • E-mail this story to a friend!
  • Netvibes
  • Ping.fm
  • Print this article!
  • Reddit

Technorati Tags: , , , ,

Posted in .Net, CSharp.

Tagged with , , , , .