Thursday, December 20, 2007

I'm re-writing a Windows Form application using WPF as a way to
understand the basics. For a while I was banging my head against the
wall trying to do something really simple.
I was trying to launch another WPF window (form) as a modal dialiog
using ShowDialog as I would have done in wwindows Forms. Every time I
ran the application a large, blank white window appeared when the
ShowDialog call was made. This confused me until I realised I had
simply, accidentally deleted the designer-generated
InitializeComponent(); call from the Window's constructor.

These things always seem so obvious afterwards!

Thursday, December 20, 2007 9:45:14 PM (GMT Standard Time, UTC+00:00)
 Friday, October 05, 2007
The simple way to average (or more accurately known as 'find the arithmetic mean of') a list of numbers is to add them all up and divide by the number of items.
 
E.g.
The average of: 6, 2, 4, 5, 6, 3, 2 is 4:
6+2+4+5+6+3+2 = 28
28/7=4
 
Yesterday, we had the need to keep recalculating the average on the fly as more data is received so the user could be constantly informed of the current average. Using the classic algorithm would result in a degradation of performance over time so we chose an alternative.
The basic idea behind the continuous average is to keep track of the total number of items and current average as you go. Then, when a new number comes along work out how far above or below the current average it is and divide it by the number of items so far. This results in an 'adjustment' value that is used to 'correct' the current average to take account of the new value.
 
Here's a simple C# class that implements the algorithm

public class ContinuousAverage
{
   private int count = 0; 
   private decimal? currentAverage = null

   public decimal Average 
   {
      get 
      {
      if (currentAverage == null
         throw new InvalidOperationException ("No numbers have been averaged"); 
   
      return currentAverage.Value; 
      }
   }

   public int Count 
   {
      get { return count; } 
   }

   public void Add(decimal number) 
   {
      count++;

      if (currentAverage == null
      {
         currentAverage = number;
      }
      else 
      {
         decimal differenceFromAverage = number - currentAverage.Value; 
         currentAverage += differenceFromAverage / count;
      }
   }
}

[TestFixture]
public class ContinuousAverageTests
{

   [Test] 
   [ExpectedException(typeof(InvalidOperationException ), "No numbers have been averaged")] 
   public void TestAverageOfNoItemsThrowsException( ) 
   {
      MovingAverage movingAverage = new MovingAverage (); 

      decimal value = movingAverage.Average; 
   }

   [Test] 
   public void TestAverageOfOneItemIsItemValue( ) 
   {
      MovingAverage movingAverage = new MovingAverage (); 
      movingAverage.Add( 1.234M );

      Assert.AreEqual( 1.234M, movingAverage.Average ); 
   }

   [Test] 
   public void TestAverageOfSeveralItemsIsStandardArithmeticMean() 
   {
      MovingAverage movingAverage = new MovingAverage (); 

      movingAverage.Add(6);
      movingAverage.Add(2);
      movingAverage.Add(4);
      movingAverage.Add(5);
      movingAverage.Add(6);
      movingAverage.Add(3);
      movingAverage.Add(2);

      Assert.AreEqual(7, movingAverage.Count);
      Assert.AreEqual(4, movingAverage.Average, "(6+2+4+5+6+3+2)/7 = (28/7) = 4"); 
   }
}

Friday, October 05, 2007 7:06:23 AM (GMT Daylight Time, UTC+01:00)
 Wednesday, September 26, 2007

The difficulty with testing XML is that there are several ways of writing the same thing and each of them is valid.

For example, the two XML snippets below are equivalent:

Indented XML using an explicit end tag to close empty elements:

<Person>
  <FirstName></FirstName>
  <LastName>Smith</LastName>
</Person>

Non-indented XML with no additional whitespace and abbreviated empty tag:

<Person><FirstName/><LastName>Smith</LastName></Person>

XML Unit (http://xmlunit.sourceforge.net/) allows you to test if two pieces of XML are equivalent:

[Test]
public void TestEquivalentXmlFragmentsAreEqual( )
{
   string actualXml = "<Person><FirstName/><LastName>Smith</LastName></Person>";
   string expectedXml = "<Person>\r\n <FirstName></FirstName>\r\n <LastName>Smith</LastName></Person>";

   XmlDiff xmlDifference = new XmlDiff(new StringReader(actualXml), new StringReader(expectedXml));
   DiffResult result = xmlDifference.Compare();

   Assert.IsTrue(result.Equal);
}

The only negative thing to say about XmlUnit is the information it provides when the XML is not equivalent doesn’t make it particular easy to understand why the two pieces of XML differ.

Wednesday, September 26, 2007 7:23:09 AM (GMT Daylight Time, UTC+01:00)
 Tuesday, July 10, 2007

Last Friday I had the most infuriating day attempting to track down a problem with our project's continuous build machine. It was one of those erratic, inconsistent errors that prove tricky to pin down and it was occuring during registration of a DLL. The weird thing was Reggie and Regsvr32 were both reporting successful registration but MSBuild was failing in TlbImp when attempting to create the CLR callable interop wrapper from the DLL saying the DLL wasn't registered.

Anyway, I finally tracked down the problem on Monday morning when other weird things started happening. It turns out the Windows 2000 Server had run out of allocated registry space. (see http://www.google.co.uk/search?hl=en&q=windows+2000+registry+size)

Tuesday, July 10, 2007 6:25:11 PM (GMT Daylight Time, UTC+01:00)
 Sunday, May 27, 2007
Recently, I came across some C# code that was passing a reference type to a method using the 'ref' keyword. Since reference types are inherently passed by reference I was curious what effect the 'ref' keyword would have.

One of my colleagues speculated it would work like a double dereference in C++ and a little experimentation proved him correct.

The 'ref' keyword can be used to pass the reference of the reference to the object which allows the method to assign a different object to be returned via the parameter

[Test]
public void TestPassingClassBasedObjectsByRef( )
{
    string str1 = "initial value";


    PassStringInNormalWay( str1 );
    Assert.AreEqual("initial value", str1, "str1 object is not altered" );

    PassStringByReference( ref str1); 
    Assert.AreEqual("a", str1, "str1 is now a different object");
}

public void PassStringInNormalWay( string str )
{
    str = new string( 'new value', 1 );
}

public void PassStringByReference( ref string str)
{
    str = new string('new value', 1);
}

Sunday, May 27, 2007 10:42:24 PM (GMT Daylight Time, UTC+01:00)
 Tuesday, May 22, 2007

A few weeks ago I developed a website for my sister to help promote her mobile beauty therapist business.

Originally, I designed the website as a series of static html pages so we had the greatest amount of freedom in choosing a web host which helps keep her hosting costs down (There are loads of webhosts that will host basic websites for free with the hope that once you're with them you'll purchase extra features. In the end we settled for http://www.easyinternetsolutions.co.uk and so far we've had no problems) 

Yesterday, I needed to make a small change to the website that would affect all five pages and because I had manually created each of the pages it would be tedious to make the change on each page. Also, in the back of my mind I knew the price list would need updating on a regular basis to adjust the prices and to allow new treatments to be added. These requirements led me to revisit the way I produce the static HTML.

My idea was to extract all the dynamic portions of the website into an XML file then apply an XSLT transformation to produce the static HTML pages.
The XML contains:

  • The intra-site navigation
  • Full price list
  • Links to other websites

<links>
  <link>
    <text>Guild of Professional Beauty Therapists</text>
    <description>The UKs biggest professional beauty trade body. The Guild has over 5,000 members who are all fully qualified beauty and holistic therapists</description>
    <url>http://www.beautyguild.com/</url>
  </link>
</links>
<priceList>
  <section name="Waxing">
    <item text="Lip" duration="10 mins" price="£4.50"/>
    <item text="Chin" duration="10 mins" price="£4.50"/>

I created one XSLT document per output page and use nant's style task to apply the XSLT to the XML producing the HTML

e.g.

<?xml version="1.0"?>
<project default="BuildWebSite" basedir=".">
    
    <target name="BuildWebSite">

        <style style="index.xslt" in="website.xml" out="..\WebSite\index.htm" />
        <style style="treatments.xslt" in="website.xml" out="..\WebSite\treatments.htm" />
        <style style="prices.xslt" in="website.xml" out="..\WebSite\prices.htm" />
        <style style="contact.xslt" in="website.xml" out="..\WebSite\contact.htm" />
        <style style="links.xslt" in="website.xml" out="..\WebSite\links.htm" />
        
    </target>
            
</project>

 

Now, changes can be made to the XML data and the whole site rebuilt with the click of a button

Tuesday, May 22, 2007 7:33:17 PM (GMT Daylight Time, UTC+01:00)
 Friday, May 18, 2007

Recently, I was modifying an XSLT template for generating code and I needed to convert a Property name into camelCase (e.g. FirstName becomes firstName). I initially tried calling an XSLT template but soon reached the limits of what can be achieved in XSLT (or at least the limit of my knowledge!) without resorting to complex, unmanageable code.

Luckily, I stumbled across this article on MSDN describing how C# can be embedded in an XSLT document as a CDATA block and called in the same way as built in functions. Note: As far as I know, this only works if you are using the Microsoft MSXML 4.0 or .NET to perform the transformation.

The C# code must be enclosed in a ms:script element and, for readability, should be inside a CDATA block.

E.g.

<ms:script language="C#" implements-prefix="usr">
  <![CDATA[
    public string ToCamelCase( string str )
    {
      if (String.IsNullOrEmpty(str))
        return str;
      else
        return str.Substring(0, 1).ToLower() + str.Substring(1);
    }
  ]]>
</ms:script>

All namespaces must be declared in the stylesheet header:

<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:ms="urn:schemas-microsoft-com:xslt"
xmlns:usr="urn:my-namespace">

Now the new C# method can be called from within the stylesheet like this:

<xsl:value-of select="usr:ToCamelCase(title)"/>

 

Friday, May 18, 2007 8:24:27 AM (GMT Daylight Time, UTC+01:00)
 Monday, May 14, 2007

In my current project we’re migrating a solution from Visual FoxPro to .NET and SQL Server in a two-stage process. First the business logic will be re-written in C#, and finally the database layer will be switched to SQL Server.

To complicate things there are several tables in the database that contain sensitive data and so they are encrypted with a 3rd party utility which makes using ODBC data access impossible. Instead, all data access is done through a DLL written in FoxPro that is auto-generated from the domain model’s metadata. This DLL must be rebuilt every time the metadata changes and this currently has to be done by hand by the developer on their own machine. This is currently the manual only step in our automated build process and I’ve been looking for a way to automate it.

I’ve finally had the chance to sit down and investigate this and it turns out I can use the Foxpro COM DLL Vfp6t.dll:

string vfpProjectPath = Path.Combine( Environment.CurrentDirectory, args[0] );
string outputDll = Path.Combine( Environment.CurrentDirectory, args[1] );

Console.WriteLine("Building '{0}' from FoxPro project '{1}'", outputDll, vfpProjectPath );

FoxApplicationClass vfp = new FoxApplicationClass( );
vfp.DoCmd( String.Format( "BUILD DLL {0} FROM {1} RECOMPILE", outputDll, vfpProjectPath ) );
vfp.Quit( );

The only drawback is if an error occurs during the build a nasty message box pops up which is not so great when it occurs on the automated build machine

Monday, May 14, 2007 8:42:45 PM (GMT Daylight Time, UTC+01:00)