After various conversations on both internal and external projects, I’ve noticed that some of our web projects were being developed using a Session state called InProc.

InProc means In-Process, so IIS is hosting all of the

Session[“Dom”] = “Idiot!”; 

variables. Now, if the web application eats up too much memory, IIS 6 and above can be configured to recycle the Application pool – a contained unit of web sites, in order to free up memory. This is good for IIS but baaaad news for your website, as everything in the Session is lost – that could be shopping basket, current order status, user details! InProc is a bit of a quick and nasty method of developing as it just does its job, assuming that you are not going to host this to a larger audience (over about 5 users).

As I found out with any large project, nothing goes to plan, so, the best thing to do is to use StateServer and not InProc – but WHY?

StateServer is a totally out-of-process service that runs on either the same web server or a different server entirely. Session data is saved to this service so if the AppPool recycles, you have no problems whatsoever. Also, the data needs to serialize properly in order for it to be saved to the service.

Whats the point I hear you ask? Well, the point is that if you use InProc and your application gets load balanced (often without your knowledge), the website won’t work properly. Remember, load balancing is decided, by either the hardware or the software, to help manage the network traffic to a destination server. So 1 request to go to Server1 and another or Server2, or even ServerX! Youch! So your site’s Session could be stored on another machine.

StateServer works because all of the web.config’s point to the same machine, so they all work off that one service.

The other option is SQLServer, which stores it in SQL Server, which is more for web farms (multiple physical PCs), rather than web gardens (multiple virtualized PCs). Or you can use Custom for a custom implementation (e.g ODBC or XML), or Off to turn it off completely.

Therefore, a good recommendation is to always change your web.config to say:

<sessionState mode=”StateServer” … />

And start the ASP.NET State Service on your machine. This way to can always revert to InProc if you need to, but you are still ready for the switch over.

Believe me, it’s a lot easier to start out this way, rather than have to work backwards.

It is always a worthwhile exercise!


Bookmark with :
Digg It! DZone StumbleUpon Technorati Reddit Del.icio.us Newsvine Furl Blinklist

When working on a project recently, the data saved back to the database was huge. We are talking well over 100 properties. After talking to my Java buddy, he said that one way is to create an IsDirty method that returns if the object has changed state.

The IsDirty() method is used to query the state of an object - if it has been modified or not. The implementation is up to the developer, but ultimately it's use can save you a trip to the data source.

I have split this example into 3 stages:

  1. First attempt
  2. Refactored
  3. Event Handled

N.B. This article helps someone in (archaic) .NET 2.0 - but if you've looking to develop for .NET 3.5, it might be worth looking into DependencyProperty's, which caters for this sort of problem.

First Attempt

The problem I found when prototyping this is that it can be quite impractical at first glance:

class Customer
{
    private string firstName, surname;
    public Customer(string firstName, string surname)
    {
        this.firstName = firstName;
        this.surname = surname;
    }

    public string FirstName
    {
        get { return firstName; }
        set 
        { 
            if( firstName != value )
            {
                IsDirty = true;
                firstName = value;
            }
        }
    }
    public string Surname
    {
        get { return surname; }
        set 
        { 
            if( surname != value )
            {
                IsDirty = true;
                surname = value;
            }
        }
    }

    public bool IsDirty { get; private set; }
}

 

This is a bit bloated. Also, it relies on every property having to check for itself whether it is equal or not, setting the IsDirty property and also assigning the value.

After writing this and implementing a few more properties I found this to be a bit too impractical. Instead, I realised that they are all basically doing 3 steps:

  1. Checking the previous value to the new value.
  2. Setting IsDirty.
  3. Assigning the new value.

This example needs simplifying - or refactoring to be more precise.

Refactoring

Instead, I decided to implement this behaviour in a method called SetValue<T>() , which would raise events when a property has changed. This allows the IsDirty property to be changed centrally and debugging to be centralized.

Firsty I created the method:

private void SetValue<T>(ref T varName, T value)
{
    if (varName.Equals(value))
        return;
    
    IsDirty = true;
    varName = value;
}

 

Now, we can change our properties to:

public string FirstName
{
    get {return firstName; }
    set
    {
        SetValue<string>(ref firstName,value);
    }
}

public string Surname
{
    get {return surname; }
    set
    {
        SetValue<string>(ref surname,value);
    }
}

This is one implementation of it, but I decided to extend it to event handling as well, so that even the outside world can be notified about what is changing.

Event Handling

I decided to also implement this is in a typical Microsoft fashion: OnPropertyChanging and OnPropertyChanged.

In order to turn this into an event driven model I need to do a few things:

  1. Create some event arguments describing what is being changed.
  2. Add some event handlers to trigger a notification that they have been changed.
  3. Trigger the events from within your code
  4. (Optionally) wire up the events.
  5. Trigger the events from within your code

Create event arguments

Since I am using events, I want to create event arguments detailing what has changed. I have implemented this in 2 identical classes (and 1 base class). Here I have implemented a base class, and 2 classes which improve the clarity of the base class. I have chosen clarity over code bloat:

//Base class implementation
public abstract class PropertyChangeEventArgs : EventArgs
{
    public string PropertyName { get; protected set; }
    protected object Value { get; set; }

    public PropertyChangeEventArgs(string propertyName, object before)
    {
        this.PropertyName = propertyName;
        this.Value = before;
    }
}

//Holds arguments before the proerty has changed
public class PropertyChangingEventArgs : PropertyChangeEventArgs
{
    public object ValueBeforeChange
    {
        get
        {
            return this.Value;
        }
    }

    public PropertyChangingEventArgs(string propertyName, object before) 
        : base(propertyName,before)
    {
    }
}

//Holds arguments after the proerty has changed
public class PropertyChangedEventArgs : PropertyChangeEventArgs
{
    public object ValueAfterChange
    { 
        get 
        { 
            return this.Value; 
        } 
    }

    public PropertyChangedEventArgs(string propertyName, object after) 
        : base(propertyName, after)
    {
    }
}

Create event handlers

Now implement some event handlers:

public event PropertyChangingEventHandler PropertyChanging;
public delegate void PropertyChangingEventHandler(object o, PropertyChangingEventArgs e);

public event PropertyChangedEventHandler PropertyChanged;
public delegate void PropertyChangedEventHandler(object o,PropertyChangedEventArgs e);

Trigger the events from within your code

Now I need to trigger these events from the SetValue<T>() method. I will also need to find out what property was called by this SetValue<T>() method.

private void SetValue<T>(T varName, T value)
{
       if (varName.Equals(value))
           return;

       //TODO: Find the property's name that is calling this method
       string propertyName = "MyProperty";

       if (PropertyChanging != null)
           OnPropertyChanging(this, new PropertyChangingEventArgs(propertyName, varName));

       varName = value;

       if (PropertyChanged != null)
           OnPropertyChanged(this, new PropertyChangedEventArgs(propertyName, varName));
   }

The last thing to do is to find the property that is calling this method. This can be done using Reflection, by looking up the call stack. By getting the previous "frame", we can deduce where this is being called from. In our case, this is called "set_FirstName". Remove the "set_" and we have our property name:

StackTrace st = new StackTrace();
StackFrame current = st.GetFrame(1);
string propertyName = current.GetMethod().Name.Replace("set_", "");

(Optionally) wire up the events

I want to subscribe to the OnPropertyChanged event, so that I can set the IsDirty property within it. I have done this within a private constructor:

private Customer()
{
   PropertyChanged += new PropertyChangedEventHandler(OnPropertyChanged);
}

public Customer(string firstName, string surname) : this()
{
   this.firstName = firstName;
   this.surname = surname;
}

(Optionally) trigger the events from within your code

Now, I want to move the IsDirty assignment out of the SetValue() method because although overkill, it is not related to the setting of the value. It is related to the event but not the assignment. It also means that you have just wasted 15 minutes reading this article! :-) :

private void OnPropertyChanged(object sender, PropertyChangedEventArgs ea)
{
   IsDirty = true;
}

Summary

So what have we done? We've looked at ways in which we can implement notification within a class, so that we can save a database access. When getting to a large number of properties, we can bypass each save and also allow the outside world to be notified of its changes.

In the first example,we saw a cheap and nasty way of doing it, but impractical for larger classes. In the second example we saw a better implementation and in the third example we added event handling to extend the functionality further.

I hope this article helps someone - but if you've looking to develop for .NET 3.5, it might be worth looking into DependencyProperty's, which caters for this sort of problem.

Here is the full source code to have a play with:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Customer c = new Customer("Dominic", "Zukiewicz");
            c.FirstName = "Dommy dom dom";

            Console.WriteLine("Customer.IsDirty = " + c.IsDirty);

            Customer c2 = new Customer("Dominic", "Zukiewicz");
            c.Surname = "Zukiewicz";

            Console.WriteLine("Customer2.IsDirty = " + c2.IsDirty);
        }
    }

    class Customer
    {
        private string firstName;
        private string surname;

        private Customer()
        {
            PropertyChanged += new PropertyChangedEventHandler(OnPropertyChanged);
        }

        public Customer(string firstName, string surname) : this()
        {
            this.firstName = firstName;
            this.surname = surname;
        }

        public string FirstName
        {
            get
            {
                return firstName;
            }
            set
            {
                SetValue(ref firstName, value);
            }
        }

        public string Surname
        {
            get 
            { 
                return surname; 
            }
            set
            {
                SetValue(ref surname,value);
            }
        }

        public bool IsDirty { get; private set; }


        private void SetValue(T varName, T value)
        {
            if (varName.Equals(value))
                return;

            StackTrace st = new StackTrace();
            StackFrame current = st.GetFrame(1);
            string propertyName = current.GetMethod().Name.Replace("set_", "");

            if (PropertyChanging != null)
                OnPropertyChanging(this, new PropertyChangingEventArgs(propertyName, varName));

            varName = value;

            if (PropertyChanged != null)
                OnPropertyChanged(this, new PropertyChangedEventArgs(propertyName, varName));
        }

        public event PropertyChangingEventHandler PropertyChanging;
        public delegate void PropertyChangingEventHandler(object o, PropertyChangingEventArgs e);

        public event PropertyChangedEventHandler PropertyChanged;
        public delegate void PropertyChangedEventHandler(object o,PropertyChangedEventArgs e);

        private void OnPropertyChanged(object sender, PropertyChangedEventArgs ea)
        {
            Debug.Print("Property: {0}, After: {1}", ea.PropertyName, ea.ValueAfterChange);
            IsDirty = true;
        }

        private void OnPropertyChanging(object sender, PropertyChangingEventArgs ea)
        {
            Debug.Print("Property: {0}, Before: {1}", ea.PropertyName, ea.ValueBeforeChange);
        }
        
    }

    //Base class implementation
    public abstract class PropertyChangeEventArgs : EventArgs
    {
        public string PropertyName { get; protected set; }
        protected object Value { get; set; }

        public PropertyChangeEventArgs(string propertyName, object before)
        {
            this.PropertyName = propertyName;
            this.Value = before;
        }
    }

    //Holds arguments before the proerty has changed
    public class PropertyChangingEventArgs : PropertyChangeEventArgs
    {
        public object ValueBeforeChange
        {
            get
            {
                return this.Value;
            }
        }

        public PropertyChangingEventArgs(string propertyName, object before) 
            : base(propertyName,before)
        {
        }
    }

    //Holds arguments after the proerty has changed
    public class PropertyChangedEventArgs : PropertyChangeEventArgs
    {
        public object ValueAfterChange
        { 
            get 
            { 
                return this.Value; 
            } 
        }

        public PropertyChangedEventArgs(string propertyName, object after) 
            : base(propertyName, after)
        {
        }
    }
}

Bookmark with :
Digg It! DZone StumbleUpon Technorati Reddit Del.icio.us Newsvine Furl Blinklist

When writing stored procedures or views, I always create them in Visual Studio (2005/2008) and then run them on a specified database. When using "SELECT *", it is compact, but obviously does not help you find the columns of the table or view.

When using the IDE, I added a new SQL Script for Stored Procedures, and then I typed:

SELECT *
FROM Customers

and a blue box surrounded the statement. I right-clicked -> Design SQL Block.

The designer then listed all of the column names for me, and when clicking OK, instantly put them back into the SQL script I was creating!

SELECT  CustomerID, CompanyName, ContactName, ContactTitle, 
Address, City, Region, PostalCode, Country, Phone, Fax
FROM Customers

For the table I was using, this list over 60 columns for me!

So if you want a quick way of listing all of the column names for table of view:

  1. Add a database project to your site (if you haven't already done so)
  2. Right click Queries -> Add SQL Script
  3. Choose Stored Procedure Script
  4. Type your SELECT * From XYZ statement
  5. Right click -> Design SQL Block
  6. Click OK.

The designer will be updated with the new query.


Bookmark with :
Digg It! DZone StumbleUpon Technorati Reddit Del.icio.us Newsvine Furl Blinklist

I was trying to parse a file which was divided into numerous parts - each one 12 lines long. For debugging, I was interested in how fast the file was being read and processed and therefore looked at the StreamReader.BaseStream.Position property. Here is an example of what I was trying to do:

class Program
{
static void Main(string[] args)
{
string filename = @"C:\windows\windowsupdate.log";
string filenameBackup = filename + ".bac";
File.Copy(filename, filenameBackup);

FileStream fs = new FileStream(filenameBackup, FileMode.Open, FileAccess.Read);
StreamReader sr = new StreamReader(fs);

int lineNumber = 0;

while (!sr.EndOfStream)
{
Console.WriteLine("Lines Read = {0}, Position = {1}", lineNumber, sr.BaseStream.Position);
string[] lines = ReadXLines(sr,5);
lineNumber += lines.Length;
}

Console.Read();
}

private static string[] ReadXLines(StreamReader sr, int linesToRead)
{
string[] lines = new string[linesToRead];

for (int lineNumber = 0; lineNumber < lines.Length; lineNumber++)
{
lines[lineNumber] = sr.ReadLine();
}

return lines;
}
}

Now, the output on my computer was this:

Lines Read = 0, Position = 1024
Lines Read = 5, Position = 1024
Lines Read = 10, Position = 1024
Lines Read = 15, Position = 2048
Lines Read = 20, Position = 2048
Lines Read = 25, Position = 3072
Lines Read = 30, Position = 3072
Lines Read = 35, Position = 4096
Lines Read = 40, Position = 5120
Lines Read = 45, Position = 5120
Lines Read = 50, Position = 6144
Lines Read = 55, Position = 7168
Lines Read = 60, Position = 7168
Lines Read = 65, Position = 8192
Lines Read = 70, Position = 8192
Lines Read = 75, Position = 9216
Lines Read = 80, Position = 9216
Lines Read = 85, Position = 10240
Lines Read = 90, Position = 10240
Lines Read = 95, Position = 11264
Lines Read = 100, Position = 11264
Lines Read = 105, Position = 12288
......

What is odd about this sequence is that the position of the FileStream is already at 1024 before anything has been read! Also, the 1024 position stays the same for 2 reads. Why is this?

The StreamReader class is a buffered reader. Therefore, it is reading the stream before anything is processed and when reading directly from StreamReader, if the amount read does not extract the entire buffer, then the position of the underlying stream doesn't change.

Unfortunately, there is nothing you can do about this. Therefore the only 2 ways you can keep track of the position is to:

  • Count how many characters are in each line (plus the Environment.Newline) and total up the position line by line.
  • Create your own implementation of the FileStream, which has a ReadLine() method. This method should continue to read the Stream until Environment.Newline is encountered. Remember, Environment.Newline is not included in the string returned.

Bookmark with :
Digg It! DZone StumbleUpon Technorati Reddit Del.icio.us Newsvine Furl Blinklist

WPF is revolutionary as it re-invents the Windows design and programming for the Microsoft platform. But why bother?

I could write an article for hours and hours on the changes brought about with WPF. Here, I will give a very brief overview of the more visual changes brought about.

History

If you have had any experience programming Windows in .NET, VB6 or C++ MFC, you'll have heard of GDI. GDI (more recently GDI+) is an API which you use to render text images and other custom drawing functions (like lines, circles, rectangles etc). The GDI library has been around since Windows 95 and was a huge hit with developers for drawing basic elements on the page. The standard Windows forms and controls are rendered by the User.dll (more recently User32.dll).

The problem that faces GDI in the modern computer is that it is implemented in software. In 1995, this is a sensible solution, but in 2008 the average computer has a half decent graphics processor. Also, DirectX has matured a huge amount since Windows 95 and this isn't utilised at all. We need a way of using the hardware to do our UI rendering so that we can draw both 2D and 3D objects within our applications, without imposing too much on the software core of the OS.

Overview

Graphics

WPF replaces the slow GDI libraries by using DirectX as its UI drawing library. WPF is also intelligent enough to know about your hardware capabilities, falling back to the slower software rendering should it need to. WPF's DirectX rendering capabilities only work for Windows XP and Windows Vista and even then there is a catch. When Microsoft were thinking about Vista and "Indigo" (code name for the WPF project), they released a new specification for hardware manufacturers to follow, to accommodate the new interface. Therefore, if your video card didn't receive a patch after 2004, OR they haven't added this requirement, then you will only have software rendering capabilities.

That doesn't mean that Direct3D and OpenGL are defunct. WPF is an implementation and is not as fast as Direct3D. If you need to create some real-time, high resolution graphics package or game then WPF will not be the way to go. WPF does cater for 3D graphics, rotation, lighting, transformation etc, but it does not replace the abilities of the Direct3D.

Flexible UI components

Some of the web concepts have really given WPF so great ideas on how to improve the framework. These include:

  • Layouts are flexible to the width of the application.
  • Creating text documents similar to Microsoft Word are as simple as adding headings, paragraphs, tables with captions, images etc.
  • Create styles for controls and apply them across your application - much like skins in ASP.NET.
  • Data binding can be done at page level, rather than by each control separately.

Think about a list. A list, as a high level abstract is just a grouping of 1 or more items. That's it. Therefore, the current ListBox implementation is quite inflexible; you just have a bit of text for the description. If you work harder you could get an image in there as well, but ultimately, the ListBox is really a TextListBox.

An awesome example of the thinking behind WPF is that the ListBox has been totally redesigned to hold just about anything you want. If you want an image/text combination, you group the 2 together and add it to the list! Easy peesy. You might be surprised that a CheckBoxList doesn't exist - why? Because it is just a list of CheckBox controls - so why create a new control, when a ListBox with CheckBoxes in does the same thing!

Resolution Independence

When working off high resolution monitors, the pixel density is a lot higher. This means if 2 screens of the same size, but with different resolutions, display the same size window, the higher resolution monitor will show the window to be much smaller. I personally use a high resolution laptop, therefore my task bar is tiny. You can increase the size of your desktop by either:

  • Changing the font sizes
  • Changing the DPI settings (preferred)

By changing your DPI settings, the fonts remain proportionate to your screen.

The only problem is that applications built prior to XP didn't have to take this into account and therefore changing the DPI can make some windows look a little strange, whereas others (which have catered for it) remain relatively normal. In Vista, it uses a slightly different technology called bitmap scaling which intelligently stretches images and fonts to fill out the DPI setting.

Event Model Changes

The event notification model has changed as well, meaning that events can "bubble" up to parent containers if needs be.

Navigation support

Users are getting more and more familiar with the navigation of web pages - a step by step approach to using sites. The WPF team have created page based navigation too, with page history. This allows users to create a similar navigation system to that of web pages, but from a user interface.

Summary

There are many many many more exciting features that WPF brings to .NET, and you will find huge books on the subject. Hopefully, I have given a small taster of the high level features available to you and in the future, I will try and provide some samples of what it can do.


Bookmark with :
Digg It! DZone StumbleUpon Technorati Reddit Del.icio.us Newsvine Furl Blinklist

Microsoft recently (on my birthday) released a tool to analyse coding structure and formatting. No - its not FxCop - StyleCop analyses syntactical formatting. Let me explain:

Background

When Microsoft released FxCop, some people cringed. I remember at my previous job when having a code review and the conversation following:

  • Consultant: "Have you FxCop'd it?".
  • Me: "No...."
  • Consultant: "Hahahah - see you in 3 months!"

Those days, for me anyway, have gone. I started to use it in my everyday coding and am now pleased I use it without a second thought.

In my position with this company, I have tried to promote its use and benefits, because it promotes good coding guidelines standard approaches to software development.

FxCop works by analysing compiled code and therefore can look into its improvements at a detailed view. This is all good, but what about coding standards for syntax!?

Overview

StyleCop is a tool written and used by Microsoft to ensure all of their code is formatted, commented and laid out in a fixed format. It has quite a rigid structure to it, but so it should. I've read lots of threads about people complaining about its flexibility, but that's the whole point of standards - they don't change (often) .

Before I provide a link, I just want to show you how much you need to do, in order to pass one of these successfully. Here is a typical piece of code:

using System;
using System.Diagnostics;
using LogicAndData;

class User {

private string _username;

public string Username
{
get { return _username; }
}

[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private string _password;

public bool IsCorrectPassword(string guess)
{
if (String.IsNullOrEmpty(guess))
return false;

return guess.Equals(_password, StringComparison.CurrentCulture);
}

public User(string username, string password)
{
if (username == null)
throw new ArgumentNullException(Resources.Username_ParameterName);
else if (username.Length == 0)
throw new ArgumentException(Resources.Username_ParameterEmpty, Resources.Username_ParameterName);

if (password == null)
throw new ArgumentNullException(Resources.Password_ParameterName);
else if (password.Length == 0)
throw new ArgumentException(Resources.Password_ParameterEmpty, Resources.Password_ParameterName);

_username = username;
_password = password;
}
}

Pretty standard stuff really. Okay, its missing comments but it does pass FxCop! So lets have a look at the errors generated for this class:

styleCopErrors

So, what are the problems?

  1. SA1101: If you are referring to member variables (variables at class level), then you should use the keyword "this." to be explicit (2 errors)
  2. SA1201: This is a formatting issue - the order is - private fields, constructors, properties, public methods, private methods. (2 errors)
  3. SA1309: Don't use underscores! The "this" keyword implies it. (2 errors)
  4. SA1400: Class must have an identifier instead of the default (protected internal) (1 error)
  5. SA1503: If statements must use { }, even if they are only 1 line of code (6 errors)
  6. SA1600: All classes, interfaces, methods, properties and fields (optional) MUST have an XML header for documentation purposes. (4 errors)
  7. SA1633: Related to the above, there is a preset format for the documentation for the header of the file that MUST be at the top of each file created. (1 error)

Using StyleCop

What does this improve? relating to the above:

  1. It is clearer what you are working with. You don't need to use prefixes, as by using "this" you are describing which one you are referencing anyway.
  2. This just standardises the layout of your code.
  3. For clarity. It doesn't like Hungarian notation either, but DOES allow you to add acceptable notations should you wish.
  4. Be explicit about the access type, as you may not understand the access of an unmarked class.
  5. By laying out if statements this way, you are totally consistent across your code.
  6. Documentation - who doesn't document their code!?
  7. Add a header to just clarify what's doing on, any copyright notices, authors etc.

So lets see what this looks like without any errors at all!

[40 minutes later and 3 cups of coffee].... only joking - it probably took 5 minutes, mainly because I have used it before:

// <copyright file="User.cs" company="Interakting">
//     Copyright (C) 2008 Interakting. All rights reserved
// </copyright>
// <author>Dominic Zukiewicz</author>
using System;
using System.Diagnostics;
using LogicAndData;

/// <summary>
/// The User class describes a single username/password combination. The password
/// is kept secret, but timescales limit security.
/// </summary>
internal class User
{
    /// <summary>    
    /// The username of the user.    
    /// </summary>    
    private string username;

    /// <summary>    
    /// The password of the user.    
    /// </summary>    
    [DebuggerBrowsable(DebuggerBrowsableState.Never)]
    private string password;

    /// <summary>    
    /// Creates a user with a specific username/password combination    
    /// </summary>    
    /// <param name="username">The username of the user.</param>    
    /// <param name="password">The password of the user.</param>    
    public User(string username, string password)
    {
        if (username == null)
        {
            throw new ArgumentNullException(Resources.Username_ParameterName);
        }
        else if (username.Length == 0) 
        { 
            throw new ArgumentException(Resources.Username_ParameterEmpty, Resources.Username_ParameterName); 
        } 
        
        if (password == null) 
        {
            throw new ArgumentNullException(Resources.Password_ParameterName); 
        } 
        else if (password.Length == 0)
        { 
            throw new ArgumentException(Resources.Password_ParameterEmpty, Resources.Password_ParameterName); 
        }
        
        this.username = username; 
        this.password = password;
    }

    /// <summary>    
    /// Gets the username of the user.    
    /// </summary>    
    public string Username 
    { 
        get 
        { 
            return this.username; 
        } 
    }
    
    /// <summary>    
    /// Checks to see if the password of the user matches that of the stored password.    
    /// </summary>    
    /// <param name="guess">The guess for the password.</param>    
    /// <returns><code>true</code> if it matches, else <code>false</code>.</returns>    
    public bool CheckPassword(string guess)
    {
        if (String.IsNullOrEmpty(guess))
        { 
            return false; 
        }
        
        return guess.Equals(this.password, StringComparison.CurrentCulture);
    }
}

So what's changed - really?

What I have noticed, is that there is a good separation of the code, a very clear layout structure and of course, forcing you to comment your methods, which I really like. You'll find that the code is clearer because of the white-space implied by the curly brackets.

It can seem quite daunting to see all of these errors, but like FxCop, once you start to take these rules onboard, you are more likely to code in this style rather than turn away from it.

Here is the link to Microsoft's StyleCop: http://code.msdn.microsoft.com/sourceanalysis/Release/ProjectReleases.aspx?ReleaseId=1047


Bookmark with :
Digg It! DZone StumbleUpon Technorati Reddit Del.icio.us Newsvine Furl Blinklist
When using RAND() with SQL SELECT statements, the same number is generated for all rows. This is annoying if you are trying to create test data, but I've found a way to get around this. Read on for more information.

Bookmark with :
Digg It! DZone StumbleUpon Technorati Reddit Del.icio.us Newsvine Furl Blinklist

After a trip to London to visit one of my friends who works for Rightmove -  the UK's No 1 Online Housing Site and we (we meaning I) got into talking about the ways we test our code. He told me that they started to use a Test Driven Development methodology. When testing in a development environment, their test framework used something called "mock objects" - these are objects that simulate behaviour, but in reality, don't do anything! I was intrigued....

Background

One of the drawback of the development process, especially with Test Driven Development, is that there comes a stage when a large amount of code has to be written to cater for a data access layer. Your program goes from:

public class DataAccessUser
{ 
     public User Load(string username)
     {
          return new User(username);
          //TODO: Write proper load
     }
}

public class BusinessObjectUser
{
     private string _username;

     public User(string username) 
     { 
          _username = username;
     }
}

To this:

public class DataAccessUser
{
     public User Load(string username)
     {          
          if( username == null )        
              throw new ArgumentNullException("username");          
          else               
              throw new ArgumentException("username","Username cannot be empty.");
          
          string connString = ConfigurationManager.ConnectionSettings["UserDB"].ConnectionString;
          SqlConnection sqlConn = new SqlConnection(connString);

          using(SqlCommand comm = sqlConn.CreateCommand())
          {
               User u = null;
               comm.Parameters.Add("@Username", username);

               sqlConn.Open();
               
               SqlDataReader dr = comm.ExecuteReader();
               
               if(dr.HasRows)
               {
                    User u = new User(dr.GetString( dr.GetOrdinal("Username"));
               }
               
               return u;
          }
     }
}

Now, I understand this is necessary as otherwise you can't load users. But now you have to test 2 parts of the code:

  1. The constructor for the User class.
  2. The DataAccessUser.Load() method.

In effect, you've written over 20 lines of code to test 2 cases line of code - the constructor call and a method call. You've also tied yourself into a specific technology for the data access layer, when you are only supposed to be concerned with testing!

Oops... you've got ahead of yourself. Now have to write another 5 test cases just for the Data Access layer.

  1. A successful BusinessObjectsUser load.
  2. An unsuccessful BusinessObjectsUser load.
  3. A null string parameter.
  4. An empty string parameter.
  5. An exception being generated for SQL being inaccessible.

This can be quite annoying as now you're losing track of your simple little BusinessObjectsUser class and loading it. In the process, have created nearly 3 times the code just by adding one method and not testing it.

Overview

Mock objects are simply an object that simulates the behaviour of a real object. A mock object is told how to behave when passed specific parameters. The idea behind this is that you are not bogged down with the technical details of the data access layer. Instead, you concentrate on the here and now, working on what is supposed to happen, rather than what will happen. Lets have a look at this in more detail.

Firstly, mock objects simulate fully implemented objects via the use of an interface. This means that in order to take advantage of mock objects, we need to use a base interface, which our real data access layer will implement. Using the example above, this would be:

internal interface IDataAccess
{
     User Load(string username);
}

Now, we need a way of telling the application to use an IDataAccess implementation we have created, instead of using a data access layer that provides real functionality.

Why? Well we want to have control over our data access layer in development, but in stage or production environments it will use the real thing. We do this using a pattern called the Dependency Injection pattern.

Dependency Injection Pattern

This pattern uses the idea that an interface is passed into an object and then the object calls the methods on that interface. As with interfaces, it doesn't have to know how the interface works, it just calls it and get its return values. This is exactly the behaviour we want! Test Driven Development works on the basis that you know how it is going to work, so you write your test case for its expected behaviour first, check it works (which it shouldn't) and then implement it. So I'll now implement a BusinessLogic class with the Dependency Injection pattern.

NB. Note from this point on we will be looking at testing this BusinessLogic class, because this is the class that uses the Dependency Injection Pattern.

public class BusinessLogic
{
     private IDataAccess _dataAccess;

     public BusinessLogic()
     {
          //Default assignment of IDataAccess goes here
     }

     public BusinessLogic(IDataAccess dataAccess)
     {
          _dataAccess = dataAccess;
     }

     public User LoadUser( string userName )
     {
          if(userName == null)
               throw new ArgumentNullException("userName");
          else if(userName.Length == 0)
               throw new ArgumentException("userName","Parameter cannot be empty.");
          else
               return _dataAccess.Load( userName );
     }
}

So we have 3 classes now:

  1. BusinessLogic, which calls
  2. IDataAccess, which uses
  3. BusinessObjects

This creates a performant and scalable architecture, but at the cost of flexibility.

Creating a mock object

In our test class, we can now create a mock object, which will emulate a class that inherits from IDataAccess.

[TestMethod()]
public void TestUserLoad()
{
     Mockery mock = new Mockery();
     IDataAccess da = mock.NewMock<IDataAccess>();
}

We now have a working IDataAccess implementation, but it doesn't do anything at all. In the NMock framework there is a class called the Stub class, which helps us tell the interface how to react for the created instance in this method.

In this example, we'll simulate the ArgumentException, when the .Load() method is called with an empty parameter. Remember we are now testing the BusinessLogic class, not the User, or IDataAccess layer:

[TestMethod(), ExpectedException(typeof(ArgumentException)]
public void TestUserLoadEmptyParameter()
{
     Mockery mock = new Mockery();
     IDataAccess da = mock.NewMock<IDataAccess>();
     Stub.On(da).Method("Load").With(string.Empty).Will(Throw.Exception( new ArgumentException() ));

     BusinessLogic bl  = new BusinessLogic(da);
     bl.LoadUser(string.Empty);

     Assert.Fail("ArgumentException has not been thrown!");
}

So how is this working? The BusinessLogic is using our "mock" IDataAccess interface, that we passed into the constructor. It is told to throw an exception when string.Empty is passed into the "Load" method. Simple!

I'll write a second test to check for a null parameter, a 3rd test to check for a valid user, and a 4th test for an invalid user. Remember, we are simulating the behaviour!

[TestMethod(), ExpectedException(typeof(ArgumentNullException)]
public void TestUserNullParameter
{
    Mockery mock = new Mockery();
     
    IDataAccess da = mock.NewMock<IDataAccess>(); 
    Stub.On(da).Method("Load").With( new object[] { null }).Will(Throw.Exception(new ArgumentNullException()));

    BusinessLogic bl = new BusinessLogic(da);
    User u = bl.LoadUser(null);

    Assert.Fail("ArgumentNullException should have been thrown!");
}

[TestMethod()]
public void TestValidUser
{
    Mockery mock = new Mockery();
     
    IDataAccess da = mock.NewMock<IDataAccess>(); 
    string username = "Billy";
    User u = new User(username);;

    Stub.On(da).Method("Load").With( username ).Will(Return.Value(u));

    BusinessLogic bl = new BusinessLogic(da);
    User u = bl.LoadUser(username);

    Assert.IsNotNull(u);
    Assert.AreSame(u.Username, username,"Usernames should be the same.");
}

[TestMethod()]
public void TestInvalidUser
{
    Mockery mock = new Mockery();
     
    IDataAccess da = mock.NewMock<IDataAccess>(); 
    string username = "Billy";

    Stub.On(da).Method("Load").With( username ).Will(Return.Value(null));

    BusinessLogic bl = new BusinessLogic(da);
    User u = bl.LoadUser(username);

    Assert.IsNull(u);
}

If you decided that you did have an IDataAccess implementing class, then you could create a method to automatically get this instance an plug it in as needed, instead of creating the mock object each time.

Real Implementation

Now, all you have to do is implement you IDataAccess interface with a real class, which would carry out the proper database access. The NMock framework and Dependency Injection pattern you have implemented gives you an excellent starting point for the expected behaviour of each method to IDataAccess.  This would have to be tested with unit tests too.

Confused?

At this point, you might be asking "What is the point? You aren't testing any data access!" and you are absolutely correct. This was the point that I stumbled over. The thing is, you would normally spend time writing your data access layer, but you would have to write tests to test this separately anyway! Unit testing is always about testing that a specific method is working in isolation. Even though our BusinessLogic.LoadUser() calls IDataAccess.Load(), we don't really care. What matters for this specific test,  is if the BusinessLogic.LoadUser() method is working and that it's working correctly in each of the 3 cases.

Summary

The NMock framework gives developers and testers an excellent starting point to development any object through the use of interfaces and easily customized behaviour within 3 lines of code.

The only cavaet of this, is that you MUST start using this as soon as you start development. Moving your project to an interface based approach can, although improve the testability of your code through the NMock framework, can easily get developers totally side-tracked. I wouldn't recommend moving to this if you are already in full flow.

I can assure you that from my experiences with it, that is an excellent example of self documenting code: short, yet descriptive and sets the building blocks in place for even the most complex of test cases.

Extra-credit

Another little tip is that some test frameworks are implemented as a separate project or assembly. The internal keyword does not allow any methods to be exposed outside of the assembly. Therefore, you need to add an attribute in your AssemblyInfo.cs to allow another namespace to access the internal methods:

[assembly: InternalsVisibleTo("AssemblyName")]

You are then able to access the internal constructors and methods of the referenced assembly.


Bookmark with :
Digg It! DZone StumbleUpon Technorati Reddit Del.icio.us Newsvine Furl Blinklist

I don’t know about you, but when I’ve seen some string comparisons, some people use:

string text = GetStringFromDB() 
 
if( text != string.Empty ) 
    DoThis(); 

This looks good, but its actually quite a long running process, as the CLR has to compare both strings character by character. It is much better to use String.IsNullOrEmpty to cater for this, or use .Length == 0 property, as this never changes and is computed when assigned. Here is what the String.IsNullOrEmpty method looks like:

public static bool IsNullOrEmpty(string value)
{
    if (value != null)
    {
        return (value.Length == 0);
    }
    return true;
}

If you use != , or  ==, or .Equals() the method, it uses some hefty pointer manipulation like this:

public bool Equals(string value)
{
    if ((value == null) && (this != null))
    {
        return false;
    }
    return EqualsHelper(this, value);
}
 
private static unsafe bool EqualsHelper(string strA, string strB)
{
    int length = strA.Length;
 
    if (length != strB.Length)
    {
        return false;
    }
 
    fixed (char* str = ((char*) strA))
    {
        char* chPtr = str;
        fixed (char* str2 = ((char*) strB))
        {
            char* chPtr2 = str2;
            char* chPtr3 = chPtr;
            char* chPtr4 = chPtr2;
            while (length >= 10)
            {
                if ((((*(((int*) chPtr3)) != *(((int*) chPtr4))) || (*(((int*) (chPtr3 + 2))) != *(((int*) (chPtr4 + 2))))) || ((*(((int*) (chPtr3 + 4))) != *(((int*) (chPtr4 + 4)))) || (*(((int*) (chPtr3 + 6))) != *(((int*) (chPtr4 + 6)))))) || (*(((int*) (chPtr3 + 8))) != *(((int*) (chPtr4 + 8)))))
                {
                    break;
                }
                chPtr3 += 10;