Statistiques
| Branche: | Révision:

inraetemplate / INRAETemplate / Services / ConnexionService.cs @ 7b67ff55

Historique | Voir | Annoter | Télécharger (2,408 ko)

1
using System;
2
using System.Collections.Generic;
3
using System.ComponentModel;
4
using System.Linq;
5
using System.Net.NetworkInformation;
6
using System.Runtime.CompilerServices;
7
using System.Text;
8
using System.Threading.Tasks;
9

    
10
namespace INRAETemplate.Services
11
{
12
    public class ConnexionService : INotifyPropertyChanged
13
    {
14
        private bool isINRAE;
15
        public bool IsINRAE
16
        {
17
            get => isINRAE;
18
            set => SetProperty(ref isINRAE, value);
19
        }
20

    
21
        // e est null à l'init
22
        public async Task SetIsConnected(ConnectivityChangedEventArgs e = null)
23
        {
24
            bool internetAccess = e is null ? Connectivity.NetworkAccess == NetworkAccess.Internet : e.NetworkAccess == NetworkAccess.Internet;
25
            // Test de l'accès au serveur
26
            try
27
            {
28
                await Task.Run(() =>
29
                {
30
                    IsINRAE = new Ping().Send("138.102.166.28").Status == IPStatus.Success || new Ping().Send("147.100.200.52").Status == IPStatus.Success;
31
                });
32
                IsINRAE = internetAccess && IsINRAE;
33
            }
34
            catch (Exception)
35
            {
36
                IsINRAE = false;
37
            }
38
        }
39

    
40
        public ConnexionService()
41
        {
42
            Connectivity.ConnectivityChanged += Connectivity_ConnectivityChanged;
43
            Task.Run(() => this.SetIsConnected()).Wait();
44
            // ou : new Action(async () => await SetIsConnected())();
45
        }
46

    
47
        ~ConnexionService()
48
        {
49
            Connectivity.ConnectivityChanged -= Connectivity_ConnectivityChanged;
50
        }
51

    
52
        public void Connectivity_ConnectivityChanged(object sender, ConnectivityChangedEventArgs e)
53
        {
54
            Task.Run(() => this.SetIsConnected(e)).Wait();
55
        }
56

    
57
        #region INPC
58
        public event PropertyChangedEventHandler PropertyChanged;
59

    
60
        protected bool SetProperty<T>(ref T storage, T value, [CallerMemberName] string propertyname = null)
61
        {
62
            if (Equals(storage, value)) return false;
63

    
64
            storage = value;
65
            OnPropertyChanged(propertyname);
66
            return true;
67
        }
68

    
69
        private void OnPropertyChanged([CallerMemberName] string propertyName = null)
70
        {
71
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
72
        }
73
        #endregion
74
    }
75
}