Tuesday 28 April 2009

Log4Net inside code run with MSTest unit testing

This was confusing me for a while so chances are it was also confusing someone else out there.

I could not get logging using log4net to output to the configured logger inside my unit tests
i tried
[assembly: log4net.Config. XmlConfigurator()]
in the unittest projects assembalyinfo but still log4net would not pick up the config

i found that the answer is to place an assembly initialise inside the unit test project, only one mind in the whole project. In fact if you do add 2 its an error

[AssemblyInitialize]
public static void AssemblyInitialize(TestContext testContext)
{
log4net.Config.XmlConfigurator.Configure();
}

Friday 3 April 2009

Brief intro to LINQ

Ive recently given a breif tutorial to the guys on our team on LINQ (Language integrated query)

As with Generics, LINQ is a large subject that i cant write up properly without spending quite a lareg amount of time on, so i'll give a breif overview with an example of a common usage in the context of a generic list.

Overview

LINQ is a technology (or language construct) that allows you to process data using functional programming logic to perform an operation. The LINQ API is an attempt to provide a consistent programming model that allows you to manipulate data. Using LINQ we are able to create directly within the C# programming language entities called query expressions, these query expressions are created from numerous query operators that have been intentionally designed to look and feel similar (but not identical) like SQL. Using LINQ you can interact with many sources of data, listed below:

LINQ implementations
LINQ to objects
Linq to SQL
Linq to entities
Linq to XML
There are other LINQ enabled technologies but these are the most common, for a grater list look online.

All of this means that you can interact with an XML dom in the same manner as you would with a list of objects or an ADO record set without having to learn different syntax for either.

LINQ Example

List names = new List(){"George", "William Smith", "bob", "Fred"};
IEnumerable subSetNames = from n in names
where n.Length >= 4
order by n
select n;
foreach(string name in subSetNames)
{
Console.Write(name);
}

The code above firstly creates a list of strings and places then in the names variable
Then it takes that collection filters it where the length is greater than or equal to 4
Sorts it based on the string
Puts the resulting collection in the variable subSetNames?
Finally it loops through all the strings in subSetNames? and prints them out

The resulting string is "Fred George William Smith" In this example the collection being acted on was a simple list of strings but it could be a collection of any type of object, or indeed an ADO record set, or an XML document, its a very powerful technique and allows for very clear functional logic (no complex nested loops and temporary collections for ordering etc).

This topic is massive and so im not going to go into it in any more depth, but in the most part ive not used any LINQ that is anymore complex than the example listed above. more advanced features such as lambdas and extension methods start to make things complex and ive so far managed to keep clear of using these techniques, for more info search google for the answer.

LINQ Grouping

By way of an example this code below demonstrates the power of LINQ used with a simple grouping command

string[] names = {"Albert", "Burke", "Connor", "David", "Everett", "Frank", "George", "Harris"};

//Defining the GroupBy logic (here it is lengthwise)
var groups = names.GroupBy(s => s.Length);

//Iterate through the collection created by the Grouping
foreach(IGrouping group in groups)
{
//Branch on the condition decided
Console.WriteLine("Strings of Length {0}", group.Key);
//Actual results
foreach(string value in group)
Console.WriteLine(" {0}", value);
}


Produces this output

Strings of Length 6
Albert
Connor
George
Harris
Strings of Length 5
Burke
David
Frank
Strings of Length 7
Everett

LINQ Resources
MSDN 101 LINQ samples

Wednesday 1 April 2009

Quick intro to generics

Recently ive been teaching some new developers on the team about generics, its not a new concept i know, and when you know about them you cant quite figure how people sometimes just dont know about them, they are so helpfull.

So tell me about them then!

Generics came in at .net 2.0 and are used extensively through out the .net framework internally, if you do much .net dev work you will come across then at some point.

What are generics

Generics allow you to define a type (class or structure) while leaving some of the details unspecified.

Quick Tip
When you see the following in code you know you are looking at code that uses generics

//C#
List myArray = new List();
List my2ndArray = new List();

'VB.Net
Dim myArray As New List(Of integer)();
Dim my2ndArray As New List(Of myClass)();

The main benefits for using generics are:
Type safety (you can only put ints in a collection of ints for example)
Performance (boxing and unboxing of primitive types is eliminated)
Clarity (you can see in visual studio what type of class is allowed in a generic collection, and intellisence will also help you out)

The most common (and simple) usage is in the new (as of 2.0) generic collection classes.
Previous to .net 2.0 you had ArrayList, HashTable, Queue and stack (to name just a few) these classes allow you to store collections of objects, and since every class in .net derives from object you can store any object in these classes.
So if you can store any object in a collection what the point of limiting a collection to allow it to only store objects of a certain type? The main reason is for type safety and clarity. This is best discussed by example:

ArrayList myArray = new ArrayList();
myArray.Add(1);
myArray.Add(2);
myArray.Add("3");

int counter = 0;
foreach(Object o in myArray)
{
int myInt = (int) o;
counter += myInt;
}

This code will compile fine, but will throw a runtime exception when trying to cast "3" (a string) to an int. you have to be careful when adding things to your collection and you have to make sure you handle exceptions that may arise from incorrect use. I often see code testing for the type of an object before doing a cast and if it is not of the correct type ignoring it, its bad practice, error prone, and is just unnecessary when using generics.

So if we rewrite the above example using generics:

List myArray = new List();
myArray.Add(1);
myArray.Add(2);
//myArray.Add("3"); //if uncommented will not compile

int counter = 0;
foreach(int myInt in myArray)
{
counter += myInt;
}

The change to use generic list of type int has made the code type safe (you cant add anything other than an int to myArray, if you do you will get a compile time error. Also the foreach loop is much simpler, you know that all the objects in myArray are ints, so no need for explicit type casting. All in all generic collections make the code more robust and just plain easier to read and hence maintain.

Now generics goes much deeper than just generic collections but in general you wont need to know how to create your own generic types and generic methods, but i would recommend every .net developer should know, its used all over the place. But i have not created any in any of my professional work projects.

Resources
Generics on MSDN
Use MSDN documentation on your machine
Google for Generics and .net