Tag Archive for 'csharp'

Test, test, test!

Just a quick reminder to the programmers out there: make sure you write unit tests from the beginning!

I’ve recently been working on a NHibernate/ActiveRecord class library that’s fairly complex. When finished, it will wrap 125 database tables into C# classes. At the moment, it’s approximately 20% complete and I only just started writing unit tests yesterday. What happened when I ran the tests?

They bombed. It seems there is a class somewhere that has a table name misspelled. Unfortunately, the tables I have wrapped have a ton of BelongsTo relationships, so the SQL statements generated are massive (lazy loading doesn’t seem to fix this, for some reason). It’s going to be a huge headache to track down the spelling mistake since the database driver doesn’t provide any useful error information.

If I had written a unit test every time I added a new table mapping, I would have caught my spelling mistake almost instantly. But, since I waited until the library was 20% finished, I just made my job that much harder.

XML Serialize an object to a string

While working on a simple web API, I needed a way to serialize an object (using the XML serializer) to a string so I could return it as an API response. Unfortunately, there’s no Serialize() override for returning a string value. Instead, you’ll have to use a MemoryStream object and the System.Text.Encoding class.

1
2
3
4
XmlSerializer xs = new XmlSerializer(typeof(YourObject));
MemoryStream ms = new MemoryStream();
xs.Serialize(ms, instanceOfYourObject);
Console.WriteLine(Encoding.UTF8.GetString(ms.ToArray()));

Perhaps an extension method would be good in this case.

1
2
3
4
5
public static string GetXmlString(this XmlSerializer xs, object obj) {
	MemoryStream ms = new MemoryStream();
	xs.Serialize(ms, obj);
	return Encoding.UTF8.GetString(ms.ToArray());
}
1
2
XmlSerializer xs = new XmlSerializer(typeof(YourObject));
Console.WriteLine(xs.GetXmlString(instanceOfYourObject));