How to write a FreeBSD Kernel Module

You may be think that writing your first kernel module is going to be a long, painful, grueling task, but really it is only slightly harder than writing your first program, Hello World!, in C or C++.

Lets break this into nice easy steps.

Prerequisites

It is assumed you have installed FreeBSD already. If not, follow the instructions below with one change: Install the FreeBSD source during the “Choose Distribution” section.

How do I install FreeBSD?

Step 1 – Create a basic module file

A FreeBSD kernel module is written in C. This is going to be only a slightly harder than writing hello world in C. We are going to create a single text file with a .c extension and put some C code in it.

  1. Create a folder to hold you project. I used this directory:
    /usr/home/jared/code/kernel/hwm
  2. Create the file to hold your code. I named my file this:
    hello_world_kmod.c
  3. Edit the file with you favorite editor, vi, vim, emac, ee. I used easy editor (ee):
    ee hello_world_kmod.c
  4. Add the following code to the file.I have broken the code of the simplest kernel module into four parts or steps:
    1. Add four required #include statements.
    2. Create the kernel load/unload event handler.
    3. Create a struct to name the module and point to the event handler function.
    4. Call the DECLARE_MODULE macro.
    /*
     * Step 1 - Add the four needed libraries to include
     */
    #include <sys/param.h>
    #include <sys/module.h>
    #include <sys/kernel.h>
    #include <sys/systm.h>
    
    /*
     * Step 2 - Handle the load/unload event
     */
    static int EventHandler(struct module *inModule, int inEvent, void *inArg)
    {
            // Set return code to 0
            int returnCode = 0;
    
            switch (inEvent)
            {
              case MOD_LOAD:
                    uprintf("Hello, World! \n");
                    break;
              case MOD_UNLOAD:
                    uprintf("Bye, World! \n");
                    break;
              default:
                    returnCode = EOPNOTSUPP;
                    break;
            }
    
            return(returnCode);
    }
    
    /*
     * Step 3 - Name the module and the event hander function
     *          This is done using a struct of type moduledata_T
     */
    static moduledata_t  moduleData = {
            "hello_world_kmod",     // Module Name
            EventHandler,           // Event handler function name
            NULL                    // Extra data
    };
    
    /*
     * Step 4 - Declare the module
     *          This is done with the DECLARE_MODULE macro
     */
    DECLARE_MODULE(hello_world_kmod, moduleData, SI_SUB_DRIVERS, SI_ORDER_MIDDLE);
    
  5. Save and close the file.

Step 2 – Create a Makefile

Creating a Makefile to build a kernel module is quite easy because almost all the work is done for you. FreeBSD has a file that you include, /usr/src/share/mk/bsd.kmod.mk, that does most of the work for you and all you have to do is include it.

  1. In the same directory where you put your .c file, create a new text file called Makefile.
  2. There are three basic parts to the kernel module Makefile:
    1. Module name
    2. Source files
    3. Include of bsd.kmod.mk
    # Module Name
    KMOD = hello_world_kmod
    
    # Source files
    
    SRCS = hello_world_kmod.c
    
    # Include <bsd.kmod.mk>
    .include <bsd.kmod.mk>
    
  3. Save and close the file.

Step 3 – Run make to build the module

  1. In the command prompt, in the directory where you have created your code and make file, run make.
    > cd /usr/home/jared/code/kernel/hwm
    > make
    Warning: Object directory not changed from original /usr/home/jared/code/kernel/hwm
    @ -> /usr/src/sys
    machine -> /usr/src/sys/amd64/include
    x86 -> /usr/src/sys/x86/include
    cc -O2 -pipe -fno-strict-aliasing -Werror -D_KERNEL -DKLD_MODULE -nostdinc   -I. -I@ -I@/contrib/altq -finline-limit=8000 --param inline-unit-growth=100 --param large-function-growth=1000 -fno-common  -fno-omit-frame-pointer  -mno-sse -mcmodel=kernel -mno-red-zone -mno-mmx -msoft-float  -fno-asynchronous-unwind-tables -ffreestanding -fstack-protector -std=iso9899:1999 -fstack-protector -Wall -Wredundant-decls -Wnested-externs -Wstrict-prototypes  -Wmissing-prototypes -Wpointer-arith -Winline -Wcast-qual  -Wundef -Wno-pointer-sign -fformat-extensions  -Wmissing-include-dirs -fdiagnostics-show-option -c hello_world_kmod.c
    ld  -d -warn-common -r -d -o hello_world_kmod.ko hello_world_kmod.o
    :> export_syms
    awk -f /sys/conf/kmod_syms.awk hello_world_kmod.ko  export_syms | xargs -J% objcopy % hello_world_kmod.ko
    objcopy --strip-debug hello_world_kmod.ko
    >
    

Step 4 – Test loading an unloading the module

Loading and unloading kernel modules must be done as root. If you have sudo installed, use it, otherwise install it (Configuring sudo on FreeBSD) or su to root.

  1. Use kldload to load the module and kldunload to unload the module.
    > sudo kldload ./hello_world_kmod.ko
    Hello, World!
    > sudo kldunload ./hello_world_kmod.ko
    Bye, World!
    >
    

You have now performed the Hello World version of a FreeBSD kernel module.

Resources


WPF jobs trend up according to Indeed.com

According to Indeed.com the amount of WPF job trends up rapidly.

Since XAML is going to be used in Windows 8 as well, it is not going away any time in the next decade. Also, declarative UI will improve in the future, not disappear. So there is job security in this.


Unit Testing Registry access with RhinoMocks and SystemWrapper

As mentioned in the previous Unit Test post (Unit Testing Registry access with RhinoMocks and SystemWrapper) it important to be able to Unit Test code that access the registry without really accessing the registry.

Prerequisites

Step 1 – Download SystemWrapper

You may have already done this when reading the previous post, if not do so now.

  1. Go to https://github.com/jozefizso/SystemWrapper and download the latest dll or the latest source or add the SystemWrapper.Interfaces and SystemWrapper.Wrappers By jozef.izso
  2. Copy the SystemInterface.dll and SystemWrapper.dll into your project (perhaps you already have a libs directory).
  3. Add references to these two dlls in your release code.
  4. Add a reference only to SystemInterface.dll in your Unit Test project.

Step 2 – Change your code to use Interfaces and Wrappers

Ok, so here we are going to start with an example. Here is an object that I wrote myself that uses the registry to check on which versions of .NET Framework are installed. It is currently using Registry and RegistryKey directly.

using System;
using Microsoft.Win32;

namespace SystemInfo
{
    public class DotNetFramework
    {
        #region Constant members
        public const string REGPATH_DOTNET11_VERSION        = @"SOFTWARE\Microsoft\NET Framework Setup\NDP\v1.1.4322";
        public const string REGPATH_DOTNET20_VERSION        = @"SOFTWARE\Microsoft\NET Framework Setup\NDP\v2.0.50727";
        public const string REGPATH_DOTNET30_VERSION        = @"SOFTWARE\Microsoft\NET Framework Setup\NDP\v3.0";
        public const string REGPATH_DOTNET35_VERSION        = @"SOFTWARE\Microsoft\NET Framework Setup\NDP\v3.5";
        public const string REGPATH_DOTNET40_VERSION_CLIENT = @"SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Client";
        public const string REGPATH_DOTNET40_VERSION        = @"SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full";
        #endregion

        #region Properties
        /// <summary>
        /// This returns true if .NET 4 Full is installed.
        /// </summary>
        public bool FoundDotNet4
        {
            get { return HasDotNetFramework(REGPATH_DOTNET40_VERSION, 0); }
        }

        /// <summary>
        /// This returns true if .NET 4 Client is installed.
        /// </summary>
        public bool FoundDotNet4Client
        {
            get { return HasDotNetFramework(REGPATH_DOTNET40_VERSION_CLIENT, 0); }
        }

        /// <summary>
        /// This returns true if .NET 3.5 with SP1 is installed.
        /// </summary>
        public bool FoundDotNet35SP1
        {
            get { return HasDotNetFramework(REGPATH_DOTNET35_VERSION, 1); }
        }

        /// <summary>
        /// This returns true if .NET 3.5 is installed.
        /// </summary>
        public bool FoundDotNet35
        {
            get { return HasDotNetFramework(REGPATH_DOTNET35_VERSION, 0); }
        }

        /// <summary>
        /// This returns true if .NET 3.0 with SP2 is installed.
        /// </summary>
        public bool FoundDotNet30SP2
        {
            get { return HasDotNetFramework(REGPATH_DOTNET30_VERSION, 2); }
        }

        /// <summary>
        /// This returns true if .NET 3.0 with SP1 is installed.
        /// </summary>
        public bool FoundDotNet30SP1
        {
            get { return HasDotNetFramework(REGPATH_DOTNET30_VERSION, 1); }
        }

        /// <summary>
        /// This returns true if .NET 3.0 is installed.
        /// </summary>
        public bool FoundDotNet30
        {
            get { return HasDotNetFramework(REGPATH_DOTNET30_VERSION, 0); }
        }

        /// <summary>
        /// This returns true if .NET 2.0 with SP2 is installed.
        /// </summary>
        public bool FoundDotNet20SP2
        {
            get { return HasDotNetFramework(REGPATH_DOTNET20_VERSION, 2); }
        }

        /// <summary>
        /// This returns true if .NET 2.0 with SP1 is installed.
        /// </summary>
        public bool FoundDotNet20SP1
        {
            get { return HasDotNetFramework(REGPATH_DOTNET20_VERSION, 1); }
        }

        /// <summary>
        /// This returns true if .NET 2.0 is installed.
        /// </summary>
        public bool FoundDotNet20
        {
            get { return HasDotNetFramework(REGPATH_DOTNET20_VERSION, 0); }
        }

        /// <summary>
        /// This returns true if .NET 1.1 is installed.
        /// </summary>
        public bool FoundDotNet11
        {
            get { return HasDotNetFramework(REGPATH_DOTNET11_VERSION, 0); }
        }
        #endregion

        public bool HasDotNetFramework(string dotNetRegPath, int expectedServicePack)
        {
            bool retVal = false;

            try
            {
                RegistryKey localKey = Registry.LocalMachine.OpenSubKey(dotNetRegPath);
                if (localKey != null)
                {
                    int? isInstalled = localKey.GetValue("Install") as int?;
                    if (isInstalled != null)
                    {
                        if (isInstalled == 1)
                        {
                            if (expectedServicePack > 0)
                            {
                                if ((int)localKey.GetValue("SP") >= expectedServicePack)
                                    retVal = true;
                            }
                            else
                            {
                                retVal = true;
                            }
                        }
                    }
                }
                return retVal;
            }
            catch
            {
                return retVal;
            }
        }
    }
}
  1. Find any place in your code where you use touch the system. For example, if you touch the registry, find any place you call Registry or RegistryKey objects or reference Microsoft.Win32.
    Hint: Use the search feature in your IDE.
  2. Replace the reference with a reference to SystemWrapper and SystemInterfaces. For example, if replacingrRegistry code,
    SystemInterface.Microsoft.Win32
    SystemWrapper.Microsoft.Win32In the DotNetFramework.cs file above, there is a using statement to Microsoft.Win32. Our new using statements will be:

    using System;
    using SystemInterface.Microsoft.Win32;
    using SystemWrapper.Microsoft.Win32;
    
  3. For any object that touches the system, change that object to be instantiated using the interface. For example, replace RegistryKey objects with IRegistryKey objects.In the DotNetFramework.cs file, there is only one single line that needs to change to do this, line 113.
    This line…

        RegistryKey localKey = Registry.LocalMachine.OpenSubKey(dotNetRegPath);
    

    …changes to this line.

        IRegistryKey localKey = new RegistryWrap().LocalMachine.OpenSubKey(dotNetRegPath);
    

Step 3 – Allow for replacing the IRegistryKey objects

Create a property or function that allows you to replace the object you are mocking so you can pass in an object that is mocked.

This is done for you to some extent for registry access by using the IAccessTheRegistry interface.

  1. Implementing the IAccessTheRegistry interface from the SystemInterface.Microsoft.Win32 namespace. You can add the following code to the DotNetFramework object.
            #region IAccessTheRegistry Members
    
            public IRegistryKey BaseKey
            {
                get
                {
                    if (null == _BaseKey)
                        _BaseKey = new RegistryWrap().LocalMachine;
                    return _BaseKey;
                }
            } private IRegistryKey _BaseKey;
    
            public void ChangeBaseKey(IRegistryKey inBaseKey)
            {
                _BaseKey = inBaseKey;
            }
    
            #endregion
    

    Note: Notice that the Property is read only. Instead of enabling the set ability, a function is created to allow you to change the IRegistryKey instance. This is by design and keeps you from making a mistake such as BaseKey = BaseKey.OpenSubkey(“…”) and replacing the BaseKey.

    Note: You may want to look into the “Factory” design pattern.

  2. Change line 113 to use the BaseKey.
        IRegistryKey localKey = BaseKey.OpenSubKey(dotNetRegPath);
    

Step 4 – Download and Reference RhinoMocks in your Unit Test

You may have already done this when reading the previous post, if not do so now.

In this step you need to download RhinoMocks and reference it with your Unit Test project. If you don’t have a test project, create one.  Your release project won’t need it.

  1. Go to http://hibernatingrhinos.com/open-source/rhino-mocks and download RhinoMocks.
  2. Add RhinoMocks.dll

Step 5 – Mock IRegistryKey in your Unit Test

For this, you have to understand and know how to use RhinoMocks and this takes some learning. For this we need an example.

  1. Add a new class to your test project.
  2. Add a using statement:
    using&nbsp;Rhino.Mocks;
  3. Add code to create the Mock objects.I put these in separate functions because every test needed the exact same code.
    1. Mock the HKLM key and any calls made using it.
    2. Mock the registry sub key and any calls made using it.
    #region Test Helper Functions
            /// <summary>
            /// Mock to pretend to be this registry subkey:
            /// Hive:   HKLM
            ///
            /// No stubbing is preconfigured
            /// </summary>
            /// <returns>IRegistryKey</returns>
            private IRegistryKey CreateMockOfHKLM()
            {
                // Mock to pretend to be this registry key:
                // Hive:   HKLM
                IRegistryKey hklmMock = MockRepository.GenerateMock<IRegistryKey>();
                hklmMock.Stub(x => x.Name).Return("HKEY_LOCAL_MACHINE");
    
                return hklmMock;
            }
    
            /// <summary>
            /// Mock to pretend to be this registry subkey:
            /// Hive:   HKLM
            ///
            /// It has stubs preconfigured
            /// </summary>
            /// <returns>IRegistry that is a mock of HKLM with IIS Version stubs.</returns>
            private IRegistryKey CreateDotNetRegistryOpenSubKeyMock(string inSubkey, bool inIsInstalled = true, int? inSP = null)
            {
                // Mock to pretend to be this registry subkey:
                // Hive:   HKLM
                IRegistryKey hklmMock = CreateMockOfHKLM();
    
                // Allow to test a key that doesn't exist (null) or one that does.
                IRegistryKey dotNetMock = null;
                if (inIsInstalled)
                {
                    dotNetMock = CreateDotNetRegistryGetValueMock(inSubkey, inSP);
                }
    
                // Stubs using hklmMock to open and return this registry key
                // and return dotNetMock:
                hklmMock.Stub(x => x.OpenSubKey(inSubkey)).Return(dotNetMock);
    
                return hklmMock;
            }
    
            private IRegistryKey CreateDotNetRegistryGetValueMock(string inSubkey, int? inSP)
            {
                // Mock to pretend to be this subkey passed in:
                // Hive:   HKLM
                // SubKey: HKEY_LOCAL_MACHINE\" + inSubkey
                IRegistryKey dotNetMock = MockRepository.GenerateMock<IRegistryKey>();
                dotNetMock.Stub(x => x.Name).Return(@"HKEY_LOCAL_MACHINE\" + inSubkey);
    
                // Stubs checking the available registry properties:
                // Hive:   HKLM
                // SubKey: HKEY_LOCAL_MACHINE\" + inSubkey
                // Properties: "Install", "SP"
                dotNetMock.Stub(x => x.GetValueNames()).Return(new String[] { "Install", "SP" });
    
                // Stubs checking this registry:
                // Hive:   HKLM
                // SubKey: HKEY_LOCAL_MACHINE\" + inSubkey
                // Property: Install
                // Value:  1 - If not installed the whole key shouldn't even exist so it should always be 1
                dotNetMock.Stub(x => x.GetValue("Install")).Return(1);
    
                if (null != inSP)
                {
                    // Stubs checking this registry:
                    // Hive:   HKLM
                    // SubKey: HKEY_LOCAL_MACHINE\" + inSubkey
                    // Property: SP
                    // Value:    null or 1, 2, 3, ...
                    dotNetMock.Stub(x => x.GetValue("SP")).Return(inSP);
                }
                return dotNetMock;
            }
            #endregion
    
  4. Now go forth and mock all your code that uses the Registry.

Here is the final test file.

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Rhino.Mocks;
using SystemInfo;
using SystemInterface.Microsoft.Win32;

namespace DotNetFrameworkTest
{
    /// <summary>
    ///This is a test class for DotNetFrameworkTest and is intended
    ///to contain all DotNetFrameworkTest Unit Tests
    ///</summary>
    [TestClass()]
    public class DotNetFrameworkTest
    {
        #region Constructor tests
        /// <summary>
        ///A test for DotNetFramework Constructor
        ///</summary>
        [TestMethod()]
        public void DotNetFrameworkConstructorTest()
        {
            DotNetFramework target = new DotNetFramework();
            Assert.IsNotNull(target);
        }
        #endregion

        #region IAccessTheRegistry interface items test
        /// <summary>
        ///A test for ChangeBaseKey
        ///</summary>
        [TestMethod()]
        public void BaseKeyAndChangeBaseKeyTest()
        {
            DotNetFramework target = new DotNetFramework(); // TODO: Initialize to an appropriate value
            IRegistryKey defaultBaseKey = target.BaseKey;
            IRegistryKey inBaseKey = MockRepository.GenerateMock<IRegistryKey>();
            target.ChangeBaseKey(inBaseKey);

            // Make sure the newly assigned is not the same as the original
            Assert.AreNotEqual(target.BaseKey, defaultBaseKey);

            // Make sure that the assignment worked
            Assert.AreEqual(target.BaseKey, inBaseKey);
        }
        #endregion

        #region FoundDotNet11 tests
        /// <summary>
        ///A test for FoundDotNet11 mocking the key so it should return true
        ///</summary>
        [TestMethod()]
        public void FoundDotNet11_Test_KeyExists()
        {
            bool isInstalled = true;
            DotNetFramework target = new DotNetFramework();
            IRegistryKey key = CreateDotNetRegistryOpenSubKeyMock(DotNetFramework.REGPATH_DOTNET11_VERSION, isInstalled);
            target.ChangeBaseKey(key);
            bool expected = true;
            bool actual = target.FoundDotNet11;
            Assert.AreEqual(actual, expected);

            key.AssertWasCalled(x => x.OpenSubKey(DotNetFramework.REGPATH_DOTNET11_VERSION));
            IRegistryKey innerkey = key.OpenSubKey(DotNetFramework.REGPATH_DOTNET11_VERSION);
            innerkey.AssertWasCalled(x => x.GetValue("Install"));
            innerkey.AssertWasNotCalled(x => x.GetValue("SP"));
        }

        /// <summary>
        ///A test for FoundDotNet11 mocking the lack of a key so it should return false
        ///</summary>
        [TestMethod()]
        public void FoundDotNet11_Test_KeyDoesNotExist()
        {
            bool isInstalled = false;
            DotNetFramework target = new DotNetFramework();
            IRegistryKey key = CreateDotNetRegistryOpenSubKeyMock(DotNetFramework.REGPATH_DOTNET11_VERSION, isInstalled);
            target.ChangeBaseKey(key);
            bool expected = false;
            bool actual = target.FoundDotNet11;

            Assert.AreEqual(actual, expected);
            key.AssertWasCalled(x => x.OpenSubKey(DotNetFramework.REGPATH_DOTNET11_VERSION));
            Assert.IsNull(key.OpenSubKey(DotNetFramework.REGPATH_DOTNET11_VERSION));
        }
        #endregion

        #region FoundDotNet20 tests
        /// <summary>
        ///A test for FoundDotNet20 mocking the key so it should return true
        ///</summary>
        [TestMethod()]
        public void FoundDotNet20_Test_KeyExists()
        {
            bool isInstalled = true;
            DotNetFramework target = new DotNetFramework();
            IRegistryKey key = CreateDotNetRegistryOpenSubKeyMock(DotNetFramework.REGPATH_DOTNET20_VERSION, isInstalled);
            target.ChangeBaseKey(key);
            bool expected = true;
            bool actual = target.FoundDotNet20;
            Assert.AreEqual(actual, expected);

            key.AssertWasCalled(x => x.OpenSubKey(DotNetFramework.REGPATH_DOTNET20_VERSION));
            IRegistryKey innerkey = key.OpenSubKey(DotNetFramework.REGPATH_DOTNET20_VERSION);
            innerkey.AssertWasCalled(x => x.GetValue("Install"));
            innerkey.AssertWasNotCalled(x => x.GetValue("SP"));
        }

        /// <summary>
        ///A test for FoundDotNet20 mocking the lack of a key so it should return false
        ///</summary>
        [TestMethod()]
        public void FoundDotNet20_Test_KeyDoesNotExist()
        {
            bool isInstalled = false;
            DotNetFramework target = new DotNetFramework();
            IRegistryKey key = CreateDotNetRegistryOpenSubKeyMock(DotNetFramework.REGPATH_DOTNET20_VERSION, isInstalled);
            target.ChangeBaseKey(key);
            bool expected = false;
            bool actual = target.FoundDotNet20;

            Assert.AreEqual(actual, expected);
            key.AssertWasCalled(x => x.OpenSubKey(DotNetFramework.REGPATH_DOTNET20_VERSION));
            Assert.IsNull(key.OpenSubKey(DotNetFramework.REGPATH_DOTNET20_VERSION));
        }
        #endregion

        #region FoundDOtNet20SP1 tests
        /// <summary>
        ///A test for FoundDotNet20SP1 mocking the key so it should return true
        ///</summary>
        [TestMethod()]
        public void FoundDotNet20SP1_Test_KeyExistsWithSP1()
        {
            bool isInstalled = true;
            int? sp = 1;
            DotNetFramework target = new DotNetFramework();
            IRegistryKey key = CreateDotNetRegistryOpenSubKeyMock(DotNetFramework.REGPATH_DOTNET20_VERSION, isInstalled, sp);
            target.ChangeBaseKey(key);
            bool expected = true;
            bool actual = target.FoundDotNet20SP1;
            
            Assert.AreEqual(actual, expected);
            key.AssertWasCalled(x => x.OpenSubKey(DotNetFramework.REGPATH_DOTNET20_VERSION));
            IRegistryKey innerkey = key.OpenSubKey(DotNetFramework.REGPATH_DOTNET20_VERSION);
            innerkey.AssertWasCalled(x => x.GetValue("Install"));
            innerkey.AssertWasCalled(x => x.GetValue("SP"));
        }

        /// <summary>
        ///A test for FoundDotNet20SP1 mocking the key so it should return false due to no service pack
        ///</summary>
        [TestMethod()]
        public void FoundDotNet20SP1_Test_KeyExistsWithoutSP1()
        {
            bool isInstalled = true;
            int? sp = null;
            DotNetFramework target = new DotNetFramework();
            IRegistryKey key = CreateDotNetRegistryOpenSubKeyMock(DotNetFramework.REGPATH_DOTNET20_VERSION, isInstalled, sp);
            target.ChangeBaseKey(key);
            bool expected = false;
            bool actual = target.FoundDotNet20SP1;
            
            Assert.AreEqual(actual, expected);
            key.AssertWasCalled(x => x.OpenSubKey(DotNetFramework.REGPATH_DOTNET20_VERSION));
            IRegistryKey innerkey = key.OpenSubKey(DotNetFramework.REGPATH_DOTNET20_VERSION);
            innerkey.AssertWasCalled(x => x.GetValue("Install"));
            innerkey.AssertWasCalled(x => x.GetValue("SP"));
        }

        /// <summary>
        ///A test for FoundDotNet20SP1 mocking the lack of a key so it should return false
        ///</summary>
        [TestMethod()]
        public void FoundDotNet20SP1_Test_KeyDoesNotExist()
        {
            bool isInstalled = false;
            DotNetFramework target = new DotNetFramework();
            IRegistryKey key = CreateDotNetRegistryOpenSubKeyMock(DotNetFramework.REGPATH_DOTNET20_VERSION, isInstalled);
            target.ChangeBaseKey(key);
            bool expected = false;
            bool actual = target.FoundDotNet20SP1;

            Assert.AreEqual(actual, expected);
            key.AssertWasCalled(x => x.OpenSubKey(DotNetFramework.REGPATH_DOTNET20_VERSION));
            Assert.IsNull(key.OpenSubKey(DotNetFramework.REGPATH_DOTNET20_VERSION));
        }
        #endregion

        #region FoundDOtNet20SP2 tests
        /// <summary>
        ///A test for FoundDotNet20SP2 mocking the key so it should return true
        ///</summary>
        [TestMethod()]
        public void FoundDotNet20SP2_Test_KeyExistsWithSP2()
        {
            bool isInstalled = true;
            int? sp = 2;
            DotNetFramework target = new DotNetFramework();
            IRegistryKey key = CreateDotNetRegistryOpenSubKeyMock(DotNetFramework.REGPATH_DOTNET20_VERSION, isInstalled, sp);
            target.ChangeBaseKey(key);
            bool expected = true;
            bool actual = target.FoundDotNet20SP2;

            Assert.AreEqual(actual, expected);
            key.AssertWasCalled(x => x.OpenSubKey(DotNetFramework.REGPATH_DOTNET20_VERSION));
            IRegistryKey innerkey = key.OpenSubKey(DotNetFramework.REGPATH_DOTNET20_VERSION);
            innerkey.AssertWasCalled(x => x.GetValue("Install"));
            innerkey.AssertWasCalled(x => x.GetValue("SP"));
        }

        /// <summary>
        ///A test for FoundDotNet20SP2 mocking the key so it should return false because it only has SP1
        ///</summary>
        [TestMethod()]
        public void FoundDotNet20SP2_Test_KeyExistsWithSP1()
        {
            bool isInstalled = true;
            int? sp = 1;
            DotNetFramework target = new DotNetFramework();
            IRegistryKey key = CreateDotNetRegistryOpenSubKeyMock(DotNetFramework.REGPATH_DOTNET20_VERSION, isInstalled, sp);
            target.ChangeBaseKey(key);
            bool expected = false;
            bool actual = target.FoundDotNet20SP2;

            Assert.AreEqual(actual, expected);
            key.AssertWasCalled(x => x.OpenSubKey(DotNetFramework.REGPATH_DOTNET20_VERSION));
            IRegistryKey innerkey = key.OpenSubKey(DotNetFramework.REGPATH_DOTNET20_VERSION);
            innerkey.AssertWasCalled(x => x.GetValue("Install"));
            innerkey.AssertWasCalled(x => x.GetValue("SP"));
        }

        /// <summary>
        ///A test for FoundDotNet20SP2 mocking the key so it should return false due to no service pack
        ///</summary>
        [TestMethod()]
        public void FoundDotNet20SP2_Test_KeyExistsWithoutSP()
        {
            bool isInstalled = true;
            int? sp = null;
            DotNetFramework target = new DotNetFramework();
            IRegistryKey key = CreateDotNetRegistryOpenSubKeyMock(DotNetFramework.REGPATH_DOTNET20_VERSION, isInstalled, sp);
            target.ChangeBaseKey(key);
            bool expected = false;
            bool actual = target.FoundDotNet20SP2;

            Assert.AreEqual(actual, expected);
            key.AssertWasCalled(x => x.OpenSubKey(DotNetFramework.REGPATH_DOTNET20_VERSION));
            IRegistryKey innerkey = key.OpenSubKey(DotNetFramework.REGPATH_DOTNET20_VERSION);
            innerkey.AssertWasCalled(x => x.GetValue("Install"));
            innerkey.AssertWasCalled(x => x.GetValue("SP"));
        }

        /// <summary>
        ///A test for FoundDotNet20SP2 mocking the lack of a key so it should return false
        ///</summary>
        [TestMethod()]
        public void FoundDotNet20SP2_Test_KeyDoesNotExist()
        {
            bool isInstalled = false;
            DotNetFramework target = new DotNetFramework();
            IRegistryKey key = CreateDotNetRegistryOpenSubKeyMock(DotNetFramework.REGPATH_DOTNET20_VERSION, isInstalled);
            target.ChangeBaseKey(key);
            bool expected = false;
            bool actual = target.FoundDotNet20SP2;

            Assert.AreEqual(actual, expected);
            key.AssertWasCalled(x => x.OpenSubKey(DotNetFramework.REGPATH_DOTNET20_VERSION));
            Assert.IsNull(key.OpenSubKey(DotNetFramework.REGPATH_DOTNET20_VERSION));
        }
        #endregion

        #region FoundDotNet30 tests
        /// <summary>
        ///A test for FoundDotNet30 mocking the key so it should return true
        ///</summary>
        [TestMethod()]
        public void FoundDotNet30_Test_KeyExists()
        {
            bool isInstalled = true;
            DotNetFramework target = new DotNetFramework();
            IRegistryKey key = CreateDotNetRegistryOpenSubKeyMock(DotNetFramework.REGPATH_DOTNET30_VERSION, isInstalled);
            target.ChangeBaseKey(key);
            bool expected = true;
            bool actual = target.FoundDotNet30;

            Assert.AreEqual(actual, expected);
            key.AssertWasCalled(x => x.OpenSubKey(DotNetFramework.REGPATH_DOTNET30_VERSION));
            IRegistryKey innerkey = key.OpenSubKey(DotNetFramework.REGPATH_DOTNET30_VERSION);
            innerkey.AssertWasCalled(x => x.GetValue("Install"));
            innerkey.AssertWasNotCalled(x => x.GetValue("SP"));
        }

        /// <summary>
        ///A test for FoundDotNet30 mocking the lack of a key so it should return false
        ///</summary>
        [TestMethod()]
        public void FoundDotNet30_Test_KeyDoesNotExist()
        {
            bool isInstalled = false;
            DotNetFramework target = new DotNetFramework();
            IRegistryKey key = CreateDotNetRegistryOpenSubKeyMock(DotNetFramework.REGPATH_DOTNET30_VERSION, isInstalled);
            target.ChangeBaseKey(key);
            bool expected = false;
            bool actual = target.FoundDotNet30;

            Assert.AreEqual(actual, expected);
            key.AssertWasCalled(x => x.OpenSubKey(DotNetFramework.REGPATH_DOTNET30_VERSION));
            Assert.IsNull(key.OpenSubKey(DotNetFramework.REGPATH_DOTNET30_VERSION));
        }
        #endregion

        #region FoundDOtNet30SP1 tests
        /// <summary>
        ///A test for FoundDotNet30SP1 mocking the key so it should return true
        ///</summary>
        [TestMethod()]
        public void FoundDotNet30SP1_Test_KeyExistsWithSP1()
        {
            bool isInstalled = true;
            int? sp = 1;
            DotNetFramework target = new DotNetFramework();
            IRegistryKey key = CreateDotNetRegistryOpenSubKeyMock(DotNetFramework.REGPATH_DOTNET30_VERSION, isInstalled, sp);
            target.ChangeBaseKey(key);
            bool expected = true;
            bool actual = target.FoundDotNet30SP1;

            Assert.AreEqual(actual, expected);
            key.AssertWasCalled(x => x.OpenSubKey(DotNetFramework.REGPATH_DOTNET30_VERSION));
            IRegistryKey innerkey = key.OpenSubKey(DotNetFramework.REGPATH_DOTNET30_VERSION);
            innerkey.AssertWasCalled(x => x.GetValue("Install"));
            innerkey.AssertWasCalled(x => x.GetValue("SP"));
        }

        /// <summary>
        ///A test for FoundDotNet30SP1 mocking the key so it should return false due to no service pack
        ///</summary>
        [TestMethod()]
        public void FoundDotNet30SP1_Test_KeyExistsWithoutSP()
        {
            bool isInstalled = true;
            int? sp = null;
            DotNetFramework target = new DotNetFramework();
            IRegistryKey key = CreateDotNetRegistryOpenSubKeyMock(DotNetFramework.REGPATH_DOTNET30_VERSION, isInstalled, sp);
            target.ChangeBaseKey(key);
            bool expected = false;
            bool actual = target.FoundDotNet30SP1;

            Assert.AreEqual(actual, expected);
            key.AssertWasCalled(x => x.OpenSubKey(DotNetFramework.REGPATH_DOTNET30_VERSION));
            IRegistryKey innerkey = key.OpenSubKey(DotNetFramework.REGPATH_DOTNET30_VERSION);
            innerkey.AssertWasCalled(x => x.GetValue("Install"));
            innerkey.AssertWasCalled(x => x.GetValue("SP"));
        }

        /// <summary>
        ///A test for FoundDotNet30SP1 mocking the lack of a key so it should return false
        ///</summary>
        [TestMethod()]
        public void FoundDotNet30SP1_Test_KeyDoesNotExist()
        {
            bool isInstalled = false;
            DotNetFramework target = new DotNetFramework();
            IRegistryKey key = CreateDotNetRegistryOpenSubKeyMock(DotNetFramework.REGPATH_DOTNET30_VERSION, isInstalled);
            target.ChangeBaseKey(key);
            bool expected = false;
            bool actual = target.FoundDotNet30SP1;

            Assert.AreEqual(actual, expected);
            key.AssertWasCalled(x => x.OpenSubKey(DotNetFramework.REGPATH_DOTNET30_VERSION));
            Assert.IsNull(key.OpenSubKey(DotNetFramework.REGPATH_DOTNET30_VERSION));
        }
        #endregion

        #region FoundDOtNet30SP2 tests
        /// <summary>
        ///A test for FoundDotNet30SP2 mocking the key so it should return true
        ///</summary>
        [TestMethod()]
        public void FoundDotNet30SP2_Test_KeyExistsWithSP2()
        {
            bool isInstalled = true;
            int? sp = 2;
            DotNetFramework target = new DotNetFramework();
            IRegistryKey key = CreateDotNetRegistryOpenSubKeyMock(DotNetFramework.REGPATH_DOTNET30_VERSION, isInstalled, sp);
            target.ChangeBaseKey(key);
            bool expected = true;
            bool actual = target.FoundDotNet30SP2;

            Assert.AreEqual(actual, expected);
            key.AssertWasCalled(x => x.OpenSubKey(DotNetFramework.REGPATH_DOTNET30_VERSION));
            IRegistryKey innerkey = key.OpenSubKey(DotNetFramework.REGPATH_DOTNET30_VERSION);
            innerkey.AssertWasCalled(x => x.GetValue("Install"));
            innerkey.AssertWasCalled(x => x.GetValue("SP"));
        }

        /// <summary>
        ///A test for FoundDotNet30SP2 mocking the key so it should return false because it only has SP1
        ///</summary>
        [TestMethod()]
        public void FoundDotNet30SP2_Test_KeyExistsWithSP1()
        {
            bool isInstalled = true;
            int? sp = 1;
            DotNetFramework target = new DotNetFramework();
            IRegistryKey key = CreateDotNetRegistryOpenSubKeyMock(DotNetFramework.REGPATH_DOTNET30_VERSION, isInstalled, sp);
            target.ChangeBaseKey(key);
            bool expected = false;
            bool actual = target.FoundDotNet30SP2;

            Assert.AreEqual(actual, expected);
            key.AssertWasCalled(x => x.OpenSubKey(DotNetFramework.REGPATH_DOTNET30_VERSION));
            IRegistryKey innerkey = key.OpenSubKey(DotNetFramework.REGPATH_DOTNET30_VERSION);
            innerkey.AssertWasCalled(x => x.GetValue("Install"));
            innerkey.AssertWasCalled(x => x.GetValue("SP"));
        }

        /// <summary>
        ///A test for FoundDotNet30SP2 mocking the key so it should return false due to no service pack
        ///</summary>
        [TestMethod()]
        public void FoundDotNet30SP2_Test_KeyExistsWithoutSP()
        {
            bool isInstalled = true;
            int? sp = null;
            DotNetFramework target = new DotNetFramework();
            IRegistryKey key = CreateDotNetRegistryOpenSubKeyMock(DotNetFramework.REGPATH_DOTNET30_VERSION, isInstalled, sp);
            target.ChangeBaseKey(key);
            bool expected = false;
            bool actual = target.FoundDotNet30SP2;

            Assert.AreEqual(actual, expected);
            key.AssertWasCalled(x => x.OpenSubKey(DotNetFramework.REGPATH_DOTNET30_VERSION));
            IRegistryKey innerkey = key.OpenSubKey(DotNetFramework.REGPATH_DOTNET30_VERSION);
            innerkey.AssertWasCalled(x => x.GetValue("Install"));
            innerkey.AssertWasCalled(x => x.GetValue("SP"));
        }

        /// <summary>
        ///A test for FoundDotNet30SP2 mocking the lack of a key so it should return false
        ///</summary>
        [TestMethod()]
        public void FoundDotNet30SP2_Test_KeyDoesNotExist()
        {
            bool isInstalled = false;
            DotNetFramework target = new DotNetFramework();
            IRegistryKey key = CreateDotNetRegistryOpenSubKeyMock(DotNetFramework.REGPATH_DOTNET30_VERSION, isInstalled);
            target.ChangeBaseKey(key);
            bool expected = false;
            bool actual = target.FoundDotNet30SP2;

            Assert.AreEqual(actual, expected);
            key.AssertWasCalled(x => x.OpenSubKey(DotNetFramework.REGPATH_DOTNET30_VERSION));
            Assert.IsNull(key.OpenSubKey(DotNetFramework.REGPATH_DOTNET30_VERSION));
        }
        #endregion
        
        #region FoundDotNet35 tests
        /// <summary>
        ///A test for FoundDotNet35 mocking the key so it should return true
        ///</summary>
        [TestMethod()]
        public void FoundDotNet35_Test_KeyExists()
        {
            bool isInstalled = true;
            DotNetFramework target = new DotNetFramework();
            IRegistryKey key = CreateDotNetRegistryOpenSubKeyMock(DotNetFramework.REGPATH_DOTNET35_VERSION, isInstalled);
            target.ChangeBaseKey(key);
            bool expected = true;
            bool actual = target.FoundDotNet35;

            Assert.AreEqual(actual, expected);
            key.AssertWasCalled(x => x.OpenSubKey(DotNetFramework.REGPATH_DOTNET35_VERSION));
            IRegistryKey innerkey = key.OpenSubKey(DotNetFramework.REGPATH_DOTNET35_VERSION);
            innerkey.AssertWasCalled(x => x.GetValue("Install"));
            innerkey.AssertWasNotCalled(x => x.GetValue("SP"));
        }

        /// <summary>
        ///A test for FoundDotNet35 mocking the lack of a key so it should return false
        ///</summary>
        [TestMethod()]
        public void FoundDotNet35_Test_KeyDoesNotExist()
        {
            bool isInstalled = false;
            DotNetFramework target = new DotNetFramework();
            IRegistryKey key = CreateDotNetRegistryOpenSubKeyMock(DotNetFramework.REGPATH_DOTNET35_VERSION, isInstalled);
            target.ChangeBaseKey(key);
            bool expected = false;
            bool actual = target.FoundDotNet35;

            Assert.AreEqual(actual, expected);
            key.AssertWasCalled(x => x.OpenSubKey(DotNetFramework.REGPATH_DOTNET35_VERSION));
            Assert.IsNull(key.OpenSubKey(DotNetFramework.REGPATH_DOTNET35_VERSION));
        }
        #endregion

        #region FoundDOtNet35SP1 tests
        /// <summary>
        ///A test for FoundDotNet35SP1 mocking the key so it should return true
        ///</summary>
        [TestMethod()]
        public void FoundDotNet35SP1_Test_KeyExistsWithSP1()
        {
            bool isInstalled = true;
            int? sp = 1;
            DotNetFramework target = new DotNetFramework();
            IRegistryKey key = CreateDotNetRegistryOpenSubKeyMock(DotNetFramework.REGPATH_DOTNET35_VERSION, isInstalled, sp);
            target.ChangeBaseKey(key);
            bool expected = true;
            bool actual = target.FoundDotNet35SP1;

            Assert.AreEqual(actual, expected);
            key.AssertWasCalled(x => x.OpenSubKey(DotNetFramework.REGPATH_DOTNET35_VERSION));
            IRegistryKey innerkey = key.OpenSubKey(DotNetFramework.REGPATH_DOTNET35_VERSION);
            innerkey.AssertWasCalled(x => x.GetValue("Install"));
            innerkey.AssertWasCalled(x => x.GetValue("SP"));
        }

        /// <summary>
        ///A test for FoundDotNet35SP1 mocking the key so it should return false due to no service pack
        ///</summary>
        [TestMethod()]
        public void FoundDotNet35SP1_Test_KeyExistsWithoutSP()
        {
            bool isInstalled = true;
            int? sp = null;
            DotNetFramework target = new DotNetFramework();
            IRegistryKey key = CreateDotNetRegistryOpenSubKeyMock(DotNetFramework.REGPATH_DOTNET35_VERSION, isInstalled, sp);
            target.ChangeBaseKey(key);
            bool expected = false;
            bool actual = target.FoundDotNet35SP1;

            Assert.AreEqual(actual, expected);
            key.AssertWasCalled(x => x.OpenSubKey(DotNetFramework.REGPATH_DOTNET35_VERSION));
            IRegistryKey innerkey = key.OpenSubKey(DotNetFramework.REGPATH_DOTNET35_VERSION);
            innerkey.AssertWasCalled(x => x.GetValue("Install"));
            innerkey.AssertWasCalled(x => x.GetValue("SP"));
        }

        /// <summary>
        ///A test for FoundDotNet35SP1 mocking the lack of a key so it should return false
        ///</summary>
        [TestMethod()]
        public void FoundDotNet35SP1_Test_KeyDoesNotExist()
        {
            bool isInstalled = false;
            DotNetFramework target = new DotNetFramework();
            IRegistryKey key = CreateDotNetRegistryOpenSubKeyMock(DotNetFramework.REGPATH_DOTNET35_VERSION, isInstalled);
            target.ChangeBaseKey(key);
            bool expected = false;
            bool actual = target.FoundDotNet35SP1;

            Assert.AreEqual(actual, expected);
            key.AssertWasCalled(x => x.OpenSubKey(DotNetFramework.REGPATH_DOTNET35_VERSION));
            Assert.IsNull(key.OpenSubKey(DotNetFramework.REGPATH_DOTNET35_VERSION));
        }
        #endregion

        #region FoundDotNet 4 Full tests
        /// <summary>
        ///A test for FoundDotNet4 (full) mocking the key so it should return true
        ///</summary>
        [TestMethod()]
        public void FoundDotNet4_Full_Test_KeyExists()
        {
            bool isInstalled = true;
            DotNetFramework target = new DotNetFramework();
            IRegistryKey key = CreateDotNetRegistryOpenSubKeyMock(DotNetFramework.REGPATH_DOTNET40_VERSION, isInstalled);
            target.ChangeBaseKey(key);
            bool expected = true;
            bool actual = target.FoundDotNet4;

            Assert.AreEqual(actual, expected);
            key.AssertWasCalled(x => x.OpenSubKey(DotNetFramework.REGPATH_DOTNET40_VERSION));
            IRegistryKey innerkey = key.OpenSubKey(DotNetFramework.REGPATH_DOTNET40_VERSION);
            innerkey.AssertWasCalled(x => x.GetValue("Install"));
            innerkey.AssertWasNotCalled(x => x.GetValue("SP"));
        }

        /// <summary>
        ///A test for FoundDotNet4 (full) mocking the lack of a key so it should return false
        ///</summary>
        [TestMethod()]
        public void FoundDotNet4_Test_KeyDoesNotExist()
        {
            bool isInstalled = false;
            DotNetFramework target = new DotNetFramework();
            IRegistryKey key = CreateDotNetRegistryOpenSubKeyMock(DotNetFramework.REGPATH_DOTNET40_VERSION, isInstalled);
            target.ChangeBaseKey(key);
            bool expected = false;
            bool actual = target.FoundDotNet4;

            Assert.AreEqual(actual, expected);
            key.AssertWasCalled(x => x.OpenSubKey(DotNetFramework.REGPATH_DOTNET40_VERSION));
            Assert.IsNull(key.OpenSubKey(DotNetFramework.REGPATH_DOTNET40_VERSION));
        }
        #endregion

        #region FoundDotNet4 Client tests
        /// <summary>
        ///A test for FoundDotNet4Client mocking the key so it should return true
        ///</summary>
        [TestMethod()]
        public void FoundDotNet4Client_Test_KeyExists()
        {
            bool isInstalled = true;
            DotNetFramework target = new DotNetFramework();
            IRegistryKey key = CreateDotNetRegistryOpenSubKeyMock(DotNetFramework.REGPATH_DOTNET40_VERSION_CLIENT, isInstalled);
            target.ChangeBaseKey(key);
            bool expected = true;
            bool actual = target.FoundDotNet4Client;

            Assert.AreEqual(actual, expected);
            key.AssertWasCalled(x => x.OpenSubKey(DotNetFramework.REGPATH_DOTNET40_VERSION_CLIENT));
            IRegistryKey innerkey = key.OpenSubKey(DotNetFramework.REGPATH_DOTNET40_VERSION_CLIENT);
            innerkey.AssertWasCalled(x => x.GetValue("Install"));
            innerkey.AssertWasNotCalled(x => x.GetValue("SP"));
        }

        /// <summary>
        ///A test for FoundDotNet4 (client) mocking the lack of a key so it should return false
        ///</summary>
        [TestMethod()]
        public void FoundDotNet4Client_Test_KeyDoesNotExist()
        {
            bool isInstalled = false;
            DotNetFramework target = new DotNetFramework();
            IRegistryKey key = CreateDotNetRegistryOpenSubKeyMock(DotNetFramework.REGPATH_DOTNET40_VERSION_CLIENT, isInstalled);
            target.ChangeBaseKey(key);
            bool expected = false;
            bool actual = target.FoundDotNet4Client;

            Assert.AreEqual(actual, expected);
            key.AssertWasCalled(x => x.OpenSubKey(DotNetFramework.REGPATH_DOTNET40_VERSION_CLIENT));
            Assert.IsNull(key.OpenSubKey(DotNetFramework.REGPATH_DOTNET40_VERSION_CLIENT));
        }
        #endregion

        #region HasDotNetFrameworkTest
        /// <summary>
        ///A test for HasDotNetFramework
        ///</summary>
        [TestMethod()]
        public void HasDotNetFrameworkTest()
        {
            // No need to test this as all properties test this
        }

        #endregion

        #region Test Helper Functions
        /// <summary>
        /// Mock to pretend to be this registry subkey:
        /// Hive:   HKLM
        /// 
        /// No stubbing is preconfigured
        /// </summary>
        /// <returns>IRegistryKey</returns>
        private IRegistryKey CreateMockOfHKLM()
        {
            // Mock to pretend to be this registry key:
            // Hive:   HKLM
            IRegistryKey hklmMock = MockRepository.GenerateMock<IRegistryKey>();
            hklmMock.Stub(x => x.Name).Return("HKEY_LOCAL_MACHINE");

            return hklmMock;
        }

        /// <summary>
        /// Mock to pretend to be this registry subkey:
        /// Hive:   HKLM
        /// 
        /// It has stubs preconfigured
        /// </summary>
        /// <returns>IRegistry that is a mock of HKLM with IIS Version stubs.</returns>
        private IRegistryKey CreateDotNetRegistryOpenSubKeyMock(string inSubkey, bool inIsInstalled = true, int? inSP = null)
        {
            // Mock to pretend to be this registry subkey:
            // Hive:   HKLM
            IRegistryKey hklmMock = CreateMockOfHKLM();

            // Allow to test a key that doesn't exist (null) or one that does.
            IRegistryKey dotNetMock = null;
            if (inIsInstalled)
            {
                dotNetMock = CreateDotNetRegistryGetValueMock(inSubkey, inSP);
            }

            // Stubs using hklmMock to open and return this registry key
            // and return dotNetMock:
            hklmMock.Stub(x => x.OpenSubKey(inSubkey)).Return(dotNetMock);
            
            return hklmMock;
        }

        private IRegistryKey CreateDotNetRegistryGetValueMock(string inSubkey, int? inSP)
        {
            // Mock to pretend to be this subkey passed in:
            // Hive:   HKLM
            // SubKey: HKEY_LOCAL_MACHINE\" + inSubkey
            IRegistryKey dotNetMock = MockRepository.GenerateMock<IRegistryKey>();
            dotNetMock.Stub(x => x.Name).Return(@"HKEY_LOCAL_MACHINE\" + inSubkey);

            // Stubs checking the available registry properties:
            // Hive:   HKLM
            // SubKey: HKEY_LOCAL_MACHINE\" + inSubkey
            // Properties: "Install", "SP"
            dotNetMock.Stub(x => x.GetValueNames()).Return(new String[] { "Install", "SP" });

            // Stubs checking this registry:
            // Hive:   HKLM
            // SubKey: HKEY_LOCAL_MACHINE\" + inSubkey
            // Property: Install
            // Value:  1 - If not installed the whole key shouldn't even exist so it should always be 1
            dotNetMock.Stub(x => x.GetValue("Install")).Return(1);

            if (null != inSP)
            {
                // Stubs checking this registry:
                // Hive:   HKLM
                // SubKey: HKEY_LOCAL_MACHINE\" + inSubkey
                // Property: SP
                // Value:    null or 1, 2, 3, ...
                dotNetMock.Stub(x => x.GetValue("SP")).Return(inSP);
            }
            return dotNetMock;
        }
        #endregion

    }
}

Return to C# Unit Test Tutorial


Unit Testing code that touches the system

Unit Tests should be fast and simple and they should not touch the system. What we mean by touching the system is any code that actually changes the file system or registry of the build system that runs the Unit Tests. Also any code that touches a remote system such as a database or a web server as these remote system should not have to exist during a Unit Test.

Unit Test Presentation (using Open Office Impress)

Question: So if your code accesses the system, how do you test this code?

Answer: You use Interface-based design and a library that can mock that interface.

Well, it is not exactly simple.

Question: What if you are using some one elses code, such as standard C# libraries in the System or Microsoft namespaces?

Answer: Imagine you need to unit test code that touches the registry. You must do the following steps:

  1. Create an interface for accessing the registry that matches Microsoft.Win32.Registry and Microsoft.Win32.RegistryKey (and you may have to create an interfaces for each object they need as well).
  2. Create a wrapper that wraps the Microsoft.Win32.Registry and Microsoft.Win32.RegistryKey (again, you have to create a wrapper for each objects they need as well).
  3. Change your production code to use the interfaces and the wrappers instead of using the system code.  For example, if dealing with the Registry this involves Microsoft.Win32.Registry and Microsoft.Win32.RegistryKey directly.Don’t use these objects directly, instead you use these objects:
    SystemInterface.Microsoft.Win32.IRegistry
    SystemInterface.Microsoft.Win32.IRegistryKey
    SystemWrapper.Microsoft.Win32.RegistryWrap
    SystemWrapper.Microsoft.Win32.RegistryKeyWrap
  4. Provide a method in your production code for replacing anywhere you use IRegistry or IRegistryKey with any object that implements the interface.
  5. In your Unit Test, mock any neededIRegistry and IRegistryKey objects.

The best solution, long-term, is that Microsoft adds interfaces to the standard .NET libraries and exposes these interfaces so a wrapper isn’t needed. If you agree, vote for this enhancement here: Implement interfaces for your objects so we don’t have use SystemWrapper.codeplex.com

However, since Microsoft hasn’t done this, you have to do it yourself. But all of this probably takes more time than your project will allow you to take, so I am going to try to get you there faster.
Step 1 and Step 2 are done for you, all you have to do is download the dll or source from here:
http://SystemWrapper.codeplex.com
Step 3 and 4 are not done for you but there are examples in the SystemWrapper project.
Step 5 can be done extremely quickly with a free (BSD Licensed) tool called RhinoMocks.
So the new steps become these:

Step 1 – Download SystemWrapper

  1. Go to http://SystemWrapper.codeplex.com and download the latest dll or the latest source.
  2. Copy the SystemInterface.dll and SystemWrapper.dll into your project (perhaps you already have a libs directory).
  3. Add references to these two dlls in your release code.
  4. Add a reference only to SystemInterface.dll in your Unit Test project.

Step 2 – Change your code to use Interfaces and Wrappers

  1. Find any place in your code where it touches the system. For example, if you touch the registry, find any place you call Registry or RegistryKey objects or reference Microsoft.Win32.
    Hint: Use the search feature in your IDE.
  2. Replace the reference with a reference to SystemWrapper and SystemInterfaces. For example, if replacingrRegistry code,
    SystemInterface.Microsoft.Win32
    SystemWrapper.Microsoft.Win32
  3. For any object that touches the system, change that object to be instantiated using the interface. For example, replace RegistryKey objects with IRegistryKey objects.

Step 3 – Allow for replacing the Interface-based objects

Create a property or function that allows you to replace the object you are mocking so you can pass in an object that is mocked.

Here is an example of how to do this when mocking a RegistryKey object using IRegistryKey.

  1. Implement the IAccessTheRegistry interface from the SystemInterface.Microsoft.Win32 namespace. Here is a sample implementation that uses lazy property injection:
            #region IAccessTheRegistry Members
    
            public IRegistryKey BaseKey
            {
                get { return _BaseKey ?? (_BaseKey = new RegistryWrap().LocalMachine); }
                internal set { _BaseKey value; }
            } private IRegistryKey _BaseKey;
    
            #endregion
    

    Notice that the setter is internal. This is because unit tests can usually access an internal method with InternalsVisibleTo. The internal set is hidden for code not in the same assembly and not included in InternalsVisibleTo.

Note: You may want to look into the “Factory” design pattern.

Step 4 – Download and Reference RhinoMocks in your Unit Test

In this step you need to download RhinoMocks and reference it with your Unit Test project. Your release project won’t need it.

  1. Go to http://hibernatingrhinos.com/open-source/rhino-mocks and download RhinoMocks.
  2. Add RhinoMocks.dll

Step 5 – Mock IRegistryKey in your Unit Test

For this, you have to understand and know how to use RhinoMocks and this takes some learning.

Instead of trying to explain this here, let’s go straight into the examples.

Examples

Forthcoming…

  1. Unit Testing Registry access with RhinoMocks and SystemWrapper
  2. Unit Testing File IO with RhinoMocks and SystemWrapper

Return to C# Unit Test Tutorial


Avoiding the MSVCR110.dll or MSVCR110D.dll is missing error

MSVCR110.dll

This MSVCR110.dll is the Microsoft Visual C++ Redistributable dll that is needed for projects built with Visual Studio 2011. The dll letters spell this out.

MS = Microsoft
V = Visual
C = C++
R = Redistributable

If you create a C++ project in Visual Studio 2011, this file is probably needed.

MSVCR110D.dll

The MSVCR110D.dll is almost the same file only the D at the end stands for Debug. This file has debugging enabled.

Why the error?

Ok, so recently I switched to Visual Studio 2011.  I had a C++ application that worked perfectly in Visual Studio 2008.  Once I compiled it with Visual Studio 2011 and ran it on a clean 2008 server (fully patched but otherwise clean), it failed to run with the following error.

TestWin32.exe – System Error

The program can’t start because MSVCR110.dll is missing from your computer. Try reinstalling the program to fix this problem.

Here is the screen shot:

MSVCR110.dll

The same things happens with the debug version of the file, only it is a the debug version of the same DLL as noted by the fact that the DLL name ends with D.

Autorun – System Error

The program can’t start because MSVCR110.dll is missing from your computer. Try reinstalling the program to fix this problem.

The screen shot is identical except for the D in the dll name.

MSVCR110d.dll

I create a new project in Visual Studio 2011 using the project type of C++ Win32 Project and without making a single change to the default project, I built the file and tested it on my clean machine and the same issue occurred.

So obviously that is not acceptable.  It seems like this should just not happen by default, but unfortunately it does.

Solution

It was actually really easy to resolve for my one project.

Here is what I did.

You can solve this any of the following ways:

  1. Statically link to the dll files so they are compiled into my executable instead of referenced as separate dll files.
  2. Included the dll in the same directory as the exe (I actually didn’t try this but I assume it would work).
  3. Forced everyone to install the VC++ Runtime Redistributable before running the app.

The first option seems the most stable and robust and easiest for a single executable. So that is the one I am going to use.

The second option doesn’t really make sense to me and I would probably never do it.  Maybe if I had dozens of executable files that all required the same DLL and I didn’t have an installer, and I wanted to conserve size, which probably wouldn’t happen for me since I am pretty good at creating a quick installer. Though you might be in this a situation.

The third option would make sense if I was planning on running my executable after an install.  During the install I could include the VC++ Runtime Redistributable and all would be fine.

Statically Linking the DLLs

Make sure you resolve it for both Release and Debug.  The steps are slightly different.

Release

  1. In Visual Studio, I went to the project Properties.
  2. I changed my Configuration to Release.
  3. I went under Configuration Properties | C/C++ | Code Generation
  4. Look at the Runtime Library setting.  It is set to this: Multi-threaded DLL (/MD)
    Change it to this: Multi-threaded (/MT)
  5. Rebuild.

Debug

Almost exactly the same as release.

  1. In Visual Studio, I went to the project Properties.
  2. I changed my Configuration to Debug.
  3. I went under Configuration Properties | C/C++ | Code Generation
  4. Look at the Runtime Library setting.  It is set to this: Multi-threaded Debug DLL (/MDd)
    Change it to this: Multi-threaded Debug (/MTd)
  5. Rebuild the debug

It might be a good idea for me to figure out how to change the project so when I create a new project of this type, those settings are the default.


The Step-by-Step RSA Algorithm

Security is important and there is a lot to learn. I am reading the book Security in Computing and trying to memorize the RSA algorithm.

Prerequisite Math Knowledge

You must understand the following mathematical principles to understand this algorithm and if you don’t understand these principles, look them up first (I had to look up the last one, the Euler totient function, as I had never heard of it):

  • Exponentials
  • Prime numbers
  • Prime factorization
  • Greatest Common Denominator (GCD)
  • Modular arithmetic
  • Euler totient function

This is also going to have development in mind, so you maybe should also understand: binary, char, bits, ascii, UTF-8, etc..

The book is good. However, it can be quite annoying for me when it shows algorithms using one character variables. This may be the mathematical way but I prefer to use a developer style where variables are named clearly. I need to make sure I understand how RSA works so I am going to write about it.

Here is an example of how they use just one character:

The RSA algorithm uses two keys, d and e, which work in pairs, for decryption and encryption, respectively. A plaintext message P is encrypted to ciphertext C by

C = Pe mod n

The plaintext is recovered by

P = Cd mod n

Because of symmetry in modular arithmetic, encryption and decryption are mutual inverses and commutative. Therefore,

P = Cd mod n = (Pe)d mod n = (Pd)e mod n

This relationship means that one can apply the encrypting transformation and then the decrypting one, or the one followed by the encrypting one.1

I would never write code this way and looking at this, it might leave one who is not an expert wondering what do the variables P, C, d, e, n represent again? And is there a reason P, C are capitalized and d, e, n are lower case? Lets rewrite these with nice developer variable names where the name comments itself based on the what it really is. In the quoted text above each variable is defined clearly except what “mod n” really represents, I had to read on to determine this. Also, where to get the values for each variable is not defined, again, I had to read on to determine this, and this led to more equations to add to the list.These are the equations, in order

Equation List

  1. ProductOfPrime1Prime2 = Prime1 * Prime2
  2. Totient = (Prime1 – 1) * (Prime2 -1)
  3. (Totient * AnyInteger) + 1 = 1 mod Totient
  4. EncryptPrime * DecryptPrime = 1 mod Totient
  5. EncryptPrime * DecryptPrime = (Totient * AnyInteger) + 1 where (Totient * AnyInteger) + 1 has exactly prime factors
  6. CipherText = PlainTextEncryptPrime mod ProductOfPrime1Prime2
  7. PlainText = CiphertextDecryptPrime mod ProductOfPrime1Prime2
  8. PlainText = CiphertextDecryptPrime mod ProductOfPrime1Prime2 = (PlainTextEncryptPrime)DecryptPrime mod ProductOfPrime1Prime2 = (PlainTextDecryptPrime)EncryptPrime mod n

Some of the values above you get to “choose” or if you were writing this algorithm in code, you would probably not “choose” so much as generate the value at random. So if we get to choose, then lets learn how to choose.

Step 1 – Choose two prime numbers, Prime1 and Prime2 to get the ProductOfPrime1Prime2 variable

So our Equation List above starts out with this simple math equation:

Prime1 * Prime2 = ProductOfPrime1Prime2

Ok, so where do you get Prime1 and Prime2 to start? You simply choose the two primes yourself. Find or generate or a list of primes and choose two. Close your eyes and point or pull them out of a hat. It doesn’t matter just choose two primes numbers.

Of course, there are recommendations for choosing primes in production use. Here are a two basic recommendations:

  1. Prime1 and Prime2 should be very large prime numbers, at minimum 100 digits long but as larger is more secure and less efficient.
  2. Prime 1 and Prime2 should not be the same prime number

Even though Prime1 and Prime2 should be very large, I want to keep this simple, so for example’s sake, let’s use two primes from the list below:

Primes between 0 and 100.

2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97;

So we can choose any primes we want, for this example, I will choose these two: 19, 31

ProductOfPrime1Prime2 = Prime1 * Prime2

ProductOfPrime1Prime2  = 19 * 31 = 589

ProductOfPrime1Prime2  = 589

Step 2 – Find the Totient of ProductOfPrime1Prime2

You can search the internet and to study to figure out how to get the totient, but it is pretty easy to get. Totient uses a weird symbol that looks like the letter ‘p’ but is not:

Totient = φ(ProductOfPrime1Prime2)

φ(ProductOfPrime1Prime2) = (Prime1 -1) * (Prime2 – 1)

So I guess you don’t really need to know about a totient, you can just trust me, right? Ok, mathematicians are big on proofs and not just trusting someone so, go learn totient. Anyway,  the equation is as simple as this:

Totient = (Prime1 -1) * (Prime2 – 1)

So we already chose Prime1 as 19 and Prime2 as 31 in Step 1, so we have this:

Totient = (19 – 1) * (31 – 1) = 18*30 = 540

Totient = 540

Step 3 – Get a list of possible integers that result in 1 mod Totient

So we have our third and fourth equations in the Equation List:

EncryptPrime * DecryptPrime = 1 mod Totient

(Totient * AnyInteger) + 1 = 1 mod Totient

Notice that in both equations, the right sides are the same: 1 mod Totient

We get the fifth equation in our Equation List by simply merging these equations three and four:

EncryptPrime * DecryptPrime = (Totient * AnyInteger) + 1 where (Totient * AnyInteger) + 1 has exactly two prime factors

In step 2 we determined the totient is 540, so we have this:

EncryptPrime * DecryptPrime = 1 mod 540

So here is where you need to understand modular arithmetic. There are many possible values that equal 1 mod 540. It is a series. The series can be created with this function:

(Totient * AnyInteger) + 1 = 1 mod Totient

(540 * AnyInteger) + 1 = 1 mod 540

AnyInteger is just what it sounds like, it is any integer:  1, 2, 3, 4, 5, …, 100, …, ∞

540 * 1 + 1 = 541

540 * 2 + 1 = 1081

540 * 3 + 1 = 1621

540 * 4 + 1 = 2161

540 * 5 + 1 = 2701

540 * 100 + 1 = 54001

Or we make a list of these possible values that equal 1 mod 540 (which as you can see goes on for infinity)

541, 1081, 1621, 2161, 2701, …, 54001, … , ∞

Step 5 – Choose a 1 mod Totient value with exactly two prime factors: EncryptPrime and DecryptPrime

Now that we have a list, we apply the where clause to it:

{ 541, 1081, 1621, 2161, 2701, …, 54001, …, ∞ } where (Totient * AnyInteger) + 1 has exactly two prime factors

Now is when you need to understand Prime Factorization. There are three possibilities for factors and only the second one matches our where clause.

  1. The integer is a prime (has only one factor, itself)
  2. The integer has two prime factors
  3. The integer has more than two prime factors

So let’s get the factors of the integers in our list.

541 = Prime

1081 = 23 × 47

1621 = Prime

2161 = Prime

2701 = 37 × 73

54001 = Prime

So from the short list (and remember the list is infinite, we just selected a few) we have two possible representations of 1 mod Totient.
(We didn’t even see any values with more than two prime factors but don’t worry, with bigger numbers you will find them.)

Here is another place where we get to choose. Once again, close your eyes and point or pull them out of a hat. It doesn’t matter just choose.

Again, there is a recommendation:

  1. For EncryptPrime choose a prime larger than (p – 1) or (q – 1).

For this example, I have chosen 37 × 73 even though they don’t meet the above recommendation, however, I can make either EncryptPrime or DecryptPrime, they are interchangable.

So I will make the bigger value EncryptPrime.

EncryptPrime = 73

DecryptPrime = 37

Step 6 – Encrypt

We now have everything we need to Encrypt and Decrypt.

CipherText = PlainTextEncryptPrime mod ProductOfPrime1Prime2

Lets say we have an ascii character ‘A’ or 65. We already know what all the variables except for the CipherText are.

PlainText = 65

EncryptPrime = 73

ProductOfPrime1Prime2 = 589

So lets put these values into our equation. This can be done with a simple calculator.

CipherText = 6573 mod 589 = 179

CipherText = 179

Step 6 – Decrypt

Now lets decrypt this.

PlainText = CiphertextDecryptPrime mod ProductOfPrime1Prime2

We already know what all the variables are. Normally the PlainText is not known before hand as it is known in this example.

CipherText = 179

DecryptPrime = 37

ProductOfPrime1Prime2 = 589

Lets put these values into our equation and make sure they return ‘A’ or 65.

PlainText = 17937 mod 589 = 65

PlainText = 65

How does this apply to Public/Private key security (your PC to an HTTPS web server)

It is simple. A public and private key are created on the server. When you hit a web server, the web server sends you the public key.

PublicKey contains: EncryptPrime and ProductOfPrime1Prime2

You are never sent the PrivateKey.

PrivateKey = DecryptPrime and ProductOfPrime1Prime2

This works because you cannot derive EncryptPrime from DecryptPrime and ProductOfPrime1Prime2

You encrypt everything you send to the web server with the PublicKey and they encrypt everything they send you with the PrivateKey. You can decrypt what the server sends you, but only the server can decrypt what you send back. So when you type in your Password into a your bank’s web page, your password is sent encrypted so only the server can decrypt it.

1. Pfleeger, Charles P.; Pfleeger, Shari Lawrence (2007-01-23). Security in Computing (4th Edition) (Kindle Locations 19886-19887). Prentice Hall. Kindle Edition.


Android and Xml Serialization with Simple

Xml serialization is almost becoming a standard requirement for a language these days and so as I have been taking an Android class and I couldn’t find an Xml Serialization library as part of Android by default, I set out in search of one.

I came across a java XML Serialization project called Simple.

So here is a quick entry-level example of how to use Simple in an Android development project.

Note: This walk-thru assumes you are using Eclipse.

Step 1 – Create a new Android Project

  1. Go to File | New Project and select Android.
  2. Provide a Project Name.
  3. Select the minimum build target.
  4. Provide a Package name.
  5. Click Finish.

Step 2 – Download Simple

  1. Go to the Simple download page: http://simple.sourceforge.net/download.php
  2. Extract the zip file.

Step 3 – Add the Simple library to your project

  1. Create a folder called libs in your project.
  2. Copy the jar file called simple-xml-2.6.2.jar to the libs directory you just created.Note: Be aware your version may be newer than 2.6.2.
  3. In Eclipse, right-click on simple-xml-2.6.2.jar (if it doesn’t show up refresh) and choose Build Path | Add to Build Path.

Step 4 – Create an Serializeable object

  1. Right-click on your package and choose New | Class.
  2. Provide a class name and click ok.
  3. The following is an example Person class:Person.java
    package org.jaredbarneck.cs6890;
    
    import org.simpleframework.xml.Element;
    import org.simpleframework.xml.Root;
    
    @Root
    public class Person
    {
    
    	public Person()
    	{
    	}
    
    	public Person(String inFirstName, String inLastName)
    	{
    		SetFirstname(inFirstName);
    		SetLastname(inLastName);
    	}
    
    	@Element
    	private String FirstName;
    
    	public String GetFirstName()
    	{
    		return FirstName;
    	}
    
    	public void SetFirstname(String inFirstName)
    	{
    		FirstName = inFirstName;
    	}
    
    	@Element
    	private String LastName;
    
    	public String GetLastName()
    	{
    		return LastName;
    	}
    
    	public void SetLastname(String inLastName)
    	{
    		LastName = inLastName;
    	}
    
    	@Override
    	public boolean equals(Object inObject)
    	{
    		if (inObject instanceof Person)
    		{
    			Person inPerson = (Person)inObject;
    			return this.FirstName.equalsIgnoreCase(inPerson.FirstName)
    				&& this.LastName.equalsIgnoreCase(inPerson.LastName);
    		}
    		return false;
    	}
    }
    

Step 5 – Serialize and Deserialize in your main Activity

  1. Add the following code to your main Activity:Note: Code should be clear and is commented.PersonActivity.java
    package org.jaredbarneck.cs6890;
    
    import java.io.File;
    
    import org.simpleframework.xml.Serializer;
    import org.simpleframework.xml.core.Persister;
    
    import android.app.Activity;
    import android.os.Bundle;
    
    public class PersonActivity extends Activity
    {
    	public void onCreate(Bundle savedInstanceState)
    	{
    		super.onCreate(savedInstanceState);
    		setContentView(R.layout.main);
    
    		// Create a Person object
    		Person person1 = new Person("John", "Johnson");
    
    		// Create a file to save to and make sure to use the path provided from
    		// getFilesDir().getPath().
    		File xmlFile = new File(getFilesDir().getPath() + "/Person.xml");
    
    		// Serialize the Person
    
    		try
    		{
    			Serializer serializer = new Persister();
    			serializer.write(person1, xmlFile);
    		}
    		catch (Exception e)
    		{
    			e.printStackTrace();
    		}
    
    		// Create a second person object
    		Person person2 = null;
    
    		// Deserialize the Person
    		if (xmlFile.exists())
    		{
    			try
    			{
    				Serializer serializer = new Persister();
    				person2 = serializer.read(Person.class, xmlFile);
    			}
    			catch (Exception e)
    			{
    				e.printStackTrace();
    			}
    		}
    
    		boolean b = person1.equals(person2);
    	}
    }
    

Go ahead and try this in your Android emulator and step through it with a debugger.

You have now successfully implemented Xml Serialization in Java on Android using Simple.


Architecting a large application with interface-based architecture

Design and architect and write your software solution so that its different pieces can be independent in the following ways:

  1. Develop Independently
  2. Build Independently
  3. Install Independently
  4. Test Independently
  5. Refactor/Replaced Independently

Don’t just separate the concerns in one way and call it good. Separate your concerns all the ways listed above.

What will this do for your project?

  • It will make it so it can be easily unit tested.
  • It will make it so it can be easily built.
  • It will make it so it can be easily installed.
  • It will make it so it can be easily changed: Patched, Refactored, or Replaced.

Wow, all that sounds great, why doesn’t everyone do this?

Because the one area that is harder is the initial development. You have to design a lot more. You have to code different. It can be hard.

However, it is the easiest way overall, just not the easiest way at the start developing.

How do I separate my code into pieces?

There is a though among many that a software tool should do one thing only, but it should do it really well. When you think of your entire project, that should be kept in mind.

The smallest item in a project is the likely the “object”.

The term object is very abstract. It is like the work “thing” in that it can be anything.

So look at it from a high level view. Imagine your software has four pieces.

Decoupled Architecture

Ok, how do these pieces interact? Can you build each piece without having to link to another piece? You should be able to do this.

However, you have to link to something in someway in order to use its code so what do you link to?

Interfaces.

Ok, so you double the size of your pieces by having a piece and an interface for it. These could be eight separate dlls.

If Piece1 needs Peice2, it should link to IPiece2 and not to Piece2. This allows for Piece2 to be:

  1. Any version of Piece2 that implements the interface.
  2. Refactored without breaking the Piece1 build.
  3. Replaced by a completely different implementation
  4. Mocked for testing (really the same as three but used for Unit tests)

Real life example

In real life, applications are database driven. So what if your Piece2 is a database tool and Peice1, Piece3, and Piece4 all need to access the database using Piece2.

If you link directly to Piece2, you have a problem where you must have a real database in order to test your code in Piece1, Piece3, and Piece4.

This is a huge testing burden. This prevents your tests from running as Unit Tests and instead they must be run as Functional Tests.

However, by designing properly using interfaces, you can get back to Unit Tests for Piece1, Piece3, and Piece4 by mocking Piece2.

You use IPiece2 to create a new block called Mock2, which is just a Mock of Piece2, which can be run during a Unit Test. Now all the other blocks are testable.

Lets look at our Independent Architecture rules and see if this design works.

  • Yes – It will make it so it can be easily unit tested.
  • Yes – It will make it so it can be easily built.
  • Yes – It will make it so it can be easily installed.
  • Yes – It will make it so it can be easily changed: Patched, Refactored, or Replaced.

If you have a large application, this is one design pattern you should look at.

Other Resources


How to make a Makefile?

Most software compiled on BLU (BSD/Linux/Unix) operating systems is done using make.

The simplest Makefile

The simplest Makefile compiles one single executable. Think of your simplest “Hello, World!” project.

HelloWorld.cpp

#include <iostream>
using namespace std;
int main() {
  cout << "Hello, World!";
  return(0);
}

Of course, for one file you don’t need a Makefile. You could simply run this command that will compile hw.cpp

g++ -o HelloWorld HelloWorld.cpp

So even though a Makefile seems useless for a single file, here is how you would do it.

all:
	g++ -o HelloWorld HelloWorld.cpp

Notice that you have a label and the same compile command one line below the label.

Important! The syntax requires the second line to start with a tab.

Adding objects to your Makefile

Lets assume instead of one file, you have the three file HelloWord.

  • Main.cpp
  • HelloWorld.h
  • HelloWord.cpp

Main.cpp

#include <iostream>
#include "HelloWorld.h"

using namespace std;

int main()
{
  HelloWorld hw = HelloWorld();
  cout << hw.Text << endl;
}

HelloWorld.h

#include <iostream>

using namespace std;

class HelloWorld
{
public:
  HelloWorld();
  ~HelloWorld();

  string Text;
};

HelloWorld.cpp

#include "HelloWorld.h"

HelloWorld::HelloWorld()
{
  Text = string("Hello, World!");
}

HelloWorld::~HelloWorld()
{
}

This simple project can also easily be compiled without a Makefile using this command line.

g++ -o HelloWorld Main.cpp HelloWorld.cpp

However, even with only three files you can start to see how it is much easier to type make than the lengthening command above.

Makefile

all:
	g++ -o HelloWorld Main.cpp HelloWorld.cpp

This is not perfect however, as this compiles both files every time make is run. If changes are made only to Main.cpp there is no reason to recompile HelloWorld.cpp. We can accomplish this by compiling HelloWorld.cpp to a HelloWorld.o module.

all: HelloWorld.o
	g++ -o HelloWorld Main.cpp HelloWorld.o

Similarly if you make changes to HelloWorld.h or HelloWorld.cpp, why do you need to recompile Main.cpp? So you can make it a module too.

all: Main.o HelloWorld.o
	g++ -o HelloWorld Main.o HelloWorld.o

Now only the libraries that have been modified will be recompiled when you run make. This can save significant build time when the project size increases.

Using variables in your Makefile

Mistakes are annoying.  Having to type the same thing in multiple places often leads to mistakes and typos. If you look at the above, there is duplication that is unnecessary.

Makefile with duplication

all: Main.o HelloWorld.o
	g++ -o HelloWorld Main.o HelloWorld.o

Makefile using a variable to avoid duplication

objs = Main.o HelloWorld.o
all: ${objs}
	g++ -o HelloWorld ${objs}

We can even add more variables which may not seem useful now, but are useful later.

CXX = g++
CXXFLAGS =
objs = Main.o HelloWorld.o
Outfile = HelloWorld

all: ${objs}
	${CXX} ${CXXFLAGS} -o ${Outfile} ${objs}

Think about it. Right now you only have one build command, but someday on a huge project you may have dozens and possibly hundreds. Could you imaging changing the CXXFLAGS everywhere? We don’t even have one listed yet, but of course, with the variable you only have to change it once in one place and it will work everywhere you used it.

Adding make clean to your Makefile

It is very common to want to delete all build files and build again. This is often done with the make clean command. But to get make clean to work you have to create a section or label in the make file called clean.

Because we already have variables, it is easy to configure the Makefile to support make clean.

Makefile with clean

CC = g++
CXXFLAGS = -W
objs = Main.o HelloWorld.o
Outfile = HelloWorld

all: ${objs}
	${CC} ${CXXFLAGS} -o ${Outfile} ${objs}

clean:
	rm ${objs} ${outfile}

So simple, we just use rm to delete the files we created, which are all in variables so we had a nice clean short command.

Adding debugging to your make file

There are two schools of thought for debugging.

  • All builds should be release builds unless you run make debug.
  • All builds should be debug builds unless you run make release.

I am not going to tell you which school of thought you should have.  What matters is that you can configure the Makefile to perform how you want it to.

This make file will always build without debugging (release) unless yous specify make debug.

CXX = g++
CXXFlags = -W
objs = Main.o HelloWorld.o
Outfile = HelloWorld

all: objects build

objects: ${objs}

debug: clean
CXXFLAGS += -g
LDFLAGS += -g

debug: objects build

build:
	${CXX} ${CXXFLAGS} -o ${Outfile} ${objs}

clean:
	rm -f ${objs} ${Outfile}

Notice we set LDFLAGS but we never actually call it. It is a special variable that is called automatically by the linker when creating the objects. Yes it must be capitalized.


How to create an Android menu?

Ok, so adding a menu that pops up from the bottom when the menu button is clicked is very common and quite easy to do.

Note: This assumes you have the Android SDK, Emulator, and Eclipse all working already.

Step 1 – Create your Android project

  1. In Eclipse, select File | New Project | Android | Android Project.
  2. Give your project a Name.
    I named this project “HelloAll”.
  3. Select the Build Target (the minimum version of Android).
    I selected Android 2.2.
  4. Enter a Package name.
    Package name is like a namespace, it can be anything you want, but you should actually choose a name as carefully as you choose and the name of an object.  I named the package this: org.rhyous.
  5. Click Finish.

Your project is now created.

Step 2 – Add an XML file for the menu

  1. Expand the res directory in your project.
  2. Right-click on the layout folder and choose New | Other.
  3. Choose XML | XML file and click Next.
  4. Name the file.
    I named my file menu.xml.
  5. Click Finish.
  6. Add the following text into your menu:
    <menu xmlns:android="http://schemas.android.com/apk/res/android">
        id="@+id/menu_item_1" android:title="@string/menu_1"/>
        id="@+id/menu_item_2" android:title="@string/menu_2"/>
        <item android:id="@+id/menu_item_3" android:title="@string/menu_3"/>
    </menu>
    

Step 3 – Add the strings for the menu items

  1. Expand the res\values directory in your project.
  2. Open the strings.xml.
  3. Add strings for each menu item.
    Make sure you use the same id strings you used in the menu.xml for the title of each menu item.
    Your strings.xml should now look like this:

    <?xml version="1.0" encoding="utf-8"?>
    <resources>
        <string name="hello">Hello World, HelloAllActivity!</string>
        <string name="app_name">HelloAll</string>
        <string name="menu_1">Menu 1</string>
        <string name="menu_2">Menu 2</string>
        <string name="menu_3">Menu 3</string>
    </resources>
    

You now have a menu and strings for each menu item.

Step 4 – Overload onCreateOptionsMenu

  1. Open your Activity.
    Mine is src\org.rhyous\HelloAllActivity.java.
    It should look like this:

    package org.rhyous;
    
    import android.app.Activity;
    import android.os.Bundle;
    
    public class HelloAllActivity extends Activity {
    	/** Called when the activity is first created. */
    	@Override
    	public void onCreate(Bundle inSavedInstanceState) {
    		super.onCreate(inSavedInstanceState);
    		setContentView(R.layout.main);
    	}
    }
    
  2. Add code to override onCreateOptionsMenu and add code to inflate the menu.
    	@Override
    	public boolean onCreateOptionsMenu(Menu inMenu) {
    		super.onCreateOptionsMenu(inMenu);
    		getMenuInflater().inflate(R.layout.menu, inMenu);
    		return true;
    	}
    

You can now build your application and test that the menu pops up. However, the menu doesn’t do anything yet.

Step 5 – Overload onCreateOptionsMenu

  1. Add code to override onOptionsItemSelected and add code to inflate the menu.
  2. Use a switch statement with the inItem.getItemId() function to perform the appropriate action for each menu item.
    	@Override
    	public boolean onOptionsItemSelected(MenuItem inItem) {
    		switch (inItem.getItemId()) {
    		case R.id.menu_item_1:
    			// Do something here
    			return true;
    		case R.id.menu_item_2:
    			// Do something here
    			return true;
    		default:
    			// Should never get here
    			return false;
    		}
    

Based on the item clicked, the appropriate code will run.

Hope you enjoyed this simple Android development example.


Ghost 2.5 Beta 2 available – Ghost is a BSD distribution based on GNOME

Ghost 2.5 is a BSD desktop distribution based on FreeBSD. This version is keeping up with the latest FreeBSD 9 release. This is both a live distribution as well as an installer for FreeBSD 9.

It is exciting for a lot of BSD users who didn’t really have an out-of-the-box GNOME option on FreeBSD to have a distribution where GNOME is the focus.

The DVD ISO in 64 bit is only 1.3 GB, though there is a “lite” version that is on a single CD.

It is nice that they are using pcsysintall for their installer, though they are in early stages as the installer is a text installer and not for an Ubuntu user yet. 😉

If you are excited about this project go ahead and give them a donation. I just tossed them $5. http://ghostbsd.org/donate/


Prime Factors calculator in C++

Hey all, I wrote a C++ object that gets the prime factors of any number and thought I would share it.

The comments should help you and the variables have very clear names, so it should be self-documenting.

PrimeFactorsOfCalculator.h

#pragma once

#include <vector>

using namespace std;

class PrimeFactorsOfCalculator
{
public:
	PrimeFactorsOfCalculator(void);
	~PrimeFactorsOfCalculator(void);

	long GetNumber();
	void SetNumber(long inNumber);
	vector<int> GetPrimeFactors(bool inAllowDuplicates = false, bool inForceRecalculate = false);


private:
	long Number;
	vector<int> PrimeFactors;
	bool IsPrime(long inNumber);

	long MultiplyPrimes();

};

PrimeFactorsOfCalculator.cpp

#include "PrimeFactorsOfCalculator.h"
#include <math.h>
#include <algorithm>

using namespace std;

PrimeFactorsOfCalculator::PrimeFactorsOfCalculator(void)
{
}


PrimeFactorsOfCalculator::~PrimeFactorsOfCalculator(void)
{
}

long PrimeFactorsOfCalculator::GetNumber()
{
	return Number;
}

void PrimeFactorsOfCalculator::SetNumber(long inNumber)
{
	Number = inNumber;
	PrimeFactors.clear();
}

//
// Gets the prime factors of Number. 100 return 2,5.
//	
// inAllowDuplicates - Allow duplicates, for example, 100 has prime 
// factors of 2 and 5,but in order to get 100, you need 2*2*5*5. So 
// instead of returning 2,5 the return array will be 2,2,5,5.
//
// inForceRecalculate - By default the values are stored at first
// calculation and only recalcuated when needed. this is for efficiency.
vector<int> PrimeFactorsOfCalculator::GetPrimeFactors(bool inAllowDuplicates, bool inForceRecalculate)
{
	// Don't recalculate if already calculated.
	if (PrimeFactors.size() > 0 && !inForceRecalculate)
		return PrimeFactors;

	PrimeFactors.clear();
	// Calculate
	if (Number % 2 == 0 && Number >= 2)
	{
		PrimeFactors.push_back(2);
	} 

	for (int i = 3; i < Number/3; i++)
	{
		if (Number % i == 0 && IsPrime(i))
			PrimeFactors.push_back(i);
	}

	// Allow duplicates, for example, 100 has prime factors of 2 and 5,
	// but in order to get 100, you need 2*2*5*5. So instead of returning
	// 2,5 the return array will be 2,2,5,5.
	if (inAllowDuplicates)
	{
		while (MultiplyPrimes() != Number)
		{
			long multipliedVal = MultiplyPrimes();
			long val = 0;

			if (multipliedVal != 0)
				val = Number / multipliedVal;

			if (IsPrime(val))
			{
				PrimeFactors.push_back(val);
				continue;
			}
			else
			{
				// recursion
				PrimeFactorsOfCalculator calc = PrimeFactorsOfCalculator();
				calc.SetNumber(val);
				vector<int> duplicateFactors = calc.GetPrimeFactors();
				for (size_t i = 0; i < duplicateFactors.size(); i++)
				{
					PrimeFactors.push_back(duplicateFactors.at(i));
				}
			}
		}
	}

	sort(PrimeFactors.begin(), PrimeFactors.end());
	return PrimeFactors;
}

bool PrimeFactorsOfCalculator::IsPrime(long inNumber)
{
	// Get square root as that is the highest possible factor
	// and add one in case precision is screwy.
	long highestPossibleFactor = (long)(sqrt((double)inNumber) + 1);

	// Handle 2 separatly then no other even has to be checked
	if (inNumber % 2 == 0) 
		return false;

	// See if the value is divisible by any odd number
	// if so it is not prime
	for (int i = 3; i < highestPossibleFactor; i+=2)
	{
		if (inNumber % i == 0) 
			return false;
	}
	return true;
}

long PrimeFactorsOfCalculator::MultiplyPrimes()
{
	if (PrimeFactors.size() == 1)
		return PrimeFactors.at(0);
	else if (PrimeFactors.size() > 1)
	{
		int minVal = PrimeFactors.at(0);
		for (size_t i = 1; i < PrimeFactors.size(); i++)
		{
			minVal *= PrimeFactors.at(i);
		}
		return minVal;
	}
	else return 1; // 1 is always a prime
}

And last here is a sample main function that uses this.

Main.cpp

#include <vector>
#include "PrimeFactorsOfCalculator.h"

using namespace std;

int main()
{
	PrimeFactorsOfCalculator calc = PrimeFactorsOfCalculator();
	calc.SetNumber(100);
	vector<int> primeFactors = calc.GetPrimeFactors();
	vector<int> primeFactorsWithDuplicates = calc.GetPrimeFactors(true, true);


	calc.SetNumber(200);
	primeFactors = calc.GetPrimeFactors();
	primeFactorsWithDuplicates = calc.GetPrimeFactors(true, true);


	calc.SetNumber(1000);
	primeFactors = calc.GetPrimeFactors();
	primeFactorsWithDuplicates = calc.GetPrimeFactors(true, true);

	calc.SetNumber(14593);
	primeFactors = calc.GetPrimeFactors();
	primeFactorsWithDuplicates = calc.GetPrimeFactors(true, true);

	calc.SetNumber(12345678);
	primeFactors = calc.GetPrimeFactors();
	primeFactorsWithDuplicates = calc.GetPrimeFactors(true, true);
}

What is a Unit Test?

Unit Testing is the idea of writing additional code, called test code, for the purpose of testing the smallest blocks of production code to the full extent possible to make sure those blocks of code are error free.

Code is usually designed into Classes or Objects. The term “Class” and the term “Object” are usually used interchangeably. Classes are made up of variables and functions that include Constructors, Methods, and Properties but they may also include sub-classes.

For each Object in code, you should have a Unit Test for that object. For each method in an Object, the correlating Unit Test should have a test. In fact, a test should exist that makes sure that every line of your code functions as expected.

Code Coverage

Unit Tests are about making sure each line of code functions properly. A Unit Test will execute lines of codes. Imagine you have 100 lines of code and a Unit Test tests only 50 lines of code. You only have 50% code coverage. The other 50% of you code is untested.

Most Unit Test tools, MSTest, MBUnit, NUnit, and others can provide reports on code coverage.

Cyclomatic Complexity

Cyclomatic Complexity is a measurement of how complex your code is. This usually comes up in Unit Testing because in order to get 100% code coverage, one has to tests every possible path of code. The more your code branches, the more complex the code is.

If you have to write twenty tests just to get 100% coverage for a single function, you can bet your cyclomatic complexity is too high and you should probably break the function up or reconsider the design.

Parameter Value Coverage

Parameter Value Coverage is the idea of checking both expected and unexpected values for a given type. Often bugs occur because testing is not done on an a type that occurs unexpectedly at run time. Often a value is unexpectedly null and null was not handled, causing the infamous null reference exception.

Look at this function. Can you see the bug?

public bool CompareStrings(String inStr1, String inStr2)
{
    return inStr1.Equals(inStr2);
}

A System.NullReferenceExecption will occur if inStr1 is null.

How can we find these bugs before a customer reports them? A unit test can catch these bugs. We can make lists of anything we can think of that might react differently.

For example, imagine a function that takes a string. What should we try to test:

  1. An actual string: “SomeText”;
  2. An uninitialized string: null;
  3. A blank string: “”
  4. A string with only whitespace: ”   “;

Now imaging a function takes an object called PersonName that has a string member for FirstName and LastName value. We should try to test some of the above.

  1. A PersonObject but nothing populated: new PersonName();
  2. A PersonObject but everything populated: new PersonName() {FirstName=”John”, LastName=”Johnson”};
  3. A PersonObject but partially populated: new PersonName() {LastName=”Johnson”} || new PersonName() {FirstName=”John”};
  4. An uninitialized PersonName object: null;

Here is a test that will check for null in the compare strings code.

Note: There is a decision to make here. If comparing two string objects and both are null, do you want to return true, because both are null so they match? Or do you want to return false, because neither are even strings? For the code below, I’ll assume two null strings should not be considered equal.

public bool CompareStrings_Test()
{
    String test1 = null;
    String test2 = null;
    bool expected = false;
    bool actual = CompareStrings(test1, test2);
    Assert.AreEqual(expected, actual);
}

Now your unit test is going to encounter a System.NullReferenceExecption. Assuming you write Unit Tests before you release your code to a customer, you will catch the bug long before the code reaches a customer and fix it.

Here is the fixed function.

public bool CompareStrings(String inStr1, String inStr2)
{
    // If either input values are null, return false
    if (null == inStr1 || null == inStr2)
        return false;
    return inStr1.Equals(inStr2);
}

Unit Test Example

Here is an example object called PersonName. We tried to make it have a little more meat to this object than just a FirstName, LastName password.

PersonName.cs

using System;
using System.Collections.Generic;
using System.Text;

namespace PersonExample
{
    ///<summary>
    /// An Ojbect representing a Person
    /// </summary>
    public class PersonName : IPersonName
    {
        #region Constructor
        public PersonName()
        {
        }
        #endregion

        #region Properties
        /// <summary>
        /// The persons first name.
        /// </summary>
        public String FirstName { get; set; }

        /// <summary>
        /// The persons Middle Name(s). Some people have multiple middle names.
        /// So as many middle names as desired can be added.
        /// </summary>
        public List MiddleNames
        {
            get
            {
                if (null == _MiddleNames)

                    _MiddleNames = new List();
                return _MiddleNames;
            }
            set { _MiddleNames = value; }
        } private List _MiddleNames;

        public String LastName { get; set; }
        #endregion

        #region Methods
        /// <summary>
        /// Converts the name to a string.
        /// </summary>
        public override string ToString()
        {
            return ToString(NameOrder.LastNameCommaFirstName);
        }

        ///<summary>
        /// Converts the name to a string.
        /// </summary>
        ///
        ///
        private String ToString(NameOrder inOrder)
        {
            switch (inOrder)
            {
                case NameOrder.LastNameCommaFirstName:
                    return LastName + ", " + FirstName;

                case NameOrder.LastNameCommaFirstNameWithMiddleNames:
                    return LastName + ", " + FirstName + " " + MiddleNamesToString();

                case NameOrder.FirstNameSpaceLastname:
                    return FirstName + " " + LastName;

                case NameOrder.FirstNameMiddleNamesLastname:
                    return FirstName + MiddleNamesToString() + LastName;

                default:
                    return LastName + ", " + FirstName;
            }
        }

        /// <summary>
        /// Converts the list of middle names to a single string.
        /// </summary>
        /// String
        private String MiddleNamesToString()
        {
            StringBuilder builder = new StringBuilder();

            bool firstTimeThrough = true;
            foreach (var name in MiddleNames)
            {
                if (firstTimeThrough)
                    firstTimeThrough = false;
                else
                    builder.Append(" ");
                builder.Append(name);
            }
            return builder.ToString();
        }

        /// <summary>
        /// Compares the object passed in to see if it is a Person.
        /// </summary>
        ///
        /// True if FirstName and LastName and MiddleNames match, False if the object
        /// is not a Person or FirstName and LastName and MiddleNames do not match
        public override bool Equals(object inObject)
        {
            PersonName p = inObject as PersonName;
            if (null == p)
                return false;
            else
                return Equals(p);
        }

        /// <summary>
        /// Compares one PersonName to another PersonName.
        /// </summary>
        public bool Equals(IPersonName inPersonName)
        {
            return inPersonName.FirstName.Equals(FirstName, StringComparison.CurrentCultureIgnoreCase)
                && inPersonName.LastName.Equals(LastName, StringComparison.CurrentCultureIgnoreCase);
        }

        /// <summary>
        /// Compares a string to see if it matches a person.
        /// </summary>
        public bool Equals(String inString)
        {
            string tmpLastNameCommaFirstName = ToString(NameOrder.LastNameCommaFirstName);
            string tmpLastNameCommaFirstNameWithMiddleNames = ToString(NameOrder.LastNameCommaFirstNameWithMiddleNames);
            string tmpFirstNameSpaceLastname = ToString(NameOrder.FirstNameSpaceLastname);
            string FirstNameMiddleNamesLastname = ToString(NameOrder.FirstNameMiddleNamesLastname);

            return tmpLastNameCommaFirstName.Equals(inString, StringComparison.CurrentCultureIgnoreCase)
                || tmpLastNameCommaFirstNameWithMiddleNames.Equals(inString, StringComparison.CurrentCultureIgnoreCase)
                || tmpFirstNameSpaceLastname.Equals(inString, StringComparison.CurrentCultureIgnoreCase)
                || FirstNameMiddleNamesLastname.Equals(inString, StringComparison.CurrentCultureIgnoreCase);
        }

        ///
        public override int GetHashCode()
        {
            return base.GetHashCode();
        }
        #endregion

        #region Enums
        /// <summary>
        /// The order of the names when converted to a string.
        /// </summary>
        public enum NameOrder
        {
            LastNameCommaFirstName = 0,
            LastNameCommaFirstNameWithMiddleNames,
            FirstNameSpaceLastname,
            FirstNameMiddleNamesLastname
        }
        #endregion
    }
}

Ok, so in a separate test project, the following corresponding test class can be created.

PersonNameTest.cs

using Microsoft.VisualStudio.TestTools.UnitTesting;
using PersonExample;

namespace PersonExample_Test
{
    /// <summary>
    ///This is a test class for PersonNameTest and is intended
    ///to contain all PersonNameTest Unit Tests
    ///</summary>
    [TestClass()]
    public class PersonNameTest
    {
        #region PersonName()
        /// <summary>
        ///A test for PersonName Constructor
        ///</summary>
        [TestMethod()]
        public void PersonName_ConstructorTest()
        {
            PersonName person = new PersonName();
            Assert.IsNotNull(person);
            Assert.IsInstanceOfType(person, typeof(PersonName));
            Assert.IsNull(person.FirstName);
            Assert.IsNull(person.LastName);
            Assert.IsNotNull(person.MiddleNames);
        }
        #endregion

        #region Equals(Object inObject)
        /// <summary>
        ///A test for Equals(Object inObject) with matching first and last names
        ///</summary>
        [TestMethod()]
        public void Equals_Obj_Test_Matching_First_Last_Names()
        {
            PersonName target = new PersonName() { FirstName = "John", LastName = "Johnson" };
            object inObject = new PersonName() { FirstName = "John", LastName = "Johnson" };
            bool expected = true;
            bool actual = target.Equals(inObject);
            Assert.AreEqual(expected, actual);
        }

        /// <summary>
        ///A test for Equals(Object inObject) with different last name
        ///</summary>
        [TestMethod()]
        public void Equals_Obj_Test_Matching_Different_Last_Names()
        {
            PersonName target = new PersonName() { FirstName = "John", LastName = "Johnson" };
            object inObject = new PersonName() { FirstName = "John", LastName = "Jameson" };
            bool expected = false;
            bool actual = target.Equals(inObject);
            Assert.AreEqual(expected, actual);
        }

        /// <summary>
        ///A test for Equals(Object inObject) with different first name
        ///</summary>
        [TestMethod()]
        public void Equals_Obj_Test_Matching_Different_First_Names()
        {
            PersonName target = new PersonName() { FirstName = "John", LastName = "Johnson" };
            object inObject = new PersonName() { FirstName = "James", LastName = "Johnson" };
            bool expected = false;
            bool actual = target.Equals(inObject);
            Assert.AreEqual(expected, actual);
        }

        /// <summary>
        ///A test for Equals(Object inObject) when a null is passed in.
        ///</summary>
        [TestMethod()]
        public void Equals_Obj_Test_Null()
        {
            PersonName target = new PersonName();
            object inObject = null;
            bool expected = false;
            bool actual;
            actual = target.Equals(inObject);
            Assert.AreEqual(expected, actual);
        }
        #endregion

        #region Equals(String inString)
        /// <summary>
        ///A test for Equals(String inString) where inString is null
        ///</summary>
        [TestMethod()]
        public void Equals_String_Test_null()
        {
            PersonName target = new PersonName() { FirstName = "Tom", LastName = "Tomison" };
            string inString = null;
            bool expected = false;
            bool actual;
            actual = target.Equals(inString);
            Assert.AreEqual(expected, actual);
        }

        /// <summary>
        ///A test for Equals(String inString) where inString is a match using
        ///PersonName.NameOrder.FirstNameSpaceLastname
        ///</summary>
        [TestMethod()]
        public void Equals_String_Test_FirstNameSpaceLastname_Match()
        {
            PersonName target = new PersonName() { FirstName = "Tom", LastName = "Tomison" };
            string inString = "Tom Tomison";
            bool expected = true;
            bool actual;
            actual = target.Equals(inString);
            Assert.AreEqual(expected, actual);
        }

        /// <summary>
        ///A test for Equals(String inString) where inString is a match using
        ///PersonName.NameOrder.LastNameCommaFirstName
        ///</summary>
        [TestMethod()]
        public void Equals_String_Test_LastNameCommaFirstName_Match()
        {
            PersonName target = new PersonName() { FirstName = "Tom", LastName = "Tomison" };
            string inString = "Tomison, Tom";
            bool expected = true;
            bool actual;
            actual = target.Equals(inString);
            Assert.AreEqual(expected, actual);
        }
        #endregion

        // TODO: Finish testing this object

    }
}

For more learning, answer the following questions:

  1. What functions are Unit Tested?
  2. What is the code coverage of this Unit Test? (What percent of the Code is Unit Tested?)
  3. You have an enum with twenty items in it. One function has a switch on the enum with all twenty possibilities. The cyclomatic complexity appears to be high and is causing a red flag? Should you change your code? Why or Why not?
  4. Assume you finish the unit test so that the code is 100% covered. What reasons exist for needing still more tests on that code?

Return to C# Unit Test Tutorial


Listing available Properties of an DirectoryEntry object

If you are messing with IIS in C# code, you can do quite a bit if you System.DirectoryServices and the DirectoryEntry object. This can be extended if you know the name of the items in a the DirectoryEntry’s property collection. You can get these as follows:

using System;
using System.Collections.Generic;
using System.DirectoryServices;

namespace FindIISLogWithCSharp
{
    class Program
    {
        static void Main(string[] args)
        {
            List<string> AvailableProperties = new List<string>();
            DirectoryEntry folderRoot = new DirectoryEntry("IIS://localhost/W3SVC");
            PropertyCollection pc = folderRoot.Properties;
            foreach (PropertyValueCollection p in pc)
            {
                AvailableProperties.Add(p.PropertyName);                
            }
            
            // Sort alphabetically
            AvailableProperties.Sort();                       
            foreach (String prop in AvailableProperties)
            {
                Console.WriteLine(prop);
            }
        }
    }
}

Of course, different DirectoryEntry objects can have different lists. However, this exact one created the following list on a Windows 2008 R2 64-bit Server with IIS installed and configured.

AccessFlags
AccessSSLFlags
AnonymousUserName
ApplicationDependencies
AppPoolId
AspDiskTemplateCacheDirectory
AuthFlags
DefaultDoc
DirBrowseFlags
DontLog
HttpCustomHeaders
HttpErrors
IIs5IsolationModeEnabled
KeyType
LogFileDirectory
LogPluginClsid
NTAuthenticationProviders
RedirectHeaders
ScriptMaps
SSIExecDisable
SslUseDsMapper
TraceUriPrefix
WebSvcExtRestrictionList


Java version of the sequential sum algorithm or n(n+1)/2

My first Android homework was to write a little program that would add sequential numbers such as 1 to 100. I call it a Sequential Sum, but I couldn’t find the exact mathematical name.

You can read more about this mathematical task here: Techniques for adding the numbers 1 to 100

In code, you could of course loop through 1 through 100 and += them into a value but there is a more efficient way and most everyone in my class mentioned that is what they did, so I guess I was unique in choosing this solution.

Or you could use the following equation that provides you the answer to get the sum of all numbers between 1 and the end value, n.

n(n+1)/2

Now what if you aren’t starting at 1? What if you want to add the numbers between 50 and 150? Well, this is easy. The last number before the start value of 50 is 49 or 50 – 1 = 49. We can get the value of 1 to 49 and subtract it from the value of 1 to 150.

n(n+1)/2 – s(s+1)/2

While this is for Android, it is basically just java and there is nothing Android specific here. Here is my class.

package org.jaredbarneck.cs6890;

import java.security.InvalidParameterException;

/**
 * @author Jared
 *
 */
public class SequentialSum {

	// Member variables
	private int _LowValue = 0;
	private int _HighValue = 0;

	// Constructors
	public SequentialSum(int inLowValue, int inHighValue) {
		SetHighValue(inHighValue);
		SetLowValue(inLowValue);
	}

	// Getters and Setters
	public int GetLowValue() {
		return _LowValue;
	}

	public int GetHighValue() {
		return _HighValue;
	}

	public void SetLowValue(int inValue) {
		if (inValue < 0)
			throw new InvalidParameterException(
					"Value must be greater than zero!");
		if (inValue > _HighValue)
			throw new InvalidParameterException(
					"High value must be lower than the high value!");

		_LowValue = inValue;
	}

	public void SetHighValue(int inValue) {
		if (inValue < 0)
			throw new InvalidParameterException(
					"Value must be greater than zero!");
		if (inValue < _LowValue)
			throw new InvalidParameterException(
					"High value must be greater than the low value!");

		_HighValue = inValue;
	}

	// Methods
	public int Sum() {

		int sumToSubtract = 0;
		if (_LowValue > 1) {
			int tmpVal = _LowValue - 1;
			sumToSubtract = tmpVal * (tmpVal + 1) / 2;
		}

		return (_HighValue * (_HighValue + 1) / 2) - sumToSubtract;
	}
}

So if I ever need to get the sum of all values between a sequential list of numbers, I can come back and use this class again.

Note: No, I don’t follow java syntax rules and no, I don’t plan too either. I don’t start anything with lower case that is not a local variable. My member variables start with an underscore _ and then an uppercase letter. Everything else starts with upper case. I don’t conform my style to a specific language’s style, instead I try to use the same style in all languages.