Exemple #1
0
        static public async Task <string> SetPMH(string noseq)
        {
            var parameters = new Dictionary <string, string> {
                { "pheidiaction", "complexAction" }, { "pheidiparams", "action**:**setPMH**,**value**:**" + noseq + "**,**" }
            };
            HttpResponseMessage response = await PheidiNetworkManager.SendHttpRequestAsync(parameters, new TimeSpan(0, 0, 10));

            if (response != null)
            {
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    string content = await response.Content.ReadAsStringAsync();

                    Debug.WriteLine(content);

                    string setLanguageResult     = "";
                    int    setLanguageTriesCount = 0;
                    while (setLanguageResult != GoodResult && setLanguageTriesCount < 10)
                    {
                        setLanguageResult = await SendNewLanguage();

                        setLanguageTriesCount++;
                    }

                    return(GoodResult);
                }
            }
            return(BadResult);
        }
        /// <summary>
        /// Envoie une requête http au serveur contenant les données de localisation en format json.
        /// </summary>
        /// <param name="json">Json string</param>
        public static async Task <bool> SendJsonData(string json)
        {
            var handler = new HttpClientHandler()
            {
                CookieContainer = App.CookieManager.GetAllCookies()
            };

            using (var httpClient = new HttpClient(handler, true))
            {
                var parameters = new Dictionary <string, string> {
                    { "pheidiaction", "sendLocationData" }, { "pheidiparams", "value**:**" + json + "**,**" }
                };
                HttpResponseMessage response = await PheidiNetworkManager.SendHttpRequestAsync(parameters, new TimeSpan(0, 0, 30));

                if (response != null)
                {
                    if (response.StatusCode == HttpStatusCode.OK)
                    {
                        string responseContent = await response.Content.ReadAsStringAsync();

                        Debug.WriteLine("Reponse:" + responseContent);
                        return("Good" == responseContent);
                    }
                }
                Debug.WriteLine("Problème de connexion au serveur, veuillez réessayer plus tard");
                return(false);
            }
        }
Exemple #3
0
        static public async Task <string> SendNewLanguage()
        {
            string p   = "";
            var    dic = new Dictionary <string, string>();

            dic.Add("VALUE", App.Language);

            foreach (var d in dic)
            {
                p += d.Key + "**:**" + d.Value + "**,**";
            }
            var parameters = new Dictionary <string, string> {
                { "pheidiaction", "SET_CON_A_LANGUAGE" }, { "pheidiparams", p }
            };

            var response = await PheidiNetworkManager.SendHttpRequestAsync(parameters, new TimeSpan(0, 0, 240));

            if (response != null)
            {
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    string responseContent = response.Content.ReadAsStringAsync().Result;
                    Debug.WriteLine("Reponse:" + responseContent);
                }
                return(GoodResult);
            }
            return(BadResult);
        }
Exemple #4
0
        /// <summary>
        /// Sends the geofence to server.
        /// </summary>
        /// <returns><c>true</c>, if geofence was sent to the server , <c>false</c> otherwise.</returns>
        /// <param name="geofence">Geofence.</param>
        async Task <bool> SendGeofenceToServer(Geofence geofence)
        {
            var json       = JsonConvert.SerializeObject(geofence);
            var parameters = new Dictionary <string, string> {
                { "pheidiaction", "sendGeofence" }, { "pheidiparams", "value**:**" + json + "**,**" }
            };
            HttpResponseMessage response = await PheidiNetworkManager.SendHttpRequestAsync(parameters, new TimeSpan(0, 0, 30));

            if (response != null)
            {
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    string responseContent = response.Content.ReadAsStringAsync().Result;
                    Debug.WriteLine("Reponse:" + responseContent);
                    var answer = JsonConvert.DeserializeObject <Dictionary <string, string> >(responseContent);
                    if (answer["STATUS"] == "Good")
                    {
                        if (string.IsNullOrEmpty(geofence.NoSeq) && answer.ContainsKey("NOSEQ"))
                        {
                            geofence.NoSeq = answer["NOSEQ"];
                        }
                        geofence.LastModification = DateTime.UtcNow;
                        return(true);
                    }
                }
            }
            return(false);
        }
Exemple #5
0
        /// <summary>
        ///Méthode qui envoie la requête http permettant de se connecter à partir de l'application mobile.
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <param name="rememberUser"></param>
        static public async Task <string> UserLogin(string username, string password, bool rememberUser)
        {
            if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password) || App.CurrentServer == null)
            {
                return(AppResources.Erreur_LaissezAucunChampVide);
            }

            var parameters = new Dictionary <string, string> {
                { "pheidiaction", "complexAction" }, { "pheidiparams", "action**:**getWebSession**,**Username**:**" + username + "**,**Password**:**" + password + "**,**" }
            };
            HttpResponseMessage response = await PheidiNetworkManager.SendHttpRequestAsync(parameters, new TimeSpan(0, 0, 10));

            if (response != null)
            {
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    string rc = await response.Content.ReadAsStringAsync();

                    Debug.WriteLine("WEBSESSION: " + rc);
                    App.WebSession = new Cookie()
                    {
                        Name = "WEBSESSION", Domain = App.CurrentServer.Domain, Value = rc
                    };
                    var userAgent = App.AppName + " " + Xamarin.Forms.Device.RuntimePlatform;
                    var uaCookie  = new Cookie()
                    {
                        Name = "IPHEIDI_USERAGENT", Domain = App.CurrentServer.Domain, Value = userAgent
                    };
                    if (!string.IsNullOrEmpty(rc) && Utilities.IsNumeric(rc))
                    {
                        Debug.WriteLine(rc);
                        if (rememberUser && !App.DeviceIsShared)
                        {
                            App.UserNoseq = App.CredentialsManager.SaveCredentials(username, password, App.SystemCredentials.Key);
                        }
                        App.CookieContainer.GetCookies(new Uri(App.CurrentServer.Address));


                        //Ajoute le cookie de WEBSESSION et envoie vers la page web.
                        App.CookieManager.AddCookie(App.WebSession);
                        App.CookieManager.AddCookie(uaCookie);
                        string setLanguageResult     = "";
                        int    setLanguageTriesCount = 0;
                        while (setLanguageResult != GoodResult && setLanguageTriesCount < 10)
                        {
                            setLanguageResult = await SendNewLanguage();

                            setLanguageTriesCount++;
                        }
                        App.IsInLogin = false;
                        return(GoodResult);
                    }
                    return(AppResources.Erreur_MauvaisEmailOuMdp);
                }
            }
            return(AppResources.Erreur_ProblemeConnexionServeur);
        }
        static async Task <List <Action> > GetActions()
        {
            return(await Task.Run(async() =>
            {
                var list = new List <Action>();
                var parameters = new Dictionary <string, string> {
                    { "pheidiaction", "complexAction" }, { "pheidiparams", "action**:**GetIpheidiActions**,**" }
                };
                HttpResponseMessage response = await PheidiNetworkManager.SendHttpRequestAsync(parameters, new TimeSpan(0, 0, 30));
                if (response != null)
                {
                    if (response.StatusCode == HttpStatusCode.OK)
                    {
                        string responseContent = response.Content.ReadAsStringAsync().Result;
                        Debug.WriteLine("Reponse:" + responseContent);
                        try
                        {
                            List <Dictionary <string, object> > fields = PheidiNetworkManager.GetFields(responseContent);
                            foreach (var f in fields)
                            {
                                var action = new Action()
                                {
                                    NoSeq = f["ACO_A_NoSeq"].ToString(),
                                    Name = f["ACO_A_Action"].ToString(),
                                    Category = f["Category"].ToString(),
                                    Description = f["SousCategory"].ToString()
                                };
                                list.Add(action);
                            }

                            list.OrderBy((arg) => arg.Category).ThenBy((arg) => arg.Description);
                        }
                        catch
                        {
                            var answer = JsonConvert.DeserializeObject <Dictionary <string, string> >(responseContent);
                            if (answer["STATUS"] == "Good")
                            {
                                if (answer.ContainsKey("VALUE"))
                                {
                                    try
                                    {
                                        list = JsonConvert.DeserializeObject <List <Action> >(answer["VALUE"]);
                                        Debug.WriteLine("List Generated");
                                    }
                                    catch (Exception e)
                                    {
                                        Debug.WriteLine(e.Message);
                                    }
                                }
                            }
                        }
                    }
                }
                return list;
            }));
        }
        public static void ExecuteAction(Action action)
        {
            Task.Run(async() =>
            {
                if (!action.Params.ContainsKey("action"))
                {
                    action.Params.Add("action", action.Name);
                }
                action.Params["action"] = action.Name;

                if (!action.Params.ContainsKey("language"))
                {
                    action.Params.Add("language", App.Language);
                }
                action.Params["language"] = App.Language;


                string param = "";
                foreach (var data in action.Params)
                {
                    param += data.Key + "**:**" + data.Value + "**,**";
                }
                var parameters = new Dictionary <string, string> {
                    { "pheidiaction", action.Name }, { "Pheidi_Param[pheidiEvent]", action.Event }, { "pheidiparams", param }
                };
                HttpResponseMessage response = await PheidiNetworkManager.SendHttpRequestAsync(parameters, new TimeSpan(0, 0, 240));

                if (response != null)
                {
                    if (response.StatusCode == HttpStatusCode.OK)
                    {
                        string responseContent = response.Content.ReadAsStringAsync().Result;
                        Debug.WriteLine("Reponse:" + responseContent);
                        action.ActionAnswer = responseContent;
                    }
                }
                RunActionAnswer(action);
            });
        }
Exemple #8
0
        static public async Task <string> GetPMH()
        {
            var parameters = new Dictionary <string, string> {
                { "pheidiaction", "complexAction" }, { "pheidiparams", "action**:**GetPMH**,**" }
            };
            HttpResponseMessage response = await PheidiNetworkManager.SendHttpRequestAsync(parameters, new TimeSpan(0, 0, 10));

            if (response != null)
            {
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    string content = await response.Content.ReadAsStringAsync();

                    Debug.WriteLine(content);
                    App.PMH = new Dictionary <string, string>();
                    foreach (var fields in GetFields(content))
                    {
                        App.PMH.Add(fields["PMH_A_Identifiant"].ToString(), fields["Noseq"].ToString());
                    }
                    return(GoodResult);
                }
            }
            return(BadResult);
        }
Exemple #9
0
        public PmhPage(bool hasBackButton = true)
        {
            InitializeComponent();
            NavigationPage.SetHasNavigationBar(this, false);
            demiCercle.Foreground = App.ColorPrimary;
            foreach (var pmh in App.PMH)
            {
                pmhPicker.Items.Add(pmh.Key);
            }
            HasBackButton = hasBackButton;
            //if (Device.RuntimePlatform == Device.iOS)
            {
                btnBack.TextColor = App.ColorPrimary;
                btnBack.Clicked  += (sender, e) => OnBackButtonPressed();
                btnBack.IsVisible = hasBackButton;
                btnBack.Text      = AppResources.RetourBouton;
            }
            pmhPicker.SelectedIndexChanged += (sender, e) =>
            {
                noseq = App.PMH[pmhPicker.SelectedItem.ToString()];
            };
            pmhPicker.SelectedIndex = 0;

            btnContinue.Clicked += (sender, e) =>
            {
                Device.BeginInvokeOnMainThread(() =>
                {
                    Task.Run(async() =>
                    {
                        Device.BeginInvokeOnMainThread(() => AppLoadingView.SetVisibility(true));

                        string answer = await PheidiNetworkManager.SetPMH(noseq);
                        if (answer == PheidiNetworkManager.GoodResult)
                        {
                            Device.BeginInvokeOnMainThread(() =>
                            {
                                //CRASH SUR ANDROID, https://bugzilla.xamarin.com/show_bug.cgi?id=53179
                                if (Device.RuntimePlatform != Device.Android)
                                {
                                    App.Instance.GetToApplication();
                                    Navigation.RemovePage(this);
                                }
                                //Work Around
                                else
                                {
                                    Navigation.PopAsync();
                                    App.Instance.GetToApplication();
                                }
                            });
                        }
                        else
                        {
                            App.NotificationManager.DisplayAlert(AppResources.Erreur_ProblemeConnexionServeur, AppResources.Erreur_Title, "OK", () => { });
                        }
                        Device.BeginInvokeOnMainThread(() => AppLoadingView.SetVisibility(false));
                    });
                });
            };
            btnContinue.Text = AppResources.ContinuerBouton;
            SetFooter();
            mainLayout.RaiseChild(AppLoadingView);
            AppLoadingView.IsVisible = false;
        }
        public static void RunActionAnswer(Action action)
        {
            try
            {
                var fields = PheidiNetworkManager.GetFields(action.ActionAnswer);
                if (fields != null)
                {
                    foreach (var f in fields)
                    {
                        var field = f as Dictionary <string, object>;
                        if (field != null)
                        {
                            if (field.ContainsKey("autoClick"))
                            {
                                var    autoClick = field["autoClick"] as string;
                                string script    = "AutoClick(" + autoClick + ",0,0);";

                                BrowserPage.InsertJavscript(script);
                            }

                            if (field.ContainsKey("message" + App.Language.ToUpper()))
                            {
                                string lang        = App.Language.ToUpper();
                                string message     = field["message" + lang] as string;
                                string title       = "Pheidi";
                                string textConfirm = "Ok";
                                string textCancel  = "Cancel";
                                foreach (var key in field.Keys)
                                {
                                    if (key == "bCancel" + lang)
                                    {
                                        textCancel = field["bCancel" + lang] as string;
                                    }

                                    else if (key == "bConfirm" + lang)
                                    {
                                        textConfirm = field["bConfirm" + lang] as string;
                                    }

                                    else if (key == "title" + lang)
                                    {
                                        title = field["title" + lang] as string;
                                    }
                                }

                                if (App.IsInBackground)
                                {
                                    Debug.WriteLine("ActionManger - RunActionAnswer - SendNotification");
                                    App.NotificationManager.SendNotification(message, title, "nearby_square", action);
                                }
                                else
                                {
                                    Debug.WriteLine("ActionManger - RunActionAnswer - DisplayAlert");
                                    System.Action confirm = () => { };
                                    confirm = () =>
                                    {
                                        action.Event = "onConfirm";
                                        ExecuteAction(action);
                                    };


                                    System.Action cancel = () =>
                                    {
                                        action.Event = "onCancel";
                                        ExecuteAction(action);
                                    };

                                    if (!string.IsNullOrEmpty(textCancel))
                                    {
                                        App.NotificationManager.DisplayAlert(message, title, textConfirm, textCancel, confirm, cancel);
                                    }
                                    else
                                    {
                                        App.NotificationManager.DisplayAlert(message, title, textConfirm, confirm);
                                    }
                                }
                            }
                        }
                    }
                }
            }

            catch (Exception e)
            {
                Debug.WriteLine(e.Message);
            }
        }
        public ServerLoginPage()
        {
            NavigationPage.SetHasNavigationBar(this, false);
            InitializeComponent();
            LastServerNoseq = App.ServerInfoNoseq;
            EntriesVisible(false);
            demiCercle.Foreground = App.ColorPrimary;
            //if (Device.RuntimePlatform == Device.iOS)
            {
                btnBack.TextColor = App.ColorPrimary;
                btnBack.Clicked  += (sender, e) => OnBackButtonPressed();
                btnBack.IsVisible = HasBackButton;
                btnBack.Text      = AppResources.RetourBouton;
            }

            btnLogin.Clicked += (sender, e) =>
            {
                Device.BeginInvokeOnMainThread(() =>
                {
                    Task.Run(async() =>
                    {
                        Device.BeginInvokeOnMainThread(() => AppLoadingView.SetVisibility(true));

                        string s = "";
                        if (loginState == LoginState.ServerLogin)
                        {
                            s = await PheidiNetworkManager.UserLogin(usernameEntry.Text, passwordEntry.Text, true);
                            if (s != PheidiNetworkManager.GoodResult)
                            {
                                App.NotificationManager.DisplayAlert(s, AppResources.Erreur_Title, "Ok", () => { });
                            }
                        }
                        if (loginState == LoginState.ServerAutoLogin)
                        {
                            if (App.Credentials.Any((arg) => arg.Value["SystemCredentialsNoseq"] == App.SystemCredentials.Key && arg.Value["ServerNoseq"] == App.ServerInfoNoseq))
                            {
                                var credentials = App.Credentials.First((arg) => arg.Value["SystemCredentialsNoseq"] == App.SystemCredentials.Key && arg.Value["ServerNoseq"] == App.ServerInfoNoseq);
                                s = await PheidiNetworkManager.UserLogin(credentials.Value["Username"], credentials.Value["Password"], false);
                                if (s == PheidiNetworkManager.GoodResult)
                                {
                                    App.UserNoseq = credentials.Key;
                                }
                            }
                            else
                            {
                                s = await PheidiNetworkManager.UserLogin(App.SystemCredentials.Value["Username"], App.SystemCredentials.Value["Password"], false);
                                if (s == PheidiNetworkManager.GoodResult)
                                {
                                    App.UserNoseq = App.SystemCredentials.Key;
                                }
                            }

                            if (s == AppResources.Erreur_MauvaisEmailOuMdp)
                            {
                                loginState = LoginState.ServerLogin;
                                Device.BeginInvokeOnMainThread(() => EntriesVisible(true));
                            }
                            else if (s != PheidiNetworkManager.GoodResult)
                            {
                                App.NotificationManager.DisplayAlert(s, AppResources.Erreur_Title, "Ok", () => { });
                            }
                        }

                        if (s == PheidiNetworkManager.GoodResult)
                        {
                            if (LastServerNoseq != App.ServerInfoNoseq)
                            {
                                DatabaseHelper.Database.DropTable <Geofence>();
                                DatabaseHelper.Database.CreateTable <Geofence>();
                                if (Application.Current.Properties.ContainsKey("LastGeofenceSync"))
                                {
                                    Application.Current.Properties["LastGeofenceSync"] = "1753-01-01 00:00:00";
                                }
                            }
                            await PheidiNetworkManager.GetPMH();
                            if (App.PMH.Count > 1)
                            {
                                Device.BeginInvokeOnMainThread(async() => await Navigation.PushAsync(new PmhPage()));
                            }
                            else
                            {
                                Device.BeginInvokeOnMainThread(App.Instance.GetToApplication);
                            }
                        }
                        Device.BeginInvokeOnMainThread(() => AppLoadingView.SetVisibility(false));

                        if (!string.IsNullOrEmpty(s))
                        {
                            //Device.BeginInvokeOnMainThread(async () => await DisplayAlert("Problème de connexion", s, "OK"));
                        }
                    });
                });
            };



            foreach (var server in App.ServerInfoList)
            {
                urlPicker.Items.Add(server.Domain);
            }

            urlPicker.Title = AppResources.SelectAdresse;
            urlPicker.SelectedIndexChanged += (sender, e) =>
            {
                string item = urlPicker.SelectedItem.ToString();
                App.CurrentServer   = App.ServerInfoList.First(sein => sein.Domain == item);
                App.ServerInfoNoseq = App.CurrentServer.Noseq;
                EntriesVisible(false);
                loginState = LoginState.ServerAutoLogin;
            };
            if (App.CurrentServer != null)
            {
                urlPicker.SelectedIndex = urlPicker.Items.IndexOf(App.CurrentServer.Domain);
            }

            urlPicker.SelectedIndex = urlPicker.SelectedIndex >= 0 ? urlPicker.SelectedIndex : 0;



            usernameEntry.Placeholder = AppResources.CourrielPlaceHolder;
            passwordEntry.Placeholder = AppResources.MotDePassePlaceHolder;
            btnLogin.Text             = AppResources.ContinuerBouton;

            SetFooter();
            mainLayout.RaiseChild(AppLoadingView);
            AppLoadingView.SetVisibility(false);
        }
Exemple #12
0
        /// <summary>
        ///Méthode qui envoie la requête http permettant de se connecter au systeme central et de recuperer la liste des serveur de l'usager.
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        public static async Task <string> SystemLogin(string username, string password)
        {
            var list = new List <string>();

            try
            {
                if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
                {
                    return(AppResources.Erreur_LaissezAucunChampVide);
                }
                string websession = "";
                string noseq      = "";

                string url    = "https://system.pheidi.com";
                string domain = "system.pheidi.com";
                App.CurrentServer = new ServerInfo()
                {
                    Domain = domain, Address = url
                };



                var parameters = new Dictionary <string, string> {
                    { "pheidiaction", "complexAction" }, { "pheidiparams", "action**:**getWebSession**,**Username**:**" + username + "**,**Password**:**" + password + "**,**" }
                };
                HttpResponseMessage response = await PheidiNetworkManager.SendHttpRequestAsync(parameters, new TimeSpan(0, 0, 10), App.CurrentServer.GetDefaultUrl());

                if (response != null)
                {
                    if (response.StatusCode == HttpStatusCode.OK)
                    {
                        string rc = await response.Content.ReadAsStringAsync();

                        if (!string.IsNullOrEmpty(rc) && Utilities.IsNumeric(rc))
                        {
                            Debug.WriteLine(rc);
                            websession     = rc;
                            App.WebSession = new Cookie()
                            {
                                Name = "WEBSESSION", Domain = domain, Value = rc
                            };
                            App.CookieManager.AddCookie(App.WebSession);
                        }
                    }
                    else
                    {
                        return(AppResources.Erreur_ProblemeConnexionServeur);
                    }
                }
                else
                {
                    return(AppResources.Erreur_ProblemeConnexionServeur);
                }

                if (string.IsNullOrEmpty(websession))
                {
                    return(AppResources.Erreur_MauvaisEmailOuMdp);
                }
                parameters = new Dictionary <string, string>();
                parameters.Add("pheidiaction", "complexAction");
                parameters.Add("pheidiparams", "action**:**Get_UserNoseqWithWebSession**,**WES_A_WebSession**:**" + websession + "**,**");
                response = null;
                response = await SendHttpRequestAsync(parameters, new TimeSpan(0, 0, 30), App.CurrentServer.GetDefaultUrl());

                if (response != null)
                {
                    if (response.StatusCode == HttpStatusCode.OK)
                    {
                        var content = await response.Content.ReadAsStringAsync();

                        Debug.WriteLine("GET NOSEQ FOR WEBSESSION: " + content);
                        noseq = GetFields(content)[0]["WES_CON_A_NoSeq"].ToString();
                    }
                }

                if (string.IsNullOrEmpty(noseq))
                {
                    return(AppResources.Erreur_ProblemeConnexionServeur);
                }

                parameters = new Dictionary <string, string>();
                parameters.Add("pheidiaction", "complexAction");
                parameters.Add("pheidiparams", "action**:**Get_IpheidiServerList**,**CON_A_NoSeq**:**" + noseq + "**,**");
                response = null;
                response = await SendHttpRequestAsync(parameters, new TimeSpan(0, 0, 30), App.CurrentServer.GetDefaultUrl());

                if (response != null)
                {
                    if (response.StatusCode == HttpStatusCode.OK)
                    {
                        var content = await response.Content.ReadAsStringAsync();

                        Debug.WriteLine("GET SERVER LIST: " + content);
                        App.ServerInfoList = new List <ServerInfo>();
                        foreach (var fields in GetFields(content))
                        {
                            var server = new ServerInfo();
                            server.Address = fields["SEIN_A_ServerAddress"].ToString();
                            server.Name    = fields["SEIN_A_serverName"].ToString();
                            server.Noseq   = fields["SEIN_A_Noseq"].ToString();
                            server.Domain  = new Uri(server.Address).Host;
                            App.ServerInfoList.Add(server);
                            if (server.Noseq == App.ServerInfoNoseq)
                            {
                                App.CurrentServer = server;
                            }
                        }
                        if (App.CurrentServer == null)
                        {
                            App.ServerInfoNoseq = "";
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.Message);
                return(AppResources.Erreur_ProblemeConnexionServeur);
            }

            return(GoodResult);
        }
Exemple #13
0
        /// <summary>
        /// Gets the login page.
        /// </summary>
        public void GetLoginPage()
        {
            Credentials       = CredentialsManager.GetAllCredentials();
            SystemCredentials = CredentialsManager.GetSystemCredentials();
            var p1   = new SystemLoginPage();
            var page = new NavigationPage(p1);

            if (!string.IsNullOrEmpty(SystemCredentials.Key))
            {
                int    sysLoginCount    = 0;
                string sysLoginAnswer   = "";
                bool   sysLoginFinished = false;
                Task.Run(async() =>
                {
                    while (sysLoginAnswer != PheidiNetworkManager.GoodResult && sysLoginAnswer != AppResources.Erreur_MauvaisEmailOuMdp && sysLoginCount < 10)
                    {
                        sysLoginAnswer = await PheidiNetworkManager.SystemLogin(SystemCredentials.Value["Username"], SystemCredentials.Value["Password"]);
                        sysLoginCount++;
                    }
                    sysLoginFinished = true;
                });

                while (!sysLoginFinished)
                {
                    Task.Delay(500).Wait();
                }
                if (sysLoginAnswer == PheidiNetworkManager.GoodResult)
                {
                    Page p2 = new ServerLoginPage();
                    if (ServerInfoList.Count == 0)
                    {
                        MainPage = page;
                        NotificationManager.DisplayAlert(AppResources.Erreur_AucunServeur, AppResources.Erreur_Title, "OK", () => { });
                    }
                    else if (ServerInfoList.Count == 1)
                    {
                        bool   serverLoginFinished = false;
                        int    serverLoginCount    = 0;
                        string answer = "";
                        Task.Run(async() =>
                        {
                            if (Credentials.Any((arg) => arg.Value["SystemCredentialsNoseq"] == SystemCredentials.Key && arg.Value["ServerNoseq"] == ServerInfoNoseq))
                            {
                                var credentials = Credentials.First((arg) => arg.Value["SystemCredentialsNoseq"] == SystemCredentials.Key && arg.Value["ServerNoseq"] == ServerInfoList[0].Noseq);
                                answer          = await PheidiNetworkManager.UserLogin(credentials.Value["Username"], credentials.Value["Password"], false);
                                if (answer != PheidiNetworkManager.GoodResult)
                                {
                                    CredentialsManager.DeleteUser(credentials.Key);
                                }
                                else
                                {
                                    UserNoseq = credentials.Key;
                                }
                            }
                            else
                            {
                                while ((answer != PheidiNetworkManager.GoodResult && answer != AppResources.Erreur_MauvaisEmailOuMdp) && serverLoginCount < 10)
                                {
                                    answer = await PheidiNetworkManager.UserLogin(SystemCredentials.Value["Username"], SystemCredentials.Value["Password"], false);
                                    serverLoginCount++;
                                }

                                if (answer == PheidiNetworkManager.GoodResult)
                                {
                                    UserNoseq = SystemCredentials.Key;
                                }
                            }
                            serverLoginFinished = true;
                        });

                        while (!serverLoginFinished)
                        {
                            Task.Delay(500).Wait();
                        }

                        if (answer != PheidiNetworkManager.GoodResult)
                        {
                            page.Navigation.PushAsync(p2);
                            MainPage = page;
                        }
                        else if (answer == PheidiNetworkManager.GoodResult)
                        {
                            answer = string.Empty;
                            Task.Run(async() =>
                            {
                                answer = await PheidiNetworkManager.GetPMH();
                            });
                            while (string.IsNullOrEmpty(answer))
                            {
                                Task.Delay(500).Wait();
                            }
                            if (PMH.Count > 1)
                            {
                                Page p3 = new PmhPage();
                                page.Navigation.PushAsync(p3);
                                MainPage = page;
                            }
                            else
                            {
                                Instance.GetToApplication();
                            }
                        }
                    }
                    else
                    {
                        page.Navigation.PushAsync(p2);
                        MainPage = page;
                    }
                }
                else
                {
                    MainPage = page;
                }
            }
            else
            {
                MainPage = page;
                if (!Current.Properties.ContainsKey("DeviceIsPublic"))
                {
                    string        message   = AppResources.Alerte_SeulUsagerAppareil_Message;
                    string        title     = AppResources.Alerte_SeulUsagerAppareil_Title;
                    string        confirm   = AppResources.Oui;
                    string        cancel    = AppResources.Non;
                    System.Action onConfirm = () => { DeviceIsShared = false; };
                    System.Action onCancel  = () => { DeviceIsShared = true; };
                    NotificationManager.DisplayAlert(message, title, confirm, cancel, onConfirm, onCancel);
                }
            }
        }
Exemple #14
0
        /// <summary>
        /// Gets the geofence from server.
        /// </summary>
        /// <returns><c>true</c>, if geofence from server was gotten, <c>false</c> otherwise.</returns>
        public async Task <bool> GetGeofenceUpdateFromServer()
        {
            if (!Application.Current.Properties.ContainsKey("LastGeofenceSync"))
            {
                Application.Current.Properties["LastGeofenceSync"] = "2000-01-01 00:00:00";
            }
            var parameters = new Dictionary <string, string> {
                { "pheidiaction", "complexaction" }, { "pheidiparams", "action**:**GetGeofenceUpdate**,**Last_Update_Date**:**" + Application.Current.Properties["LastGeofenceSync"] + "**,**" }
            };
            HttpResponseMessage response = PheidiNetworkManager.SendHttpRequestAsync(parameters, new TimeSpan(0, 0, 30)).Result;

            if (response != null)
            {
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    string responseContent = response.Content.ReadAsStringAsync().Result;
                    Debug.WriteLine("Reponse:" + responseContent);
                    try
                    {
                        if (Geofences == null)
                        {
                            GetGeofenceFromDatabase();
                        }
                        List <Geofence> list = new List <Geofence>();
                        var             geo  = new Geofence();
                        try
                        {
                            var fields = PheidiNetworkManager.GetFields(responseContent);
                            foreach (var field in fields)
                            {
                                geo = new Geofence();

                                geo.NoSeq = field.ContainsKey("GEO_A_NoSeq") ? field["GEO_A_NoSeq"]?.ToString() : string.Empty;

                                geo.EnterActionName = field.ContainsKey("GAR_ACO_A_Action_EnterAction") ? field["GAR_ACO_A_Action_EnterAction"]?.ToString() : string.Empty;

                                geo.ExitActionName = field.ContainsKey("GAR_ACO_A_Action_ExitAction") ? field["GAR_ACO_A_Action_ExitAction"]?.ToString() : string.Empty;

                                geo.Name = field.ContainsKey("GEO_A_Name") ? field["GEO_A_Name"]?.ToString() : string.Empty;

                                geo.DeleteFlag = field.ContainsKey("GEO_B_DeleteFlag") ? (bool.Parse(field["GEO_B_DeleteFlag"]?.ToString() ?? false.ToString()) ? 1 : 0) : 0;

                                geo.CreationDate = field.ContainsKey("GEO_S_CrDate") ? DateTime.Parse(field["GEO_S_CrDate"]?.ToString()) : DateTime.Now;

                                geo.LastModification = field.ContainsKey("GEO_S_LastModDate") ? DateTime.Parse(field["GEO_S_LastModDate"]?.ToString()) : DateTime.Now;

                                geo.Latitude = field.ContainsKey("GEO_N_Latitude") ? double.Parse(field["GEO_N_Latitude"]?.ToString()) : 0;

                                geo.Longitude = field.ContainsKey("GEO_N_Longitude") ? double.Parse(field["GEO_N_Longitude"]?.ToString()) : 0;

                                geo.NotificationEnabled = field.ContainsKey("GAR_B_NotificationFlag") ? bool.Parse(field["GAR_B_NotificationFlag"]?.ToString() ?? false.ToString()) : true;

                                geo.PublicFlag = field.ContainsKey("GEO_B_PublicFlag") ? bool.Parse(field["GEO_B_PublicFlag"]?.ToString() ?? false.ToString()) ? 1 : 0 : 0;

                                geo.Radius = field.ContainsKey("GEO_N_Radius") ? double.Parse(field["GEO_N_Radius"]?.ToString()) : ApplicationConst.DefaultGeofenceRadius;

                                geo.ServerNoseq = App.ServerInfoNoseq;

                                geo.User = App.UserNoseq;

                                list.Add(geo);
                            }
                            Debug.WriteLine("List Generated");
                        }
                        catch (Exception e)
                        {
                            Debug.WriteLine("GetGeofenceUpdate - Creating List: " + e.Message);
                        }
                        List <Geofence> toRemove = new List <Geofence>();
                        foreach (var geofence in list)
                        {
                            try
                            {
                                if (Geofences.Any(g => g.NoSeq == geofence.NoSeq))
                                {
                                    //Delete la copie local si celle au serveur à déjà été supprimée.
                                    if (geofence.DeleteFlag == 1)
                                    {
                                        var data = await DatabaseHelper.Database.GetItem <Geofence>(geofence.NoSeq);

                                        await DatabaseHelper.Database.DeleteItemAsync <Geofence>(data);

                                        toRemove.Add(geofence);
                                    }
                                    //Update la copie local pour correspondre à celle du serveur.
                                    else
                                    {
                                        var data = Geofences.First(g => g.NoSeq == geofence.NoSeq);
                                        data.DeleteFlag          = geofence.DeleteFlag;
                                        data.Latitude            = geofence.Latitude;
                                        data.Longitude           = geofence.Longitude;
                                        data.Name                = geofence.Name;
                                        data.Radius              = geofence.Radius;
                                        data.LastModification    = DateTime.Now;
                                        data.EnterActionName     = geofence.EnterActionName;
                                        data.ExitActionName      = geofence.ExitActionName;
                                        data.NotificationEnabled = geofence.NotificationEnabled;
                                        await DatabaseHelper.Database.UpdateItem(data);
                                    }
                                }
                                else
                                {
                                    //Ajoute une nouvelle geofence si la copie locale n'existe pas.
                                    if (geofence.DeleteFlag == 0)
                                    {
                                        await DatabaseHelper.Database.SaveItemAsync(geofence);
                                    }
                                }
                            }
                            catch (Exception e)
                            {
                                Debug.WriteLine("GetGeofenceUpdate - Updating geofence: " + e.Message);
                            }
                        }
                        Device.BeginInvokeOnMainThread(() =>
                        {
                            foreach (var geofence in toRemove)
                            {
                                try
                                {
                                    Geofences.Remove(Geofences.FirstOrDefault((arg) => arg.NoSeq == geofence.NoSeq));
                                }
                                catch (Exception e)
                                {
                                    Debug.WriteLine("GetGeofenceUpdate - Removing deleted: " + e.Message);
                                }
                            }
                        });

                        Application.Current.Properties["LastGeofenceSync"] = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                        Debug.WriteLine("Geofence: Synch done");
                        await Application.Current.SavePropertiesAsync();

                        return(true);
                    }
                    catch (Exception e)
                    {
                        Debug.WriteLine("GetGeofenceUpdate: " + e.Message);
                    }
                }
            }
            return(false);
        }
Exemple #15
0
        public SystemLoginPage()
        {
            //Cache la nav bar
            NavigationPage.SetHasNavigationBar(this, false);
            InitializeComponent();

            //Bouton de login
            btnLogin.Clicked += (sender, e) =>
            {
                Task.Run(async() =>
                {
                    Device.BeginInvokeOnMainThread(() => AppLoadingView.SetVisibility(true));
                    string answer = await PheidiNetworkManager.SystemLogin(usernameEntry.Text, passwordEntry.Text);
                    if (answer == PheidiNetworkManager.GoodResult)
                    {
                        App.CredentialsManager.DeleteSystemCredentials();
                        App.CredentialsManager.SaveSystemCredentials(usernameEntry.Text, passwordEntry.Text);
                        DatabaseHelper.Database.DropTable <Geofence>();
                        DatabaseHelper.Database.CreateTable <Geofence>();
                        Device.BeginInvokeOnMainThread(App.Instance.GetLoginPage);
                    }
                    else
                    {
                        App.NotificationManager.DisplayAlert(answer, AppResources.Erreur_Title, "OK", () => { });
                    }
                    Device.BeginInvokeOnMainThread(() => AppLoadingView.SetVisibility(false));
                });
            };



            usernameEntry.Placeholder = AppResources.CourrielPlaceHolder;
            passwordEntry.Placeholder = AppResources.MotDePassePlaceHolder;
            btnLogin.Text             = AppResources.ConnexionBouton;

            var systemAccount = App.CredentialsManager.GetSystemCredentials();

            SetEntryLayoutVisibility(string.IsNullOrEmpty(systemAccount.Key));
            if (systemAccount.Value != null)
            {
                btnCurrentAccount.Text = systemAccount.Value["Username"];
            }
            btnCurrentAccount.BackgroundColor = App.ColorPrimary;
            btnCurrentAccount.TextColor       = Color.White;
            //btnCurrentAccount.BorderColor = App.ColorPrimary;
            btnCurrentAccount.Clicked += (sender, e) =>
            {
                Task.Run(async() =>
                {
                    Device.BeginInvokeOnMainThread(() => AppLoadingView.SetVisibility(true));
                    int count       = 0;
                    string answer   = "";
                    var credentials = App.CredentialsManager.GetSystemCredentials();
                    while (answer != PheidiNetworkManager.GoodResult && answer != AppResources.Erreur_MauvaisEmailOuMdp && count < 5)
                    {
                        answer = await PheidiNetworkManager.SystemLogin(credentials.Value["Username"], credentials.Value["Password"]);
                        count++;
                    }
                    if (answer == PheidiNetworkManager.GoodResult)
                    {
                        Device.BeginInvokeOnMainThread(App.Instance.GetLoginPage);
                    }
                    else
                    {
                        if (answer == AppResources.Erreur_MauvaisEmailOuMdp)
                        {
                            Device.BeginInvokeOnMainThread(() => updateEntryLayout.IsVisible = true);
                        }
                        App.NotificationManager.DisplayAlert(answer, AppResources.Erreur_Title, "OK", () => { });
                    }
                    Device.BeginInvokeOnMainThread(() => AppLoadingView.SetVisibility(false));
                });
            };

            btnOtherAccount.TextColor       = App.ColorPrimary;
            btnOtherAccount.BorderColor     = App.ColorPrimary;
            btnOtherAccount.BackgroundColor = Color.White;
            btnOtherAccount.Text            = AppResources.AutreCompteBouton;
            btnOtherAccount.Clicked        += (sender, e) =>
            {
                SetEntryLayoutVisibility(true);
            };

            btnBackToMainAccount.IsVisible       = !string.IsNullOrEmpty(systemAccount.Key);
            btnBackToMainAccount.TextColor       = App.ColorPrimary;
            btnBackToMainAccount.BorderColor     = App.ColorPrimary;
            btnBackToMainAccount.BackgroundColor = Color.White;
            btnBackToMainAccount.Text            = AppResources.RetourBouton;
            btnBackToMainAccount.Clicked        += (sender, e) =>
            {
                SetEntryLayoutVisibility(false);
            };

            demiCercle.Foreground = App.ColorPrimary;

            updateUsernameEntry.Placeholder = AppResources.CourrielPlaceHolder;
            updatePasswordEntry.Placeholder = AppResources.MotDePassePlaceHolder;
            btnUpdateLogin.Text             = AppResources.ConnexionBouton;
            //Bouton de login
            btnUpdateLogin.FontSize = Device.GetNamedSize(NamedSize.Large, typeof(Button));
            btnUpdateLogin.Clicked += (sender, e) =>
            {
                Task.Run(async() =>
                {
                    Device.BeginInvokeOnMainThread(() => AppLoadingView.SetVisibility(true));
                    string answer = await PheidiNetworkManager.SystemLogin(updateUsernameEntry.Text, updatePasswordEntry.Text);
                    if (answer == PheidiNetworkManager.GoodResult)
                    {
                        var credentials = App.CredentialsManager.GetSystemCredentials();
                        credentials.Value["Password"] = updatePasswordEntry.Text;
                        credentials.Value["Username"] = updateUsernameEntry.Text;
                        App.CredentialsManager.UpdateSystemCredentials(credentials);
                        Device.BeginInvokeOnMainThread(App.Instance.GetLoginPage);
                    }
                    else
                    {
                        App.NotificationManager.DisplayAlert(answer, AppResources.Erreur_Title, "OK", () => { });
                    }
                    Device.BeginInvokeOnMainThread(() => AppLoadingView.SetVisibility(false));
                });
            };

            SetFooter();
            mainLayout.RaiseChild(AppLoadingView);
            AppLoadingView.SetVisibility(false);
        }
        public LoginPage(bool secondePage)
        {
            firstPageExist = !secondePage;
            Debug.WriteLine("LoginPage: ctor");
            var watch = Stopwatch.StartNew();

            //Cache la nav bar
            NavigationPage.SetHasNavigationBar(this, false);
            InitializeComponent();
            Debug.WriteLine("Initialize: " + watch.Elapsed.Milliseconds);
            IsInSecondPage = secondePage;

            Debug.WriteLine("Setting Android: " + watch.Elapsed.Milliseconds);
            //Setting pour Android.
            if (Device.RuntimePlatform == Device.Android)
            {
                btnOtherAccount.BackgroundColor = Color.Transparent;
                btnOtherAccount.BorderColor     = Color.Transparent;
            }
            btnOtherAccount.TextColor    = App.ColorPrimary;
            btnBackToFirstPage.TextColor = App.ColorPrimary;
            btnBackToFirstPage.Clicked  += (sender, e) => OnBackButtonPressed();
            btnBackToFirstPage.IsVisible = false;
            Debug.WriteLine("Btn login: "******"Problème de connexion", s, "OK"));
                        }
                    });
                });
            };

            Debug.WriteLine("Entry visible: " + watch.Elapsed.Milliseconds);
            EntriesVisible(secondePage);

            Debug.WriteLine("Url Picker: " + watch.Elapsed.Milliseconds);
            //Url Picker
            urlPicker.IsEnabled = secondePage;
            foreach (var server in App.ServerInfoList)
            {
                urlPicker.Items.Add(server.Domain);
            }

            urlPicker.Title = "Sélectionnez une adresse";
            urlPicker.SelectedIndexChanged += (sender, e) =>
            {
                string item = urlPicker.SelectedItem.ToString();
                App.CurrentServer   = App.ServerInfoList.First(sein => sein.Domain == item);
                App.ServerInfoNoseq = App.CurrentServer.Noseq;
            };
            if (App.CurrentServer != null)
            {
                urlPicker.SelectedIndex = urlPicker.Items.IndexOf(App.CurrentServer.Domain);
            }

            Debug.WriteLine("User Picker: " + watch.Elapsed.Milliseconds);
            //User picker
            if (App.Credentials.Count > 0 && !secondePage)
            {
                foreach (var account in App.Credentials)
                {
                    if (account.Value.ContainsKey("Username") && account.Value.ContainsKey("ServerNoseq"))
                    {
                        if (App.ServerInfoList.Any((arg) => account.Value["ServerNoseq"] == arg.Noseq))
                        {
                            userPicker.Items.Add(account.Value["Username"] + " (" + App.ServerInfoList.First((arg) => account.Value["ServerNoseq"] == arg.Noseq).Domain + ")");
                        }
                    }
                }
                if (userPicker.Items.Count == 0)
                {
                    App.CredentialsManager.DeleteCredentials();
                    Device.BeginInvokeOnMainThread(App.Instance.GetLoginPage);
                }
                userPicker.SelectedIndexChanged += (sender, e) =>
                {
                    if (userPicker.SelectedIndex >= 0)
                    {
                        lastUserIndex = userPicker.SelectedIndex;
                        string account = userPicker.Items[userPicker.SelectedIndex];
                        if (App.Credentials.Any((arg) => account == arg.Value["Username"] + " (" + App.ServerInfoList.First((si) => si.Noseq == arg.Value["ServerNoseq"]).Domain + ")"))
                        {
                            var user = App.Credentials.First((arg) => account == arg.Value["Username"] + " (" + App.ServerInfoList.First((si) => si.Noseq == arg.Value["ServerNoseq"]).Domain + ")");
                            App.UserNoseq           = user.Key;
                            App.ServerInfoNoseq     = user.Value["ServerNoseq"];
                            App.CurrentServer       = App.ServerInfoList.First((arg) => arg.Noseq == App.ServerInfoNoseq);
                            usernameEntry.Text      = user.Value["Username"];
                            passwordEntry.Text      = user.Value["Password"];
                            urlPicker.SelectedIndex = urlPicker.Items.IndexOf(App.CurrentServer.Domain);
                        }
                    }
                };
                userPicker.SelectedIndex = string.IsNullOrEmpty(App.UserNoseq) || App.CurrentServer == null ? 0 : App.Credentials.ContainsKey(App.UserNoseq) ? userPicker.Items.IndexOf(App.Credentials[App.UserNoseq]["Username"] + " (" + App.CurrentServer.Domain + ")") : 0;
            }

            usernameEntry.Placeholder = AppResources.CourrielPlaceHolder;
            lblCourriel.Text          = AppResources.CourrielLabel;
            passwordEntry.Placeholder = AppResources.MotDePassePlaceHolder;
            lblPassword.Text          = AppResources.MotDePasseLabel;
            lblRemember.Text          = AppResources.MemoriserLabel;
            btnLogin.Text             = AppResources.ConnexionBouton;
            btnOtherAccount.Text      = AppResources.AutreCompteBouton;
            btnBackToFirstPage.Text   = AppResources.RetourBouton;

            SetFooter();
            mainLayout.RaiseChild(AppLoadingView);
            AppLoadingView.SetVisibility(false);
            Debug.WriteLine("TOTAL: " + watch.Elapsed.Milliseconds);
        }