binary dreams

a world of 1s and 0s

Positive statements

Whenever I see variable names like FeatureDisabled or IgnoreFeature or FeatureNotActive it frustrate

Whenever I see variable names like FeatureDisabled or IgnoreFeature or FeatureNotActive it frustrates me because these can confuse you when trying to understand mysterious code. What would you expect the value of that variable to be? true or false? When you look at the word true what do you see? I see something is "on" and false will mean "off".

A variable like FeatureDisabled could appear as true and reading that means you need to revert your thinking while understanding the code. We naturally see true as something active or on. You see it on light switches, any IT equipment, you name it, on is true and off is false.

A boolean variable name should be like IsFeatureEnabled or HasSpecificValue - all positive verbs. It makes it so much easier to read and understand. The Is, Has, Was verbs all indicate this is a boolean statement and then just had something like Active or Enabled to indicate the status.

What if you are using code from something you don't have control of like the ones above? Just invert it so it looks positive from your side. Don't let that bad practice infect your good code!

Good luck and keep your statements positive!

Give your QA a stub while you develop your service

In my development career I have often needed to provide a stub of my service. In this case I develop

In my development career I have often needed to provide a stub of my service to help test an application.

I originally started to hardcode data to return specific responses. I realised this was wrong a few years ago when I had to continually change customer identifiers to suit the testing taking place. This was wrong and so I changed my strategy from then on.

In this post I will go through what a stub should and should NOT do, show how my reusable stub class works and provide an example of it.

The stub rules

A stub should:

  • Provide the ability to return a response that is not easily repeatable.
  • Enable it to be used in a larger test with other applications.
  • Save the developer and/or QA doing all sorts of complex data setup that may be required. I.e. Database.
  • Allow anyone to set the response of the service method to whatever is possible for that operation.
  • Be lean. It shouldn't be time-consuming to maintain.
  • NOT tightly couple specific data requests to specific responses. This only increases the maintenance for the developer to change it when required.

Do bare in mind this solution does limit the stub by returning the same response to whatever called it after whoever set it. For example, if two people want different responses then they need to negotiate their time testing of the service.

The response object we want to stub

We want to set the main method to return this response object.

    [DataContract]     public class CalculateResponse     {         [DataMember]         public ValueType TypeOfValue { getset; }         [DataMember]         public object Result { getset; }     }

    public enum ValueType

The stub base class 

So to make it easier to reuse I needed two reusable methods to call for a Set method and the main method.

The SetResponse will take whatever object the TResponse is and the method name, serialise the TResponse object into xml and save it as the method name, for example CalculatorServiceStub_Calculate.xml. If the XML file already exists the code will overwrite it.

public void SetResponse<TResponse>(TResponse response, string methodName)     where TResponse : classnew() {     if (response == null)         throw new ArgumentNullException("request");     if (string.IsNullOrWhiteSpace(methodName))         throw new ArgumentException("Value cannot be null, empty or have whitespace."
"methodName");     try     {         var xml = CreateXML<TResponse>(response);         SaveXML(methodName, xml.ToString());     }     catch (Exception exception)     {         // log the exception         throw;     } } private StringBuilder CreateXML<TResponse>(TResponse response)      where TResponse : classnew() {     var xml = new StringBuilder();     var serialiser = new XmlSerializer(response.GetType());     var writerSettings = new XmlWriterSettings();     using (XmlWriter xmlWriter = XmlWriter.Create(xml, writerSettings))     {         serialiser.Serialize(xmlWriter, response);     }     return xml; } private void SaveXML(string methodName, string xml) {     string fullPath = StubXmlLocation(methodName);     using (Stream stream = new FileStream(fullPath, FileMode.Create, FileAccess.Write))     {         XmlDocument document = new XmlDocument();         document.LoadXml(xml);         document.Save(stream);     } }

The xml filename is created using the StubXmlLocation method.

        private string StubXmlLocation(string method)
            var setting = ConfigurationManager.AppSettings["StubXmlOutputLocation"];
            string path = string.IsNullOrWhiteSpace(setting) ? @".\" : setting;
            string className = this.GetType().Name;
            return string.Format("{0}{1}_{2}.xml", path, className, method);

The RetrieveResponse will take the method name. The Xml will be loaded from the expected filename and serialised into the TResponse object.

public TResponse RetrieveResponse<TResponse>(string methodName)     where TResponse : classnew() {     if (string.IsNullOrWhiteSpace(methodName))         throw new ArgumentException("Value cannot be null, empty or have whitespace."
"methodName");     TResponse response = new TResponse();     try     {         XDocument xmlDocument = XDocument.Load(StubXmlLocation(methodName));         using (TextReader textReader = new StringReader(xmlDocument.ToString()))         {             var serialiser = new XmlSerializer(response.GetType());             response = (TResponse)serialiser.Deserialize(textReader);         }     }     catch (Exception exception)     {         // log the exception         throw;     }     return response; }

Using both of these public methods works incredibly well because any changes to the service contract will be reflected the next time the SetResponse method is called and the new XML saved.

The saved xml file contents could look like this:

<?xml version="1.0" encoding="utf-16"?>
<CalculateResponse xmlns:xsi="" xmlns:xsd="">
  <Result xsi:type="xsd:int">10</Result>

The Service Stub

Now in your service you would have something like this using the two methods. Now your stubbing is so easy!

public class CalculatorServiceStub : StubBaseICalculatorServiceStub {     public CalculateResponse Calculate(CalculateRequest request)     {         if (request == null)             throw new ArgumentNullException("request");         return RetrieveResponse<CalculateResponse>("Calculate");     }     public void SetCalculate(SetCalculateRequest request)     {         if (request == null)             throw new ArgumentNullException("request");         SetResponse<CalculateResponse>(request.Request, "Calculate");     }


I have attached the example Visual Studio 2012 project as a ZIP file. (79KB)

Get stubbing!

How to use Moles

This blog post is a copy of information I gathered at the time many moons ago for Moles and may well

This blog post is a copy of information I gathered at the time many moons ago for Moles and may well be inaccurate now but here for reference. I was using Visual Studio 2010 at the time.

Moles best practice

When moling, follow this best practice:

  • Use moles as a last resort. Stubs are the preference to mocks. If the object you want to mock has an interface or base class create a stub!
  • Always mole your external classes, even constructors! Even empty ones. Do not rely on other code not changing for your tests to pass.
  • The preference is for system DLLs to not be moled unless absolutely necessary. You really want them to work as they normally should. Plus you don't want loads of moles for loads of .NET interactions. Moling a system DLL would be required if you must interact with, configuration, files or some other external dependency.
  • Observer Locals
    Use booleans when testing for when a property is get or set and when methods are called. For when collections are built, a count should be adequate. Then Assert at the end of the test.
  • Use Stubs rather than Moles wherever possible as moles have reportedly worse performance. There is no study to confirm this or even how badly the performance is. It is just in said in the Moles documentation.
  • Consider putting reuseable mock methods into own class with the naming convention as <ClassName>Mock, e.g. DateTimeMock.
  • A mock method should ideally handle only one method in the object even if you mock all the other ones. This allows better reuse across the tests as some paths will not require the mocked methods.
  • Use our custom the ParameterValidator class (which throws a ParameterValidatorException) to check mole parameters instead of Assertions to keep to the principle of one Assert per test. This will also not confuse anyone when tests break.

Moles knowledge base

MoleNotImplementedException thrown


Add missing mole.

How do you mole an object in System.dll/mscorlib.dll?


Mole the DLL as normal but add the following attributes to the xml file:

<Moles xmlns="">

<Assembly Name="System" ExportedTypes="true" ReflectionOnly="true" />


There are some special types that cannot be moled. There is currently no list of specific types that are listed as unmoleable.


Moved a class, namespace changed and not moling that class?


Clean the solution and rebuild.

Mole complains about COM object


Moling Interop.Vixcom needed the "Embed interop Types" property on the dll set to false to stop Moles generator complaining.

InvalidOperationException: Dynamic operations can only be performed in homogenous AppDomain


Change a value in the Moles config file:

C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\PrivateAssemblies\Microsoft.Moles.VsHost.x86.exe.config


     <legacyCasPolicy enabled="true" />


     <legacyCasPolicy enabled="false" />


TFS build shows a Moles warning


C:\Windows\Microsoft.NET\Framework\v4.0.30319\Microsoft.Common.targets (1360): Could not resolve this reference. Could not locate the assembly "mscorlib.Moles, Version=, Culture=neutral, PublicKeyToken=0ae41878053f6703, processorArchitecture=MSIL". Check to make sure the assembly exists on disk. If this reference is required by your code, you may get compilation errors.


  • Unload the test roject. Right-click on the unloaded project and select "Edit ... proj"
  • Replace this reference
    <Reference Include="mscorlib.Moles.dll, Version=, Culture=neutral, 
    PublicKeyToken=0ae41878053f6703, processorArchitecture=MSIL"
  • With this
    1. <Reference Condition="Exists('..\..\MolesAssemblies\mscorlib.Moles.dll')" Include="mscorlib.Moles.dll">   
    2.   <SpecificVersion>False</SpecificVersion>   
    3.   <HintPath>..\..\MolesAssemblies\mscorlib.Moles.dll</HintPath>  
    4. </Reference>  
  • Note: The moles hint path assumes the test project is referencing from a "bin\Debug" folder.
  • Note: If you get local compile warnings of "The referenced component 'mscorlib.Moles' could not be
    " then ignore it.

My standard development PC installs

I need to write down what I need to install whenever I have to reinstall everything onto a Dev PC. Our company UK Dev PC build PLUS:

  • Visual Studio 2010
  • Visual Studio 2012 + update 4
  • Visual Studio 2012 Extension - Nuget.PackageNPublish
  • Visual Studio 2012 Extension - NCrunch (if I am using it)
  • TFS 2010 Power tools (September 2011)
  • DevExpress 13.x
  • WiX 3.6 
  • XPath Builder
  • Connection String Manager
  • WCFStorm 2.5
  • Virtual Clone Drive
  • Telerik JustDecompile
  • VMWare vSphere Client
  • KDiff 3


Internet Explorer

Enable the Favourites Bar and add everything required to it.


TFS Workspaces

Remember: If you just permanently moved to a new PC then you might need to delete your old PC TFS workspace.

Remove a Workspace


Power saving settings

Change Hard disk to turn off after 4 hours.

Change Power saving to not turn off Network Card so I can remote login quickly.

Hopefully this can be of use to other people as well.

How to use C# properties with SOLID class design principles

It wasn&#39;t so long ago I was using properties without any consideration to how they SHOULD be used. I&#39;m going to show you how you can use them properly with the help of SOLID Class Design Principles.

It wasn't so long ago I was using C# properties without any consideration to how they SHOULD be used. I'm going to show you how you can use them properly with the help of SOLID Class Design Principles.

Case 1:

This is a typical class you might have written.

public class Person
public string Forename { get; set; }
public string Surname { get; set; }
public Person() {}

STOP! Using public setters here with the person attributes breaks the Single Responsibility Principle (SRP) because the class has more than one reason to change. The class breaks this with two reasons - Forename and Surname.

To fix this, make the setters of those properties private and create an Update method like so:

public class Person
public string Forename { get; private set; }
public string Surname { get; private set; }
public void Update(string forename, string surname)
Forename = forename;
Surname = surname;

Now the class has one reason to change rather than two.

In general an object should not have it's state changed unless it was changed by an action. Remember OO design is about data hiding, how an objects attribute changes is of no concern to its consumer. Only the object needs to know how it changes.

Case 2:

How would you check the object is valid? Check each property like this:

var person = new Person();
person.Update("forename", "surname");
if (person.Surname != null && person.Forename != null)

STOP! This breaks the Dependency Inversion Principle (DIP) - Depend on abstractions not on concretions. We need to create a validation method to abstract us from the attributes. The properties should not be checked outside of the class but from inside the class.

Lets rewrite it.

Create an interface

public interface IValidate
	bool IsValid();

Now change the Person class.

public class Person : IValidate
public string Forename { get; private set; }
public string Surname { get; private set; }
public void Update(string forename, string surname)
Forename = forename;
Surname = surname;
public bool IsValid()
return (Forename != null) && (Surname != null);

With the Person class rewritten you would use it like so.

var person = new Person();
person.Update("forename", "surname");
if (person.IsPersonValid())