The Culture of Silverlight

January 19, 2009
No Comments.

Url: http://wildermuth.com/2009/01/18/Fun_with_Items…
Silverlight Logo
If you were paying attention yesterday, you probably noticed the little ItemsControl article that I dropped on the blog. Almost immediately I received comments from readers who where unable to run the app, either on the site or with the source code. What the heck is going on?  There was almost zero code, it was a very simple example…and it works on my machine.

So what went wrong? A big thanks to Hugo for posting the error he was getting:

Line: 0
Error: Unhandled Error in Silverlight 2 Application String was not recognized as a valid DateTime. at System.DateTimeParse.Parse(String s, DateTimeFormatInfo dtfi, DateTimeStyles styles)

That pointed to exactly what was happening. I was parsing dates in some code to create a set of data to bind to.  And some of those dates were invalid.  Weren’t they?  Let’s look at the innocent code:

DateTime dt = DateTime.Parse("7/23/2008 12:00:00 AM");

Why is this bad? Because Silverlight runs in the culture of the machine that it runs on. That means that when some of my non-North American readers (the only ones to test my code at 3am) ran the app it failed.  Being ethnocentric myself, this date is decidedly American-English (us-en). Europeans were the first th point this out when Silverlight correctly attempted to convert that date to the 7th day of the 23rd month of 2008.  D’oh!

I had two ways of solving this, I could have re-generated all the dates as UTC dates to solve it, but I opted for the simple approach:  use a culture. Because these dates were American-English dates, I simply grabbed a “us-en” culture and told the parser to use it:

// Get my Culture, who knew it was so small
CultureInfo culture = new CultureInfo("en-US");

// Parse the date with my ethnocentricity
DateTime dt = DateTime.Parse("7/23/2008 12:00:00 AM", culture);

Lesson learned…be careful of letting my culture invade my code.