Well, this is long way back when I was a rookie to develop Windows Mobile applications with C#.
I believe there are some people want to sync the device date/time with their web server as the device date/time somehow doesn't tick correctly after certain days. So first of all, you should have a look the SetSystemTime function as you need a SYSTEMTIME structure to pass the value to SetSystemTime function.
We start to P/Invoke the SetSystemTime method.
[DllImport("coredll.dll", SetLastError = true)] private static extern bool SetSystemTime(ref SYSTEMTIME time);
Create the SYSTEMTIME structure.
public struct SYSTEMTIME { public short year; public short month; public short dayOfWeek; public short day; public short hour; public short minute; public short second; public short milliseconds; }
Create a simple function to convert DateTime to SYSTEMTIME and also calls the SetSystemTime function.
public void SetSystemDateTime(DateTime time) { SYSTEMTIME s = new SYSTEMTIME(); s.Year = (short)time.Year; s.Month = (short)time.Month; s.DayOfWeek = (short)time.DayOfWeek; s.Day = (short)time.Day; s.Hour = (short)time.Hour; s.Minute = (short)time.Minute; s.Second = (short)time.Second; s.Milliseconds = (short)time.Millisecond; SetSystemTime(ref s); }
As most http web pages contains "Date" part of the document header and the "Date" part usually is the server time. So we gets the date/time and sync with our device. We use HttpWebRequest and HttpWebResponse to get the web page header.
public bool SyncDateTime(string url) { HttpWebRequest myRequest = null; HttpWebResponse myResponse = null; try { //create a HTTP request of the file and capture the response myRequest = (HttpWebRequest)WebRequest.Create(url); myRequest.Accept = "*/*"; myRequest.KeepAlive = false; // Assign the response object of 'HttpWebRequest' to a 'HttpWebResponse' variable. myResponse = (HttpWebResponse)myRequest.GetResponse(); if (myResponse != null) { if (myResponse.Headers["Date"] != null) { DateTime dt = DateTime.Parse(myResponse.Headers["Date"], CultureInfo.CurrentCulture); // Sets the parsed time to device. SetSystemDateTime(dt.ToUniversalTime()); return true; } } } finally { // Releases the resources of the response. if (myResponse != null) myResponse.Close(); myRequest = null; myResponse = null; } return false; }
Above method has few millisecond or event seconds inaccuracy as we doesn't calculate the time difference from request to response. However, it is quite good enough for many customers. Ha... I am lazy again...
0 comments :
Post a Comment