root / GES_PAC / Services / ConnexionService.cs @ 42456640
Historique | Voir | Annoter | Télécharger (2,203 ko)
1 |
using System.ComponentModel; |
---|---|
2 |
using System.Net.NetworkInformation; |
3 |
using System.Runtime.CompilerServices; |
4 |
|
5 |
namespace GES_PAC.Services |
6 |
{ |
7 |
public class ConnexionService : INotifyPropertyChanged |
8 |
{ |
9 |
private bool isINRAE; |
10 |
public bool IsINRAE |
11 |
{ |
12 |
get => isINRAE; |
13 |
set => SetProperty(ref isINRAE, value); |
14 |
} |
15 |
|
16 |
// e est null à l'init |
17 |
public async Task SetIsConnected(ConnectivityChangedEventArgs e = null) |
18 |
{ |
19 |
bool internetAccess = e is null ? Connectivity.NetworkAccess == NetworkAccess.Internet : e.NetworkAccess == NetworkAccess.Internet; |
20 |
// Test de l'accès au serveur |
21 |
try |
22 |
{ |
23 |
await Task.Run(() => |
24 |
{ |
25 |
IsINRAE = new Ping().Send("138.102.166.28").Status == IPStatus.Success || new Ping().Send("147.100.200.52").Status == IPStatus.Success; |
26 |
}); |
27 |
IsINRAE = internetAccess && IsINRAE; |
28 |
} |
29 |
catch (Exception) |
30 |
{ |
31 |
IsINRAE = false; |
32 |
} |
33 |
} |
34 |
|
35 |
public ConnexionService() |
36 |
{ |
37 |
Connectivity.ConnectivityChanged += Connectivity_ConnectivityChanged; |
38 |
Task.Run(() => SetIsConnected()).Wait(); |
39 |
// ou : new Action(async () => await SetIsConnected())(); |
40 |
} |
41 |
|
42 |
~ConnexionService() |
43 |
{ |
44 |
Connectivity.ConnectivityChanged -= Connectivity_ConnectivityChanged; |
45 |
} |
46 |
|
47 |
public void Connectivity_ConnectivityChanged(object sender, ConnectivityChangedEventArgs e) |
48 |
{ |
49 |
Task.Run(() => SetIsConnected(e)).Wait(); |
50 |
} |
51 |
|
52 |
#region INPC |
53 |
public event PropertyChangedEventHandler PropertyChanged; |
54 |
|
55 |
protected bool SetProperty<T>(ref T storage, T value, [CallerMemberName] string propertyname = null) |
56 |
{ |
57 |
if (Equals(storage, value)) return false; |
58 |
|
59 |
storage = value; |
60 |
OnPropertyChanged(propertyname); |
61 |
return true; |
62 |
} |
63 |
|
64 |
private void OnPropertyChanged([CallerMemberName] string propertyName = null) |
65 |
{ |
66 |
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); |
67 |
} |
68 |
#endregion |
69 |
} |
70 |
} |