Archive for the ‘Agile’ Category.

Custom Nant Task

When using Nant there is not much you can say is lacking. Sometimes you find yourself wondering why you are cutting and pasting good amount of code between different scripts. There has to be a better way of reusing code and sure enough there is. Just write your own Nant extension and it’s pretty simple, let’s take a look.

First create a class that extends the nant Task then declare the name of the task and setup the properties you want available to the user. Lastly you will have ExecuteTask procedure that will be called by Nant when your Task executes. That’s all the magic !

[TaskName(“setVersionAssembly”)]
    public class CxSetVersionAssembly : NAnt.Core.Task
    {
        [TaskAttribute(“file”, Required = true)]
        [StringValidator(AllowEmpty = false)]
        public string file
        {
            get { return msAssemblyFile; }
            set { msAssemblyFile = value; }
        }

        [TaskAttribute(“buildNumber”, Required = true)]
        [StringValidator(AllowEmpty = false)]
        public string buildNumber
        {
            get { return msBuildNumber; }
            set { msBuildNumber = value; }
        }

        // Executes the nant task
        protected override void ExecuteTask()
        {
            // Don’t catch errors, it will display in the build log if any
            Project.Log(Level.Info, “start setVersionAssembly”);
            ChangeAssemblyVersionNumber(msBuildNumber, msAssemblyFile);
        }
}

When you use it in your Nant script you will have to load your assembly first. Once your assembly has been loaded you can start using your custom Task.

<loadtasks assembly=“bin\debug\DE.Nant.Extensions.dll”/>

    <setVersionAssembly
         file=“${tempFile}”
         buildNumber=“3.333.3.3000”
    />

This is a very brief and simple example, there are bunch of properties and other goodies you can use as you build out your custom Nant Tasks.

The Custom Nant Task I wrote is used to update the version of our .net assemblies during build. Attached is the complete code including Nant script and unittests. Get the code

Code coverage from Nant script using Gallio and nCover

I decided to go with MbUnit for a new project, the newest version 3.x comes bundled with Gallio. Gallio is a test runner and can run loads of different flavors of tests. nUnit, msTest, MbUnit, etc. Of course once you have your tests running you wonder how much of your code gets coverage. To figure that one out I added NCover, here is a sample of how you can have nCover cover your Gallio UnitTest runs.

For best results install Gallio on the build machine and point to that directory when you load the task
loadtasks assembly=
also make sure your list of assemblies to be covered is just the assembly name, not the file name.
assembly.list=myAssembly1;myAssembly1;etc

<!– Gallio –>
<target name=“galliounittest”
              description=“Runs MbUnit UnitTests using Gallio.” >

<echo message=“*** Start Gallio unittest: “/>

<!– Run tests –>
<loadtasks assembly=“${path.gallio.task}Gallio.NAntTasks.dll” />

<gallio
  result-property=“exitCode”
  failonerror=“false”
  runner-type=“NCover”
  report-types=“Html;Xml”
  report-directory=“${artifacts}”
  report-name-format=“gallioresults”
  show-reports=“false”
  application-base-directory=“${path.base.test}”
  >

  <runner-property value=“NCoverArguments=’//w ${path.base.test} //a ${assembly.list}'” />
  <runner-property value=“NCoverCoverageFile=’${path.ncover.dir}${coverage.xml.file}'” />
  <!– Specify the tests assemblies  –>
  <files>
    <include name=“${path.base.test}${assembly.test}”/>
  </files>
</gallio>
<fail if=“${exitCode != ‘0’}” >One or more tests failed. Please check the log for more details</fail>

<echo message=“*** End Gallio unittest: “/>
</target>

<!– NCover –>
<target name=“nCoverReport”
              description=“Creates UnitTest Coverage report.” >

<echo message=“*** Start nCoverReport: “/>

    <ncoverexplorer
      program=“${path.ncover.explorer.exe}”
      projectName=“${PojectName}”
      reportType=“ModuleClassFunctionSummary”
      outputDir=“${path.ncover.dir}”
      xmlReportName=“${coverage.xml.file}”
      htmlReportName=“${coverage.html.file}”
      showExcluded=“false”
      verbose=“True”
      satisfactoryCoverage=“1”
      failCombinedMinimum=“true”
      minimumCoverage=“0.0”>

      <fileset>
        <include name=“${path.ncover.dir}${coverage.xml.file}” />
      </fileset>
      <exclusions>
        <exclusion type=“Assembly” pattern=“*.Tests” />
        <exclusion type=“Namespace” pattern=“*.Tests*” />
      </exclusions>
    </ncoverexplorer>

<echo message=“*** End nCoverReport: “/>
</target>

NCover error

I ran into a problem when adding NCover to our UnitTests on a new project the error I got when using NCover with Gallio was the following, Profiled process terminated. Profiler connection not established. The FAQ that is in the NCover directory bundled with Gallio suggested – If using the command-line, did you COM register CoverLib.dll ?

Sure enough, just run
>regsvr32 CoverLib.dll
from a command prompt, that fixed the problem on both our build machines.

Nant, Tf Unable to determine the workspace

I was using Nant to checkout files in a build script and got the error “Unable to determine the workspace” from Team Foundation Server repository. The trick is to reset the cache first, run this command
tf workspaces /s:http://yourserver.com:8080 /noprompt
from your Nant script before doing any checkouts etc, then it should work.

C# download web page

I’m sure you had the need sometime to download the content of a web page to be able to analyze it or work with the content. Here is a code snippet just for you, we will use simple http GET for the specified URL.

public static string getWebPage(string psUrl)
{
    WebResponse result = null;
    string sRet = string.Empty;

    try
    {
        WebRequest req = WebRequest.Create(psUrl);
        req.Method = “GET”;
        req.Timeout = 3 * 1000// 3 secs
        // Explicit no caching, usually this is the default
        req.CachePolicy = new RequestCachePolicy(RequestCacheLevel.BypassCache);

        // Has to process the results if the responding service is spitting it out
        result = req.GetResponse();
        Stream ReceiveStream = result.GetResponseStream();
        Encoding encode = System.Text.Encoding.GetEncoding(“utf-8”);
        StreamReader sr = new StreamReader(ReceiveStream, encode);
        // in case the caller is interested
        sRet = sr.ReadToEnd();
    }
    finally
    {
        if (result != null) result.Close();
    }

    return sRet;
}

UnitTesting a door

I was explaining to somebody from non development world some time back what unittesting is about. At the time the best thing I could come up with was something along the way. Well if your building a house and then you install a door. Now you have to make sure the door works. In case of the door we write Unittest that makes sure that the door nob turns and does actually open the door. We also make sure that the door latches when it’s shut, further we make sure that the door fully opens and closes without any trouble. We make sure the key fits and can lock and unlock the door. Since we are at it we might as well shake the door and make sure nothing is rattling, that all screws were tightened up properly. Further if the door gets replaced it has to be verified that it works as well and the same key can be used as before.

The good part is once you have written the unittest it will work for the replacement door as well. This is where you get the most bang for you buck. Unless you never rewrite your software, that’s another story then. So let’s say your interior designer came up with a new door, a sliding door. Now your tests fail of course and they should, the function of the door has changed and it’s time to update the unittest. The base will stay the same the same key might still fit, the door should shut properly, etc. One of the new functions might be that the door slides open when a person walks into the sensor that triggers the door etc.

So how does it look when you need to unittest objects in your new webserver project. It’s similar but it’s a little different the problem is when you are running on a webserver you are running in a container. The container is the webserver. So logically you can’t test the door as the door can only be accessed when inside the container ( installed in the house ). The problem with that is that you do not want to unittest against a live webserver. As you can not get down to the object level to address the door directly. Therefor the trick is to setup a unittest environment that can fake the container / house. Once you do that your door thinks that it’s installed in a house and you can verify that the door functions as expected.

There is only one thing left to say, Jawoll Mein Agile F├╝hrer