Feed Subscribe
Exception has been thrown by the target of an invocation.

Globalization is not an enemy 2 (N2CMS case)

by ondrejsv 28. August 2010 21:11

Some time ago I wrote an article about failures to properly write code concerning globalization, i.e. to write the code in such a way that it does not crash and works as intended when running in environments with regional settings you have not anticipated.

I’m playing with the wonderful N2CMS project these days. So far I’ve really enjoyed it. One of my first attempts to get known with it was to create a simple page with a date time field. They have an out-of-the-box date time control to render the field. As you can guess, I don’t have the en-US regional settings. Here’s the field:


One text box with a small nice calendar button for the date part and another text box sitting next for the time part. Let’s choose a date with the calendar.


It even recognizes the Slovak date pattern (DD. MM. YYYY):


So far so good. Let’s save the page and again open for edit. Bump:


Something very wrong happened. After some researching I found the DatePicker control’s source and there’s a quite ugly code :-):

if(value != null) { string[] dateTime = value.Split(' '); DatePickerBox.Text = dateTime[0]; if (dateTime.Length > 1) TimePickerBox.Text = dateTime[1].EndsWith(":00") ? dateTime[1].Substring(0, dateTime[1].Length - 3) : dateTime[1]; else TimePickerBox.Text = string.Empty; if (dateTime.Length > 2) TimePickerBox.Text += " " + dateTime[2]; // This could be AM/PM } else { DatePickerBox.Text = string.Empty; TimePickerBox.Text = string.Empty; }

I don’t know the reason behind that but parsing a datetime string on your own devices is a very bad idea.

And fix is simple. Just rely on the .NET Framework to do all the magic:

if(value != null)
    DateTime parsed;
    if (DateTime.TryParse(value, out parsed))
        DatePickerBox.Text = parsed.ToShortDateString();
        if (parsed.Second == 0)
            TimePickerBox.Text = parsed.ToShortTimeString();
            TimePickerBox.Text = parsed.ToLongTimeString();
DatePickerBox.Text = string.Empty;
TimePickerBox.Text = string.Empty;

Disclaimer: My goal is not to whine about the N2CMS quality. No, I think that N2CMS is really a wonderful project and I’m a fan of it :-) Give it a try!


Comments (2) -

8/29/2010 1:54:57 PM #


Is N2 still alive? It's been pretty viable project a couple of years ago, but I'm not sure anymore.

cruster Slovakia |

8/29/2010 6:39:59 PM #


Yes, it's alive and keeping very well with active commits (source codes reside on Google Code - http://code.google.com/p/n2cms/) and version 2.0 released on Jun 2010 with MVC 2 support!

ondrej Slovakia |

Comments are closed