The Visitor Pattern Explained

In my last job interview I got a (rather vague) question about traversing a tree and operating on the tree nodes. I think I’ve a lot of experience in programming but I couldn’t figure out the answer on my own. The answer the guy wanted to hear was: visitor pattern.

I had never heard of it before. So, in preparation for my next job interview, I thought I take a look at it.

While trying to figure it out, I stumbled over this quote:

The Visitor pattern is possibly the most complicated design pattern you will face. (Source)

I totally agree. (And this is probably why I’ve never heard or used it before.)

But since I’m not a quitter I went on and tamed it. So, in this article I’m going to shed some light on this mysterious design pattern.

Read more →

P/Invoke Tutorial: Pinning (Part 4)

Sometimes a C/C++ function needs to store data you pass to it for later reference. If such data is a managed object (like a string or class) you need to make sure that the garbage collector doesn’t delete it while it’s still used/stored in the native code.

That’s what pinning is for. It prevents the garbage collector from deleting and moving the object.

Read more →

Breaking .NET’s Random class

Security is hard. In a current project I saw some code that created some access tokens based on a random number generator – .NET’s Random class. The code used an instance of Random stored in static field and I got curious:

If you have such a long living Random instance, could you predict the random values after generating a few of them?

It turns out, it is possible. And you only need to read 56 55 “random” values to predict all future values.

Read more →

Mutexes in .NET

The Mutex class in .NET is a little bit tricky to use.

Here’s an example how I got it to do what I want:

/// <summary>
/// A simple, cross application mutex. Use <see cref="Acquire"/> to acquire it
/// and release it via <see cref="Dispose"/> when you're finished.
/// </summary>
/// <remarks>
/// Only one thread (and thus process) can have the mutex acquired at the same
/// time.
/// </remarks>
public class SimpleMutex : IDisposable
{
    private readonly Mutex m_mutex;

    /// <summary>
    /// Acquires the mutex with the specified name.
    /// </summary>
    /// <param name="mutexName">the mutex's name</param>
    /// <param name="timeout">how long to try to acquire the mutex</param>
    /// <returns>Returns the mutex or <c>null</c>, if the mutex couldn't be
    /// acquire in time (i.e. the current mutex holder didn't release it in
    /// time).</returns>
    public static SimpleMutex Acquire(string mutexName, TimeSpan timeout)
    {
        var mutex = new SimpleMutex(mutexName);
        try
        {
            if (!mutex.m_mutex.WaitOne(timeout))
            {
                // We could not acquire the mutex in time.
                mutex.m_mutex.Dispose();
                return null;
            }
        }
        catch (AbandonedMutexException ex)
        {
            // We now own this mutex. The previous owner didn't
            // release it properly, though.
            Trace.WriteLine(ex);
        }

        return mutex;
    }

    private SimpleMutex(string mutexName)
    {
        this.m_mutex = new Mutex(false, mutexName);
    }

    public void Dispose()
    {
        this.m_mutex.ReleaseMutex();
        this.m_mutex.Dispose();
    }
}

You can use it like this:

using (SimpleMutex.Acquire("MyTestMutex", Timeout.InfiniteTimeSpan))
{
    Console.WriteLine("Acquired mutext");
    Console.ReadKey();
}

Console.WriteLine("Released mutext");

If you run your program twice, one will acquire the mutex and the other one will wait – until you press a key in the first one.

Note: If you forget to call Dispose() on this mutex, the operating system will make sure that the mutex is released when the program terminates. However, the next process trying to acquire this mutex will then get an AbandonedMutexException (which is handled properly in Acquire() though).