private void UpdateLocalProfileInfo(ApiPlainClientProfile newValue)
        {
            var oldDate = ProfileViewModel.GetInstance().MyClient.Afiliado;


            ImageSource profileImage = null;

            if (this.ProfileImageBytes.Length != 0)
            {
                profileImage = ImageSource.FromStream(() => new MemoryStream(this.ProfileImageBytes));
            }

            ProfileViewModel.GetInstance().NombreApellido = $"{newValue.PrimerNombre} {newValue.Apellido}";

            ProfileViewModel.GetInstance().MyClient = new ClientProfile()
            {
                PrimerNombre    = newValue.PrimerNombre,
                SegundoNombre   = newValue.SegundoNombre,
                Apellido        = newValue.Apellido,
                SegundoApellido = newValue.SegundoApellido,
                Email           = newValue.Email,
                ProfileImage    = profileImage,
                Afiliado        = oldDate.Date
            };

            var tmpC = ProfileViewModel.GetInstance().MyClient;

            try
            {
                var r = Realm.GetInstance();
                r.Write(() => {
                    r.Add <RmbClientProfile>(new RmbClientProfile()
                    {
                        ID              = Settings.ClientUID,
                        PrimerNombre    = tmpC.PrimerNombre,
                        ProfilePhoto    = this.ProfileImageBytes,
                        SegundoNombre   = tmpC.SegundoNombre,
                        Apellido        = tmpC.Apellido,
                        SegundoApellido = tmpC.SegundoApellido,
                        Email           = tmpC.Email,
                        Afiliado        = tmpC.Afiliado.Date
                    }, update: true);
                });
            }
            catch (Exception ex)
            {
                UpdateProfileViewModel.CustomizedToast(Android.Graphics.Color.White, Android.Graphics.Color.Black,
                                                       ex.Message, ToastLength.Long, iconResource: "error64", textSize: 16);
            }
        }
Example #2
0
        public ProfileViewModel()
        {
            //Obtencion de datos del perfil
            ApiPlainClientProfile profileInf = LoginViewModel.GetInstance().ClientProfile;

            if (profileInf != null)
            {
                LocalCharge = Convert.FromBase64String(Convert.ToString(profileInf.PP));
                ImageSource profileImage;
                profileImage = FromBytesToImageSource(LocalCharge);



                MyClient = new ClientProfile()
                {
                    ProfileImage    = profileImage,
                    Apellido        = profileInf.Apellido,
                    PrimerNombre    = profileInf.PrimerNombre,
                    SegundoNombre   = profileInf.SegundoNombre,
                    SegundoApellido = profileInf.SegundoApellido,
                    Email           = profileInf.Email,
                    Afiliado        = profileInf.Afiliado
                };

                this.NombreApellido = $"{MyClient.PrimerNombre} {MyClient.Apellido}";

                this.LogOutCommand = new Command(LogOutCommandExecute);

                _instance = this;
            }
            else
            {
                //Datos locales
                //Consulta a Realm
                var r          = Realm.GetInstance();
                var realmQuery = r.All <RmbClientProfile>().First <RmbClientProfile>();
                LocalCharge = realmQuery.ProfilePhoto;
                ImageSource profileImageSource = FromBytesToImageSource(LocalCharge);

                //Seteando datos del perfil
                this.MyClient = new ClientProfile()
                {
                    ProfileImage    = profileImageSource,
                    Afiliado        = realmQuery.Afiliado.Date,
                    Apellido        = realmQuery.Apellido,
                    SegundoApellido = realmQuery.SegundoApellido,
                    Email           = realmQuery.Email,
                    PrimerNombre    = realmQuery.PrimerNombre,
                    SegundoNombre   = realmQuery.SegundoNombre,
                };

                this.NombreApellido = $"{MyClient.PrimerNombre} {MyClient.Apellido}";

                this.LogOutCommand = new Command(LogOutCommandExecute);

                _instance = this;
            }
            //Cargando pantalla de actualizacion
            UpdateProfileViewModel.GetInstance().Nombres = $"{MyClient.PrimerNombre} {MyClient.SegundoNombre}";
            UpdateProfileViewModel.GetInstance().Apellidos = $"{MyClient.Apellido} {MyClient.SegundoApellido}";
            UpdateProfileViewModel.GetInstance().Profile.Email = $"{MyClient.Email}";
            UpdateProfileViewModel.GetInstance().Profile.ProfileImage = FromBytesToImageSource(LocalCharge);
        }
        public async void UpdateCommandExecute()
        {
            bool updateCredentials = false;
            RestServiceConsumer service;

            SetActivity(true);
            //Conexion
            service = new RestServiceConsumer();
            var response = await service.CheckConnection();

            if (!response.IsSuccesFull)
            {
                SetActivity(false);
                //No hay conexion
                CustomizedToast(Android.Graphics.Color.White, Android.Graphics.Color.Black,
                                response.Message, iconResource: "error64", textSize: 16);
                return;
            }
            try
            {
                //Chequeo de vacios
                if (!AllDataChecker())
                {
                    //Faltan datos
                    SetActivity(false);
                    CustomizedToast(Android.Graphics.Color.White, Android.Graphics.Color.Black,
                                    Languages.AllDataNeeded, iconResource: "error64", textSize: 16);
                    return;
                }

                if (!NameChecker(this.Nombres.TrimEnd(' ')) || !NameChecker(this.Apellidos.TrimEnd(' ')))
                {
                    SetActivity(false);
                    //Los nombres o apellidos no han sido bien escritos}
                    if (!NameChecker(this.Nombres.TrimEnd(' ')))
                    {
                        CustomizedToast(Android.Graphics.Color.White, Android.Graphics.Color.Black,
                                        Languages.WronWGNames, iconResource: "error64", textSize: 16);
                    }
                    else
                    {
                        CustomizedToast(Android.Graphics.Color.White, Android.Graphics.Color.Black,
                                        Languages.WronWGivenNames, iconResource: "error64", textSize: 16);
                    }
                    return;
                }

                //Chequeo de password correcto
                if (Settings.SuccesfullPassword != this.OldPassword)
                {
                    SetActivity(false);
                    //No coinciden las contraseñas
                    CustomizedToast(Android.Graphics.Color.White, Android.Graphics.Color.Black,
                                    Languages.PasswordsDontMatch, iconResource: "error64", textSize: 16);
                    return;
                }

                //Se quiere actualizar algo de la seccion de credenciales?
                if (!this.NewPassword.Equals(string.Empty) || !this.RepeatPassword.Equals(string.Empty))
                {
                    //Todos los datos fueron proporcionados?
                    if (NewPassword.Equals(string.Empty) || RepeatPassword.Equals(string.Empty))
                    {
                        SetActivity(false);
                        CustomizedToast(Android.Graphics.Color.White, Android.Graphics.Color.Black,
                                        Languages.AllDataNeeded, iconResource: "error64", textSize: 16);
                        return;
                    }
                    //Chequeo de repeticion de nueva contraseña
                    if (this.NewPassword != this.RepeatPassword)
                    {
                        SetActivity(false);
                        //No coinciden las contraseñas
                        CustomizedToast(Android.Graphics.Color.White, Android.Graphics.Color.Black,
                                        Languages.PasswordsShouldMatch, iconResource: "error64", textSize: 16);
                        return;
                    }
                    else
                    {
                        updateCredentials = true;
                    }
                }


                //Creacion del modelo a enviar
                Stream streamedImage = GetImageSourceStream(this.Profile.ProfileImage);
                this.ProfileImageBytes = StreamToByteArray(streamedImage);


                var token = Settings.SerializedToken;

                var posted = new ApiPlainClientProfile()
                {
                    ID              = Settings.ClientUID,
                    PrimerNombre    = this.Nombres.Split(' ')[0],
                    SegundoNombre   = this.Nombres.Split(' ')[1],
                    Apellido        = this.Apellidos.Split(' ')[0],
                    SegundoApellido = this.Apellidos.Split(' ')[1],
                    Email           = this.Profile.Email,
                    PP              = this.ProfileImageBytes,
                    Afiliado        = DateTime.Now
                };

                var posted2 = new ApiClientCredentials()
                {
                    IdClient  = -1,
                    IdPersona = posted.ID,
                    Password  = this.NewPassword,
                    UserName  = "******"
                };

                Response result2 = null;
                var      result  = await service.Put <ApiPlainClientProfile>(Constantes.BASEURL, Constantes.CLIENTPREFIX, Constantes.CLIENTUPDATEPROFILE, posted, token);

                if (updateCredentials)
                {
                    result2 = await service.Put <ApiClientCredentials>(Constantes.BASEURL, Constantes.CLIENTPREFIX, Constantes.CLIENTUPDATECREDENTIALS, posted2, token);
                }

                if (updateCredentials)
                {
                    if (!result.IsSuccesFull || !result2.IsSuccesFull)
                    {
                        SetActivity(false);
                        //Error en la peticion
                        if (!result.IsSuccesFull)
                        {
                            CustomizedToast(Android.Graphics.Color.White, Android.Graphics.Color.Black,
                                            result.Message, iconResource: "error64", textSize: 16);
                            SetActivity(false);
                            return;
                        }
                        else
                        {
                            CustomizedToast(Android.Graphics.Color.White, Android.Graphics.Color.Black,
                                            result2.Message, iconResource: "error64", textSize: 16);
                        }
                        SetActivity(false);
                        return;
                    }
                    Settings.SuccesfullPassword = this.NewPassword;
                }
                else
                {
                    if (!result.IsSuccesFull)
                    {
                        CustomizedToast(Android.Graphics.Color.White, Android.Graphics.Color.Black,
                                        result.Message, iconResource: "error64", textSize: 16);
                        SetActivity(false);
                        return;
                    }
                }

                SetActivity(false);
                CustomizedToast(Android.Graphics.Color.White, Android.Graphics.Color.Black,
                                Languages.UpdatedProfile, iconResource: "ok96", textSize: 16);
                UpdateLocalProfileInfo(posted);
            }
            catch (Exception ex)
            {
                CustomizedToast(Android.Graphics.Color.White, Android.Graphics.Color.Black,
                                ex.Message, iconResource: "error64", textSize: 16);
                SetActivity(false);
                throw ex;
            }
        }
Example #4
0
        public async void LoginCommandExecute()
        {
            await Device.InvokeOnMainThreadAsync(() => {
                this.IsBusy    = true;
                this.IsEnabled = false;
            });

            /*Logueandome y obteniendo un token*/
            if (userLogin.password != null && userLogin.userName != null)
            {
                proc = new RestServiceConsumer();
                var controllerString = $"{Constantes.LOGINAUTH}{Constantes.LOGINAUTHUSERPAR}={userLogin.userName}&{Constantes.LOGINAUTHPASSPAR}={userLogin.password}";
                var response         = await proc.Get <string>(Constantes.BASEURL, Constantes.LOGINPREFIX, controllerString);

                if (!response.IsSuccesFull)
                {
                    //Errores en la respuesta
                    if (response.Result == null)
                    {
                        await Device.InvokeOnMainThreadAsync(() => {
                            this.IsBusy    = false;
                            this.IsEnabled = true;
                        });

                        await Application.Current.MainPage.DisplayAlert("Error!", "Credenciales incorrectas", "OK");

                        return;
                    }
                    //Manejo de otros errores
                    await Device.InvokeOnMainThreadAsync(() => {
                        this.IsBusy    = false;
                        this.IsEnabled = true;
                    });

                    await Application.Current.MainPage.DisplayAlert("Error!", response.Message, "OK");

                    return;
                }
                //Settings
                Settings.SerializedToken = Convert.ToString(response.Result);
                Settings.IsRemembered    = RememberMe;


                //Informacion de perfil
                var profileControllerString = $"{Constantes.CLIENTPROFILE}{Constantes.LOGINAUTHUSERPAR}={userLogin.userName}&{Constantes.LOGINAUTHPASSPAR}={userLogin.password}";
                var profileResponse         = await proc.Get <ApiPlainClientProfile>(Constantes.BASEURL, Constantes.CLIENTPREFIX, profileControllerString, Settings.SerializedToken);

                if (!profileResponse.IsSuccesFull)
                {
                    await Device.InvokeOnMainThreadAsync(() => {
                        this.IsBusy    = false;
                        this.IsEnabled = true;
                    });

                    await Application.Current.MainPage.DisplayAlert("Error!", response.Message, "OK");

                    return;
                }

                ApiPlainClientProfile profileInfo = (ApiPlainClientProfile)profileResponse.Result;
                this.ClientProfile = profileInfo;



                #region Carga de datos a otros ViewModels
                var         profileImageBytes = Convert.FromBase64String(profileInfo.PP.ToString());
                ImageSource profileImage;
                if (profileImageBytes.Length != 0)
                {
                    profileImage = ImageSource.FromStream(() => new MemoryStream(profileImageBytes));
                }
                else
                {
                    profileImage = ImageSource.FromFile("userF.png");
                }
                #endregion

                //Control de recuerdos
                if (Settings.IsRemembered)
                {
                    //Cargar perfil a BD local
                    var r = Realm.GetInstance();
                    try {
                        r.Write(() => {
                            r.Add(new RmbClientProfile()
                            {
                                ID              = profileInfo.ID,
                                ProfilePhoto    = profileImageBytes,
                                Afiliado        = profileInfo.Afiliado,
                                Apellido        = profileInfo.Apellido,
                                SegundoApellido = profileInfo.SegundoApellido,
                                Email           = profileInfo.Email,
                                PrimerNombre    = profileInfo.PrimerNombre,
                                SegundoNombre   = profileInfo.SegundoNombre,
                            });
                        });
                    }
                    catch (Exception ex) {
                        UpdateProfileViewModel.CustomizedToast(Android.Graphics.Color.White, Android.Graphics.Color.Black,
                                                               ex.Message, ToastLength.Long, iconResource: "error64", textSize: 16);
                    }
                }



                //Settings
                Settings.FullName           = $"{profileInfo.PrimerNombre} {profileInfo.SegundoNombre} {profileInfo.Apellido} {profileInfo.SegundoApellido}";
                Settings.ClientUID          = profileInfo.ID;
                Settings.SuccesfullPassword = userLogin.password;

                await Device.InvokeOnMainThreadAsync(() => {
                    this.IsBusy    = false;
                    this.IsEnabled = true;
                });

                //Navegacion a la pagina Root bloqueando el regreso al Login
                Application.Current.MainPage = new RootHomePage();
            }
            else
            {
                await Device.InvokeOnMainThreadAsync(() => {
                    this.IsBusy    = false;
                    this.IsEnabled = true;
                });

                await Application.Current.MainPage.DisplayAlert("Error!", "Todos los datos son obligatorios", "OK");
            }
        }