using Microsoft.WindowsAPICodePack.Net;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Tango.Core;
namespace Tango.FSE.BL.Connectivity
{
///
/// Represents the default implementation.
///
///
///
public class DefaultConnectivityProvider : ExtendedObject, IConnectivityProvider
{
private class TimeoutWebClient : WebClient
{
public int Timeout { get; set; }
protected override WebRequest GetWebRequest(Uri uri)
{
WebRequest lWebRequest = base.GetWebRequest(uri);
lWebRequest.Timeout = Timeout;
((HttpWebRequest)lWebRequest).ReadWriteTimeout = Timeout;
return lWebRequest;
}
}
///
/// Gets or sets the connectivity verification method.
///
public ConnectivityVerificationMethod VerificationMethod { get; set; }
private bool _isOnline;
///
/// Gets a value indicating whether the system has an active Internet connection currently.
///
public bool IsOnline
{
get { return _isOnline; }
set
{
_isOnline = value;
RaisePropertyChanged(nameof(IsOnline));
}
}
///
/// Checks whether the system has an active Internet connection.
///
///
public bool CheckOnline()
{
#if OFFLINE
return false;
#endif
try
{
if (VerificationMethod == ConnectivityVerificationMethod.Default)
{
using (var client = new TimeoutWebClient())
{
client.Timeout = 1000;
client.OpenRead("http://google.com/generate_204");
IsOnline = true;
return true;
}
}
else if (VerificationMethod == ConnectivityVerificationMethod.Windows)
{
if (NetworkListManager.GetNetworks(NetworkConnectivityLevels.Connected).Any(x => x.IsConnectedToInternet))
{
IsOnline = true;
return true;
}
}
else if (VerificationMethod == ConnectivityVerificationMethod.Gateway)
{
return false; //Not implemented.
}
else if (VerificationMethod == ConnectivityVerificationMethod.AlwaysOnline)
{
return true;
}
return false;
}
catch
{
IsOnline = false;
return false;
}
}
///
/// Checks whether the system has an active Internet connection.
///
///
public Task CheckOnlineAsync()
{
return Task.Factory.StartNew(CheckOnline);
}
///
/// Throws an exception if there is no Internet connection.
///
public void ThrowIfNoInternet()
{
if (!CheckOnline())
{
throw new InternetConnectionException();
}
}
}
}