// -----------------------------------------------------------------------
//
// This code can be used in commercial, free and open source projects.
//
// -----------------------------------------------------------------------
using GalaSoft.MvvmLight.Messaging;
using System;
using System.Net.Http;
using System.Threading.Tasks;
using VDsoft.OnlineMeter.Uwp.Model;
namespace VDsoft.OnlineMeter.Uwp.Dal
{
///
/// Monitors the internet connection.
///
public class InternetMonitor
{
///
/// Url for the test.
///
private readonly string testUrl = "http://www.google.at";
///
/// Starts to check the connection periodically.
///
/// A Task when the operation is finished.
public async Task StartConnectionCheck()
{
while (true)
{
var result = this.CheckConnection();
Messenger.Default.Send(result.Result, ViewModel.ViewModelLocator.StatusUpdateToken);
await Task.Delay(TimeSpan.FromSeconds(2));
}
}
///
/// Checks the connection.
///
/// with the result of the check.
public async Task CheckConnection()
{
ConnectionResult connection = null;
try
{
using (HttpClient client = new HttpClient())
{
var result = await client.GetAsync(this.testUrl);
string body = await result.Content.ReadAsStringAsync();
if (string.IsNullOrEmpty(body))
{
connection = new ConnectionResult(false);
}
else
{
connection = new ConnectionResult(true);
}
}
}
catch (Exception)
{
connection = new ConnectionResult(false);
}
return connection;
}
}
}