Why Can't You Code?
The highest form of ignorance is when you reject something you don't know anything about.
The highest form of ignorance is when you reject something you don't know anything about.
Nov 25th
While working on a Silverlight application. I discovered that all the dates displayed in my DataGrid were skewed by a few hours from the real date stored in the database. Upon a closer look I noticed this skew was closely correlated to the time difference between the server’s time zone and the UTC date.
I needed my Silverlight application to display and use the exact same dates as the database regardless of the time zone my users were in.
Apparently, there’s a little known bug “feature” in the latest RIA Services Beta for Silverlight that involves dates:
RIA uses JSON to send data across the wire, and the Microsoft JSON serializers always serialize dates as UTC.
Dates retrieved from the database always seem to come up as DateTimeKind.Unspecified, meaning that the serializer will take a guess and treat them as local dates (in the server’s local time zone) and convert them to UTC time before sending out on the wire.
There’s an overridable property in the DomainService class called UsesUtcDateTimes which should in theory make the serializer leave your dates alone by treating them as UTC – which is still not ideal, but it means it won’t change them further – the property, however, currently doesn’t do anything.
The gotcha here is that the original time zone of the date is lost on the wire. It’s not sent along with the date so there’s no way you could determine, on the client, what time zone the date was in originally!
Example: if the server’s timezone is GMT+1, a date of December 21, 2012 12:21 PM will be converted to the UTC (GMT+0) date of December 21, 2012 11:21 AM before being sent out!
The Silverlight application will now display the UTC date of December 21, 2012 11:21 AM instead of the expected date from the database.
… is to mimic the behavior of the currently un-implemented UsesUtcDateTimes property and fool the serializer into thinking all of your dates are already in UTC so it doesn’t mess with them. Thanks to partial classes, you can do this.
Create new partial classes for each of your RIA Data Classes that hold DateTime values and override the On(DateTimePropertyName)Changed() methods like the following:
public partial class MyDataClass
{
partial void OnDateChanged()
{
_Date = DateTime.SpecifyKind(_Date, DateTimeKind.Utc);
}
partial void OnOtherDateChanged()
{
_OtherDate = DateTime.SpecifyKind(_OtherDate, DateTimeKind.Utc);
}
}
(Notice the partial keyword on the methods as well, not just on the class.)
.. is to pass the original time zone, as a property, along with the UTC DateTime across the wire, and then re-apply the time zone to it on the client before using it.
I’m hoping for a future RIA Services release to address this issue better, and perhaps pass the time zone across by itself.