Great: happy talk

September 7th, 2009 Uncategorized No comments

Surfing the net, I stumbled upon a great post about so-called ‘happy talk’. Reading it, I laughed a lot. Jeff Atwood, I will read your blog more often :) ! The link: http://www.codinghorror.com/blog/archives/001300.html. Enjoy reading :) !

The using statement and XmlReader.Create

September 7th, 2009 .NET, bug, c#, tip, visual studio 2008 No comments

Are you also fond of using the using statement (e.g. when dealing with streams)? I am, since it kind-of guarantees me that streams are closed when I think they should be closed, even if I do not specify the Dispose() command. You probably noticed the ‘kind-of guarantee’ part. You are right, this is not always the case. It took me a while to find out the the following is not going to work as smooth as expected:

using (var reader = XmlReader.Create(File.Open(fileName, FileMode.Open)))
    { ... }

You probably wonder what’s the problem of the code printed above. I don’t see it too, however, I know there is a problem related to this code. The problem lies in the Create overload used in the example code. It uses default XmlReaderSettings. Unfortunately, this settings do not include having the CloseInput property set to true. You can do the math: no closed file at all! That’s a guarantee for having troubles on the file ‘being in use already’.

The solution to this problem is quite simple:

using (XmlReader reader = XmlReader.Create(File.Open(path, FileMode.Open),
         new XmlReaderSettings { CloseInput = true })) { ... }

How can we call this? A ‘bug’? No, at least not technically spoken. Since the XmlReader creates the stream, it should close it too. The case is, you should not expext it knowing the using statement as most people know it (fail-proofing your code). Since I know this, I am a little bit scared about using using statements without calling the stream’s constructor. You can do so, but be sure it does what you expect it to do… In my opinion, the using statement still remains very helpful, please I do not consider it being as perfect as I thought it to be for years ;)

Calculate age (for instance, on reference data)

September 2nd, 2009 .NET, c#, datetime, tip No comments

Now and then, I have to calculate ages (for instance, on a reference date). The method to calculate ages in .NET is pretty simple, although it can be ‘a pain in the ass’ to find out how simple it should have been :) … Enjoy the code :) !

public static class DateTimeHelper
{
    public static int CalculateAge(DateTime birthday)
    {
        return CalculateAge(DateTime.Now, birthday);
    }

    public static int CalculateAge(DateTime referenceDate, DateTime birthday)
    {
        // calculate age in years on the given reference date.
        var comparisonDate = new DateTime(birthday.Year, referenceDate.Month, referenceDate.Day);

        return (comparisonDate.Date < birthday.Date)
                      ? referenceDate.Year - birthday.Year - 1
                      : referenceDate.Year - birthday.Year;
    }
}

Dutch bank account number check

August 13th, 2009 .NET, 11-proef, c#, elfproef No comments

For a Dutch customer I currently work for, I worked out the bank account number check (in Dutch: elfproef voor bankrekeningnummers). After checking out the Internet for the correct definition of Dutch bank account numbers (found on Wikipedia), I created the next check in C#:

var cleanAccNumber = accountNumber.Replace(".", "");

// A bank account number consists of 9 or 10 digits
if (!(cleanAccNumber.Length == 9 || cleanAccNumber.Length == 10)) return false;

// ... all being numeric and not resulting in a 0 when converted to a number ...
long l;
if (!long.TryParse(cleanAccNumber, out l)) return false;
if (l == 0) return false;

// pad it to the left to 10 digits with preceding zero's.
cleanAccNumber = cleanAccNumber.PadLeft(10, '0');

// ... the number must be validatable to the so-called 11-proof ...
long total = 0;
for (var i = 1; i <= cleanAccNumber.Length; i++)
{
// 11-proof for 10 digit bank account numbers (bron: Wikipedia): (1*A + 2*B + 3*C + 4*D + 5*E + 6*F + 7*G + 8*H + 9*H + 10*I) % 11 == 0
var number = Convert.ToInt32(cleanAccNumber[i - 1].ToString());
total += number*i;
}

// ... not result in a 0 when dividing by 11 ...
if (total == 0) return false;

// ... and not have a modulo when dividing by 11.
return total % 11 == 0;

Good luck when you should build one for yourself!

How to insert blank rule (<br />) from C# code

Once in a while I have to develop custom user controls that require blank rules in them. Almost always I think again: ‘I should have blogged about it, would have saved me lots of time searching’ :) … Well, no more, because here it is…

Many people using blank rules in C# code, use the following commands:

var brControl1 = new HtmlGenericControl { InnerHtml = "<br />" };
var brControl2 = new HtmlGenericControl("br");

However, brControl1 also prints a <span> tag and brControl2 prints <br></br>. Both options are not really useful. You should take notice of the fact that the HtmlGenericControl is not meant to be used for anything else than span, body, div and font (what is designed for ‘as the word goes’).  The way to go when printing a blank rule is:

var brControl3 = new LiteralControl("<br />");

This actually prints exactly what you would like it to print, namely <br />. Hope this helps you too :) ! BTW, if you are using the HtmlTextWriter class, you can also use the WriteBreak() function if you like.