I want to verify whether the system date of a computer is correct by checking date from the internet when my WPF app is launched.
I've created a class for this:
public static class DateVerifications
{
[System.Runtime.InteropServices.DllImport("wininet.dll")]
private extern static bool InternetGetConnectedState(out int Description, int ReservedValue);
public static bool CheckNetConnectivity()
{
int desc;
return InternetGetConnectedState(out desc, 0);
}
public static DateTime GetGoogleTime()
{
var myHttpWebRequest = (HttpWebRequest)WebRequest.Create("http://www.google.com");
var response = myHttpWebRequest.GetResponse();
string todaysDates = response.Headers["date"];
return DateTime.ParseExact(todaysDates,
"ddd, dd MMM yyyy HH:mm:ss 'GMT'",
CultureInfo.InvariantCulture.DateTimeFormat,
DateTimeStyles.AssumeUniversal);
}
}
Then in my viewmodel I've created a property and bound it to a label's text/content like below:
private string _dtm;
public string dtm
{
get
{
if (DateVerifications.CheckNetConnectivity())
{
if (DateTime.Today.ToString("dd-MM-yyyy") == DateVerifications.GetGoogleTime().ToString("dd-MM-yyyy"))
{
return _dtm="System date verified!";
}
else
return _dtm="System date is not correct!";
}
else
return _dtm="System date cannot be verified! No internet!!!";
}
}
xaml :
<Label
Content="{Binding dtm}"
But the problem is even when the internet connection is off the final else statement portion of the getter doesn't get hit because CheckNetConnectivity() is returning true even when the internet is disabled.
How to get around this ?