Just read this excellent post by Eric Lippert about why it is incorrect to describe references in .NET as a pointer to a memory location

In the article he goes on to explain the differences between a pointer and a reference, and why they are not mutually interchangeable.

I have to admit, I’ve been incorrectly defining a reference. After reading this article from now on my definition of a “reference type” will be a type which contains a reference to an object held internally within the .NET GC. This reference is not *necessarily* a pointer and should be thought of more like a unique handle to the GC’s object than a pointer to a memory address.

In my last article on the topic of database development, I covered performing database migration using MigratorDotNET.

Next, I wanted to look at the mapping process to the object model. I’d already decided I was going to use NHibernate as my ORM, but the detail was in hooking up NHibernate to the database. NHibernate’s XML syntax is pretty straightforward and incredibly powerful, but once again it’s another language i’m forced to deal with – i’m most efficient working in my primary language so the idea of slowing down when dealing with these mapping files by hand was really not in question.

Initially I looked into ActiveRecord (admittedly not into a whole lot of detail) but wasn’t excited by the framework. ActiveRecord performs it’s mappings from objects to database through attributes and it just seemed to me like an abuse of SoC. If i should want to change my ORM (unlikely, but i’m working within that constraint on this project), then it would have to support the same attribute syntax. Having said that however, there is a lot of momentum behind ActiveRecord, so i’m still reserving judgement on it’s applicability.

So apart from ActiveRecord, I went in search of another alternative to the XML mapping and recalled reading about Fluent NHibernate. In a nut-shell, Fluent NHibernate is a replacement for the XML mapping layer in NHibernate by defining the mapping in C#. Essentially the same benefits I got by using MigratorDotNet (type safety, compile-time checking etc) were available for defining my DB->OM mapping. Sweet!

A very quick spike with the project, and I immediately liked what I saw:

	public class NoteMap : ClassMap<Note>
	{
		public NoteMap()
		{
			Id(x => x.NoteId).GeneratedBy.Guid();
			Map(x => x.NoteTitle).WithLengthOf(64);
			Map(x => x.NoteData);
		}
	}

The equivalent XML mapping file (I won’t discuss it in detail in this post) would have been at least twice the size, and more importantly not refactor-friendly.

Because it’s in C# I was easily able to unit-test this mapping, with a little assistance. In fact it was so successful, it helped me discover a bug in my database migration script!

	[TestFixture]
	public class NoteMapping_Test : BaseTestMappings
	{
		[Test]
		public void TestCanAddNote()
		{
			Note note = new Note
			            	{
			            		NoteTitle = "Title",
			            		NoteData = "Data`"
			            	};
			Session.Save(note);

			Session.Flush();
			Session.Clear();
			Note fromDb = Session.Get<Note>(note.NoteId);
			Assert.AreNotSame(note, fromDb);
			Assert.AreEqual(note.NoteData, fromDb.NoteData);
			Assert.AreEqual(note.NoteTitle, fromDb.NoteTitle);
			Assert.AreEqual(note.NoteId, fromDb.NoteId);
		}
	}


	public class BaseTestMappings
	{
		protected SessionSource Source { get; set; }
		protected ISession Session { get; private set; }

		[SetUp]
		public void SetUp()
		{
			Source = new SessionSource(new TestModel());
			Session = Source.CreateSession();
			Source.BuildSchema(Session);
			CreateInitialData(Session);
			Session.Clear();
			Session.Transaction.Begin();
		}

		[TearDown]
		public void TearDown()
		{
			Session.Transaction.Rollback();
			Session.Close();
			Session.Dispose();
		}

		public class TestModel : PersistenceModel
		{
			public TestModel()
			{
				Assembly ass = typeof(NoteMap).Assembly;
				addMappingsFromAssembly(ass);
			}
		}
	}

What’s happening here is that Fluent NHibernate allows me to instantiate an NHibernate instance just by creating a Model. The model contains a list of all of the mappings applicable for my application and I pass that directly into the NHibernate session. Any of my tests which I want connected to a database will now have transaction management and a session for performing querying. I can use this in my application too with just about the exact same code, so instantiate a session and pass in the model.

It works very well and i’ve sucessfully removed the XML file with a type-safe C# mapping engine. The problem this poses, however is now I have two places where I have defined what my data structures look like. One in the MigratorDotNET framework, and the other in FluentNHibernate to map the data model. This means that to make any any change to the model would involve no less than 3 changes – the POCO, FluentNHibernate and MigratorDotNET.

Next time, I want to discuss ways of reducing this friction and streamline the refactoring process.

(There are some websites which i wish to attribute for some of the code and ideas i’ve expressed here but have since lost the links. If you see anything that’s yours, please let me know so I can appropriately credit)

http://weblogs.asp.net/nunitaddin/archive/2008/12/02/testdriven-net-2-18-nunit-2-5-beta.aspx

Jamie covers off some of the new things in NUnit 2.5 which are pretty cool, but the one thing he omitted (and I think is quite awesome) is the Assert.Throws<T>(); assertion.

Previously (NUnit 2.4 and below) you would either have to use the [ExpectedException()] attribute or implement the exception handling logic yourself in your test. Issues with using the ExpectedException attribute are well known. I’m doing this without VS at hand, so forgive me if parts are wrong, but for example:


[Test]
[ExpectedException(typeof(ArgumentNullException))]
public void TestArgumentNullThrowsException()
{
    new MyObject(null);
}
  
  
[Test]
public void TestArgumentNullThrowsException()
{
  bool thrown = false;
  
  try
  {
    new MyObject(null);
  }
  catch (ArgumentNullException e)
  {
    // Check if the message is correct
    thrown = true;
  }
  catch (Exception e)
  {
    throw; // Any unexpected exceptions still get raised up
  }
  finally
  {
    Assert.IsTrue(thrown, "Expected exception should be thrown, but was not");
  }
}

Well with NUnit 2.5, you can lambda the entire thing and the testcase becomes so much simpler:


[Test]
public void TestArgumentNullExceptionIsThrown()
{
  Assert.Throws<ArgumentNullException>( () =>  new MyObject(null)  );
}

…And why is this good for TestDriven.NET? It means I can install NUnit 2.5 and actually use it with TD.NET, instead of using the GUI test runner.

I’m digging deeper into WPF and learning more about XAML, web-XAML and XBAP. This evening i’ve stumbled across a nasty side-effect. When i’m creating an XBAP project in Visual Studio and run it without the debugger, the XBAP gets cached somewhere and any subsequent changes don’t show up – It keeps running the old XBAP file.

I’ve done a little digging and found out that the XBAP is cached by Click-Once when you run it outside the debugger. When executed, the application is deployed and run using Click-Once which (amongst other things) versions the assembly, checks for dependencies on the target machine and loads the application. If the application has been cached, then it will use the cached version instead. However you don’t have this problem when you’re running through the debugger because the process is launched by Visual Studio, and it will always run the latest assembly. This bugs me because I more frequently run my development apps outside the debugger and only attach when I need to. I know when my code is generally going to work, and most errors can be spotted without the need for attaching a debugger to the process.

Anyway the temporary solution is to add a pre-build event which clears the Click-Once cache and upon execution, the correct version of my app will be spawned. The command for the event is:

%windir%system32rundll32 %windir%system32dfshim.dll CleanOnlineAppCache

You can also run the command mage.exe -cc which is a CLI tool to do the same thing. More research is required into Click-Once and all this. Please note that this is a preliminary post, and I haven’t done much research in depth into the problem – if you know of a better way, i’d like to hear it!

I was recently reading a post about writing non-threadsafe code which talks about the main peril of multi-threading, and one way you can work around it.

I’ve long been a believer that doing anything multi-threaded is fraught with danger and you have to tread incredibly carefully when doing so. I say this with experience. What I learnt from reading that post wasn’t in the content, but in the comments, which talked about the Interlocked class for performing simple, thread-safe increments and decrements of operators.

So i decided to try it and see what the benefit really is, and i was surprised by by the results! I did my own profile against 3 scenarios:

  1. No thread safety (fast comparitively, though gave incorrect results)
  2. Locking using “lock” keyword (correct, but very slow by magnitude of nearly 10x)
  3. Locking using Interlocked class (correct, and fast – faster than no thread safety in some test runs)

Clearly these results aren’t scientific, but are quite good to give relative indicators of performance. I’ve reproduced the code below.


using System;
using System.Diagnostics;
using System.Threading;
using NUnit.Framework;

namespace ThreadingExample
{
	public interface IThreadTest
	{
		int Value { get; }
		void Debit();
		void Credit();
	}

	public class NonThreadSafe : IThreadTest
	{
		public int Value { get; private set; }

		public void Debit()
		{
			Value--;
		}

		public void Credit()
		{
			Value++;
		}
	}

	public class ThreadSafe : IThreadTest
	{
		public int Value { get; private set; }

		object lockSentinel = new object();

		public void Debit()
		{
			lock (lockSentinel)
			{
				Value--;
			}
		}

		public void Credit()
		{
			lock (lockSentinel)
			{
				Value++;
			}
		}
	}

	public class ThreadSafeUsingInterlocking : IThreadTest
	{
		private int value;
		public int Value
		{
			get { return value; }
			private set { this.value = value; }
		}

		public void Debit()
		{
			Interlocked.Decrement(ref value);
		}

		public void Credit()
		{
			Interlocked.Increment(ref value);
		}
	}

	[TestFixture]
	public class TestClass
	{
		[Test]
		public void TestNonThreadSafe()
		{
			NonThreadSafe nts = new NonThreadSafe();

			ExecuteThreadedTest(nts);

			Assert.AreEqual(0, nts.Value);
		}

		[Test]
		public void TestThreadSafe()
		{
			ThreadSafe ts = new ThreadSafe();

			ExecuteThreadedTest(ts);

			Assert.AreEqual(0, ts.Value);
		}

		[Test]
		public void TestThreadSafeUsingInterlocking()
		{
			ThreadSafeUsingInterlocking tsui = new ThreadSafeUsingInterlocking();

			ExecuteThreadedTest(tsui);

			Assert.AreEqual(0, tsui.Value);
		}

		private void ExecuteThreadedTest(IThreadTest threadTest)
		{
			int maxIterations = 99999999;
			DateTime start = DateTime.Now;
			Thread t1 = new Thread(() =>
			{
				for (int i = 0; i < maxIterations; i++)
				{
					threadTest.Credit();
				}
			}
			);
			t1.Name = "t1";

			Thread t2 = new Thread(() =>
			{
				for (int i = 0; i < maxIterations; i++)
				{
					threadTest.Debit();
				}
			}
			);
			t2.Name = "t2";

			t1.Start();
			t2.Start();

			t1.Join();
			t2.Join();

			DateTime finish = DateTime.Now;
			Debug.WriteLine(String.Format("Took {0}ms to complete", (finish - start).TotalMilliseconds));
		}
	}
}

Reading an article about unit testing got me thinking about some of the tools i’d love to sink my teeth into.

I’m documenting them here in case i forget.

Backend
NHibernate (ORM)
SQLLite (DB)

Framework
Castle Windsor/Ninject (DI)
Lof4Net (Logging)
LINQ (Language Querying)
Tree Surgeon (Environment setup)

Testing
NUNit (Unit testing)
Rhino.Mocks/Moq (Mocking)
WatIn (UI testing)

Build Integration
Nant (Build tool)
CC.NET (CI server)

UI
WPF (GUI)
ASP.NET MVC /Monorail (Web engine)
PRISM (WPF App framework)
NHaml (MVC View Engine)

a lot of these i have or currently do use….some of them i have only ever played around with and a few i’ve never even touched.

At least me putting it down on paper (or bits, in this case) is a reminder of what i’m keen to try, and will get to it soon.

Sometimes though when you’re changing interfaces across several projects, you can end up in a stink because a method reference is removed or a signature is changed, and you end up with the following error:

When i build in Visual Studio, in order to save time, I don’t always do a <ctrl><shift>-<b> (Rebuild Solution). instead, i do a <alt>-<b>,<u> in order to rebuild just the project, and its dependencies (faster build).

I’ve had this error come up a few times, and it’s easy to solve – in case i ever forget here it is:.

Server Error in ‘/’ Application.
——————————————————————————–

?
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.MissingMethodException: ?

When you get this problem, just re-build the entire project.

I’ve seen this now twice in about 30 mins, and its bugging me.

One of the developers i work with is writing code like this:

string postingUrl = CmsHttpContext.Current.Posting.Url.ToLower(CultureInfo.InvariantCulture);

Whats bugs me with this code is that it shows no understanding or care for defensive programming.

Q1: Why do you assume that CmsHttpContext.Current is safe? Sure, within ASP.NET the framework creates a new Context for you upon request, and (in this case) Microsoft CMS wraps the HttpContext and guarantees you a copy of a context for you. Under these known conditions, the CmsHttpContext.Current is safe.

Now that’s been chained onto Posting, which throws the exception. Why assume that you’ve hit a posting? Why assume that there would be a posting at all? This kind of lack of thinking just demonstrates lazy programming, to me.

*grumble*

The DateTime.Parse() method (and all its derivatives, i assume) are locale sensitive and will assume that the string you provide it is in the standard ISO date format, or in the format for your locale.

The buggy implementation I found in our system was calling DateTime.Parse() with a value of “23-07-2007”, which threw an exception citing that the string was not in the correct format. I dug around a bit with the code and tried different implementations with different results. It was only after i provided it a US date value (which it did not baulk at) I realised that my system’s locale was set to English (US).

The code was wrong to assume the current system locale is the expected input data format, in the first place, but this one tripped me up for a little while.