blob: 437808bfeff6115cb6fe18efda76f4e0fad809f6 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
|
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
{
/// <summary>
/// Represents the <see cref="IConnectivityProvider"/> default implementation.
/// </summary>
/// <seealso cref="Tango.Core.ExtendedObject" />
/// <seealso cref="Tango.FSE.BL.Connectivity.IConnectivityProvider" />
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;
}
}
/// <summary>
/// Gets or sets the connectivity verification method.
/// </summary>
public ConnectivityVerificationMethod VerificationMethod { get; set; }
private bool _isOnline;
/// <summary>
/// Gets a value indicating whether the system has an active Internet connection currently.
/// </summary>
public bool IsOnline
{
get { return _isOnline; }
set
{
_isOnline = value;
RaisePropertyChanged(nameof(IsOnline));
}
}
/// <summary>
/// Checks whether the system has an active Internet connection.
/// </summary>
/// <returns></returns>
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;
}
}
/// <summary>
/// Checks whether the system has an active Internet connection.
/// </summary>
/// <returns></returns>
public Task<bool> CheckOnlineAsync()
{
return Task.Factory.StartNew<bool>(CheckOnline);
}
/// <summary>
/// Throws an exception if there is no Internet connection.
/// </summary>
public void ThrowIfNoInternet()
{
if (!CheckOnline())
{
throw new InternetConnectionException();
}
}
}
}
|