Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Windows Phone NTP Client

0.00/5 (No votes)
7 Aug 2011 1  
Windows Phone NTP Client

I've got plans for an application in which I need to know with certainty the current time. So I don't want to trust the time as reported by the user's device. Instead, I need to retrieve the time from a server. I made a NTP (Network Time Protocol) client for retrieving this information. This is something that couldn't be done on Windows Phone 7 prior to Mango. But with the fall update (Mango), access to sockets is granted.

The use of the client is pretty simple. At a minimum, one can create the client with the default constructor, subscribe to the ReceivedTime event, and call the RequestTime method to initiate a request. The ReceivedTime event may be called on a thread other than the UI thread so remember to use a dispatcher when making UI updates.

NTP Client

This is an example of a client using the code to display both the system time and the network time.

public partial class MainPage : PhoneApplicationPage
{
    private NtpClient _ntpClient;
    public MainPage()
    {
        InitializeComponent();
        _ntpClient = new NtpClient();
        _ntpClient.TimeReceived += new EventHandler<NtpClient.TimeReceivedEventArgs>
				(_ntpClient_TimeReceived);
    }

    void _ntpClient_TimeReceived(object sender, NtpClient.TimeReceivedEventArgs e)
    {
        this.Dispatcher.BeginInvoke(() =>
                                        {
                                            txtCurrentTime.Text = 
						e.CurrentTime.ToLongTimeString();
                                            txtSystemTime.Text = 
						DateTime.Now.ToUniversalTime().
						ToLongTimeString();
                                        });
    }

    private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
    {
            
    }

    private void UpdateTimeButton_Click(object sender, RoutedEventArgs e)
    {
        _ntpClient.RequestTime();
    }
}

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here