# Tuesday, December 01, 2009

Ruby was the impetus for me to write a Guard clause that automatically get a parameter name from code. What do I mean by that? This passes:

[Test]
public void Expression_guard_can_get_parameter_name_from_expression()
{
	object address = null;
	Assert.Throws<ArgumentException>(() => Guard.AgainstNull(() => address),
		"The parameter address must not be null");
}

Notice how I didn’t specify the string “address” anywhere, the Guard.AgainstNull method got it from the expression () => address. I’m sure I’ve used constructs like this in C# before, but I haven’t written any yet. I wonder in what other ways I can abuse Expressions?

The implementation, that is not well tested by any means:

public static void AgainstNull<T>(Expression<Func<T>> expression)
{
	AgainstNull(expression, "expression");

	string paramName = "";
	var memberExpression = expression.Body as MemberExpression;
	if (memberExpression != null)
	{
		paramName = memberExpression.Member.Name;
	}
	T instance = expression.Compile().Invoke();
	AgainstNull(instance, paramName);
}
Tuesday, December 01, 2009 2:14:31 AM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [0]  | 
# Saturday, November 07, 2009

I've been playing around with Visual Studio 2010, and of course the latest ReSharper, version 5. Unfortunately my NUnit tests wouldn't run inside the ReSharper runner. Instead they would spin for a second then turn grey, like nothing happened.

Running the tests under the debugger turned up an interesting exception in the VS output window: BadImageFormatException. I also noticed a bunch of DLLs being loaded out of the v2.0 framework GAC, and not .NET 4. Shouldn't my .NET 4 app be using the .NET 4.0 GAC?

Of course it should. There's an easy fix to this. ReSharper shells out to another exe that actuall runs the unit tests JetBrains.ReSharper.TaskRunner.exe. If we modify the JetBrains.ReSharper.TaskRunner.exe.config in the ReSharper installation directory we can force the test runner to run under the .NET 4.0 framework. At the bottom of the file you'll find the associated startup element already there, just commented out and with the .NET 4.0 beta 1 framework version. To fix it, just incomment it and change the version to the .NET beta 2 framework version.

<!-- Needed in dev10, not needed in dev9/8 --> <startup> <requiredRuntime version="v4.0.21006"/> </startup>

Now you can run unit tests via ReSharper in VS 2010 beta 2.

Saturday, November 07, 2009 7:59:07 PM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [0]  | 
# Monday, October 19, 2009

Most every language has a sweet spot, something it does better than any other language around it.

C and C++ are really good for writing console video games because of its speed, portability, and deterministic finalization.  Perl is really good at string manipulation. Java has a gazillion OSS frameworks and application servers. Ruby is damn pretty and has a couple of really super productive web frameworks.

Erlang has a very succinct and elegant syntax, a syntax that is highly optimized for writing recursive functions. One could argue that’s just a property of being a functional language, but I think there’s more too it than just being functional.

C# 3 has a decent functional syntax that is clearly more succinct than Java or C# 2, but it just doesn’t stack up to Erlang.

Warning: don’t use these code samples in production code! They use Ω(n) extra storage space and are toy functions.

For example, take this Erlang quick sort function:

qsort([]) -> [];
qsort([Pivot|T]) ->
	qsort([X || X <- T, X < Pivot])
	++ [Pivot] ++
	qsort([X || X <- T, X >= Pivot]).

That is, IMO, beautiful code.  Small, compact, succinct, powerful, readable. On the other hand, what does a comparable implementation look like in C# 3? 

static IEnumerable<int> Qsort(IEnumerable<int> list)
{
    if (list.Count() <= 1)
        return list;

    int pivot = list.First();
    var tail = list.Skip(1).Take(list.Count() - 1);

    var result = new List<int>();
    result.AddRange(Qsort(tail.Where(o => o < pivot)));
    result.Add(pivot);
    result.AddRange(Qsort(tail.Where(o => o >= pivot)));
    return result;
}

It works, it doesn’t contain any loops and only one if statement (the initial C# 2 version was even longer and uglier), but its still very much lacking in the beautiful code department.  Did you also notice it was more than twice as long as the Erlang function? Perhaps you can improve the syntax?

I don’t have numbers to prove this, but the Erlang implementation can also be made faster with a lot less effort since each recursive call can be run in parallel.  Try that in C# without writing extra threading code. Even if you did, your threads are probably going to be a lot slower than the light weight threads in Erlang.

Recursive functions in Erlang are definitely a sweet spot.

Monday, October 19, 2009 3:52:56 PM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [1]  | 
# Friday, October 09, 2009

Sometimes you need a paradigm shift, a different way to look at the same set of problems. Erlang I hope will give me that paradigm shift. Hopefully I can add another a screwdriver to my toolbox, if not, hopefully something besides a hammer.

I just bought a copy (on PDF) of Programming Erlang Software for a Concurrent World. I’ve only gotten through the first few pages of chapter 1, and so far I’m impressed. I guess its no surprise as the book is published by Pragmatic Programmers.

I finally understand why mathematicians like functional languages.  Its so obvious now, and it has a lot to do with immutability. From the book:

When I went to school, my math teacher said, “If there’s an X in several different parts in the same equation, then all the Xs mean the same thing.” That’s how we can solve equations: if we know that X+Y=10 and X-Y=2, then X will be 6 and Y will be 4 in both equations. But when I learned my first programming language, we were shown stuff like this:
X = X + 1
Everyone protested, saying “you can’t do that!” But the teacher said we were wrong, and we had to unlearn what we learned in math class. X isn’t a math variable: it’s like a pigeon hole/little box.... In Erlang, variables are just like they are inmath.When you associate a value with a variable, you’re making an assertion—a statement of fact. This variable has that value. And that’s that.

I guess mutability is a strange beast for most people when learning to program, forcing a lot of them to quit while in their first year of CS.  Well, that and pointers. Its an odd way to think of things for people living in a concrete world. I wonder if first year CS students wouldn’t have an easier time learning a functional language?

Friday, October 09, 2009 1:09:12 AM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [0]  | 
# Thursday, October 01, 2009

I found another reason to love open source NUnit over MSTest, NUnitEx. NUnitEx provides a fluent DSL to write NUnit assertions where Visual Studio intellisense is your guiding friend. I’m sure you’re thinking, “Yeah whatever, show me some code.”

[Test]
public void AdjacencyGraph_is_directed_by_default()
{
    var graph = new AdjacencyGraph<Task, TaskDependency>(DoNotAllowParallelEdges);
    graph.IsDirected.Should().Be.True();
}

Nice eh? graph.IsDirected is the property I want to test.  Everything after that is the NUnitEx extension methods. I know I find it much more readable than this:

[Test]
public void AdjacencyGraph_is_directed_by_default()
{
    var graph = new AdjacencyGraph<Task, TaskDependency>(DoNotAllowParallelEdges);
    Assert.IsTrue(graph.IsDirected);
}

I would also like to add that this syntax is likely to be included in NUnit 3, which would be excellent!

Thursday, October 01, 2009 1:19:34 AM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [1]  | 
# Wednesday, September 23, 2009

Ive spent the last couple of days writing visual studio web tests to create a load test scenario for a critical section of application. Unfortunately i find it repetitive and boring.

The web tests recorder in VS doesn't capture everything and additionally it hurts to look at the produced code. I did find fiddler much better at recording tests but they still needed serious cleaning up.

I wish there was a more polished tool for this kind of test. I doubt other tools like JMeter are much better, and for .NET their probably worse because of viewstate and other platform specifics.

Wednesday, September 23, 2009 12:47:31 AM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [0]  | 
# Thursday, September 17, 2009

I just found another useful thing that resharper does for you, it can generate code to check for null method parameters.

image

Just put the cursor on the parameter….

image

Nice huh!?

Thursday, September 17, 2009 3:46:55 PM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [0]  | 
# Tuesday, September 15, 2009

Its amazing how one single line of code and a bad assumption (or misunderstanding) can cause all sorts of strange production issues.

The day started out with static content throwing exceptions that contained our UnitOfWork in the call stack.  My first question was, why on earth is a static resource request hitting our begin unit of work.  Well it turns out that we map all requests through the ASP.NET pipeline because of some nameless .NET document management module.  Unfortunately we generally don’t have wild card mapping enabled for ASP.NET in our dev environment because:

  1. We weren’t aware of the requirement.
  2. There’s no documentation surrounding proper dev environment setup (e.g. script).
  3. Only one dev in our entire organization has ever actively touched this module.

Why is the wildcard mapping a big deal?  Because a single page load will create 10, 20, or more HTTP get requests for static content.  If you have a threading bug in your begin request, they’re much, much more likely to show up with numerous requests. 

The sad truth of the matter is that because our environment we have a lot of NHibernate session factories, which is not normal for most applications. All of these session factories need to be configured and were using Fluent NHibernate to do so.  FNH is a great tool and makes configuration so much easier for us devs, but the fact remains FNH is not thread safe.

Seems easy enough, put a lock around the FNH stuff.  Well, we did, but the locker class was not static, we were relying on AutoFac to ensure that our NHibernate session factory class (the class with the lock) was a singleton.  Not too hard since AutoFac defaults to singleton.

Here’s the mistake.  ASP.NET creates not one, but many HttpApplication instances for each app domain.  I was falsely under the assumption is only ever created one, maybe two, but only ever kept one around.  Our AutoFac registration was setup in the Global instance constructor, so each app instance was getting its own container instance.  Can you guess why this is bad?

Each request had its own NHibernate configuration class with its own instance lock, thus multiple threads were entering into the critical section at the same time since they couldn’t see each other.  Lots of weirdness ensued.  We saw all sorts of the strange Nhibernate and FNH errors, things like property “XYZ” doesn’t exist on class “ABC".  Odd stuff that definitely smelt of threading.

I was starting to think SELECT was broken (e.g. AutoFac), but soon realized the errors of my ways with a simple Debug.Assert. Yep, multiple container, produce multiple “singletons”. 

WTF
Tuesday, September 15, 2009 1:54:46 AM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [0]  |