Monday, July 28, 2008

Synchronize Timezone for Windows Mobile 5.0 devices in C# and .Net Compact Framework

Synchronize Timezone for Windows Mobile 5.0 devices in C# and .Net Compact Framework

Many forums on the web have the issue of timezone synchronization for the WM5.0 devices posted and unanswered. Changing the timezone information on a Windows Mobile 5.0 device is not as straight forward as a Windows CE 5.0 one. The latter keep all the different timezones in the device registry, while the former has the timezones in a file on its file system.

To correctly change current timezone for applications in C# running on the Windows Mobile 5.0 platform, the PInvoke calls can be used. To make life easier, I would recommend the OpenNETCF library as it already wraps the PInvoke calls and their complexity in managed classes.

In the OpenNETCF.Win32 namespace, the TimeZoneCollection class exposes the Initialize() method that loads an array of timezone structures into memory. The Initialize() method of the TimeZoneCollection class uses the PInvoke call

[DllImport("citydb")]
extern static IntPtr ClockGetTimeZoneDataByOffset(int nOffset);

to get all the different timezones available on the device.

Once all the different timezones have been loaded, it is easy to loop through the collection and pick up the appropriate timezone and then call the SetTimeZoneInformation() method found in the DateEx class within the same namespace.

However, when the TimeZoneCollection is instantiated and initialized, a native exception is thrown on the device, similar to the following:

TimeZoneCollection tzc = new TimeZoneCollection();
tzc.Initialize();





Chris Tacke mentioned about a bug in the OpenNETCF code in his blog, and to get over this exception, the PInvoke definition must be changed so that it accepts a second parameter that is a ref int (the original only has one parameter, which is incorrect). Hence, the PInvoke definition will be as follows:

[DllImport("citydb")]
extern static IntPtr ClockGetTimeZoneDataByOffset(int nOffset, ref int fix);

If you need further information or still having problems, please do not hesitate to let me know.

Last but not the least, talking about the real synchronization, my application's server tier already handled all the complexity (i.e. determining the correct time, and timezone for the device and providing the timezone bias), so I just had to set the timezone and time correctly using the provided bias.

2 comments:

Nickname unavailable said...

This is good information. However, citydb is missing the start dates which are required for the timezone information struct. Any idea how to gather that data?

Anonymous said...

Cool article you got here. I'd like to read something more concerning that matter. The only thing it would also be great to see here is some pictures of any devices.
Kate Flouee
Cell jammer