Friday, August 22, 2008

How to Replace Nested foreach Loops With a LINQ Expression

The following nested foreach loops search for all test methods in an assembly:

IEnumerable<String> tests = new List<String>();

Assembly a = Assembly.LoadFrom(dll);
Type[] types = a.GetTypes();

foreach (Type type in types)
{
if (type.IsDefined(typeof (TestClassAttribute), true))
{
MethodInfo[] methods = type.GetMethods();

foreach (MethodInfo method in methods)
{
if (method.IsDefined(typeof (TestMethodAttribute), true))
{
tests.Add(method.Name);
}
}
}
}

return tests;
Using LINQ this function can be rewritten in a very compact yet very readable form:
return from type in Assembly.LoadFrom(dll).GetTypes()
where type.IsDefined(typeof (TestClassAttribute), true)
from method in type.GetMethods()
where method.IsDefined(typeof (TestMethodAttribute), true)
select method.Name;
The first from - where part selects all types which are test classes. The second from where part walks through this list and searches for all methods which are test methods. From these methods the method name is added to the return value.

Note that in LINQ you can combine from - where clauses to generate nested queries.

Tuesday, August 19, 2008

Createing a Bootable DOS USB Stick with OpenSUSE 11.0

Install the FreeDos boot disk with

zypper install dosbootdisk

Create a DOS (type 0x0E) partition on your usb stick with

cfdisk /dev/[usbdevice]

and mark it Boot.

Create the dos boot disk in the partition you created with cfdisk

dosbootdisk [partition on usb stick]

Mount the dos partition and copy whatever additional files (BIOS upgrades, etc.) you need to the stick.

Monday, August 11, 2008

Listing all Test Methods in an Assembly Using C#


In order to write your own test runner you have to find out which methods of your assembly are marked with the attribute TestMethod.

This can be done easily using reflection as the following code example shows.


Assembly a = Assembly.LoadFrom("whatever.dll");
foreach (Type type in a.GetTypes())
{
if (type.IsDefined(typeof (TestClassAttribute), true))
{
MethodInfo[] methods = type.GetMethods();
foreach (MethodInfo method in methods)
{
if (method.IsDefined(typeof (TestMethodAttribute), true))
{
Console.Writeln(method.Name);
}
}
}
}



First we walk through all types of the assembly and search for the attribute TestClassAttribute.
Then we list all methods of the type and search for the attribute TestMethodAttribute.

In this example the result is simply written to the console.