Category Archives: c#

Clean and minified Javascript

It has been a while since I last posted a technical post. I’m sorry, but I am too busy enjoying my work to keep you posted as much as I should.

Just a few days ago I was playing around with YSlow and PageSpeed, two add-ons on Firefox. Both stated my Javascript files were 1) to many and 2) not at all at minimum size.

Searching for an automated way of cleaning up and minifying my Javascript files, I bumped in on JSMin, a Javascript minifier that can be downloaded in C#. Do you hear the term HttpModule in your head already as I did?

When you try to implement JSMin, do consider the fact that your Javascript files will be stripped really rigorous: some of my files did not work anymore after minifying. The reason for this is that Javascript gives you the opportunity to write bad code. To prevent myself from writing rubbish Javascript files that fall apart using JSMin, I now use ‘the tool that hurts feelings’, JSLint. It hints you about bad code and, when obliged to, prevents you from failure when using JSMin afterwards ;)

Lucky coding :) !

The using statement and XmlReader.Create

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)

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

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!