Ejemplo n.º 1
0
        private void ConvertPropertyNamesToCamelCase(ValidatorRules validatorRules)
        {
            // Workaround as System.Text.Json in ASP.NET 3 cannot serialise property keys.
            // Although unnecessary for ASP.NET Core 2.2, it's too expensive to check!
            var newValidatorList = new SerialisableDictionary <string, SerialisableDictionary <string, object> >();

            foreach (var item in validatorRules.ValidatorList)
            {
                newValidatorList.Add(item.Key.ToCamelCase(), validatorRules.ValidatorList[item.Key]);
            }

            var newErrorList = new SerialisableDictionary <string, SerialisableDictionary <string, string> >();

            foreach (var item in validatorRules.ErrorList)
            {
                newErrorList.Add(item.Key.ToCamelCase(), validatorRules.ErrorList[item.Key]);
            }

            var newTypeList = new SerialisableDictionary <string, string>();

            foreach (var item in validatorRules.TypeList)
            {
                newTypeList.Add(item.Key.ToCamelCase(), validatorRules.TypeList[item.Key]);
            }

            validatorRules.ValidatorList = newValidatorList;
            validatorRules.ErrorList     = newErrorList;
            validatorRules.TypeList      = newTypeList;
        }
Ejemplo n.º 2
0
        public async Task <IActionResult> GetLicencePro(CardViewModel cardViewModel)
        {
            var checkingCard = new PaymentCard()
            {
                CardNumber = cardViewModel.cardNumber,
                Cvc        = cardViewModel.CVc,
                HolderName = cardViewModel.Holdername,
                Month      = cardViewModel.MM,
                Year       = cardViewModel.YY,
            };

            Validator creditcardValidator = new Validator(ValidatorRules.CreditCardCheckerRule(checkingCard));

            if (!creditcardValidator.HasError)
            {
                try
                {
                    //Obtenemos informacion validada de la tarjeta del nuevo usuario administrador.
                    PaymentCard = new PaymentCard()
                    {
                        CardNumber = cardViewModel.cardNumber,
                        Cvc        = cardViewModel.CVc,
                        HolderName = cardViewModel.Holdername,
                        Month      = cardViewModel.MM,
                        Year       = cardViewModel.YY
                    };


                    //Creamos un el token para la tarjeta
                    StripePaymentCardResult = await StripeServiceDS.CreateCardToken(PaymentCard);

                    //Verficamos si hay algun error en la tarjeta
                    if (!StripePaymentCardResult.HasError)
                    {
                        return(RedirectToAction("UserRegistration"));
                    }
                    else
                    {
                        ViewBag.CardError = "Some error have ocurred." + "\r Check:" + StripePaymentCardResult.ErrorMsg;

                        return(View());
                    }
                }
                catch (Exception)
                {
                    throw;
                }
            }
            else
            {
                if (creditcardValidator.ErrorMessage != "Values are empty.")
                {
                    ViewBag.CardError = "Some error have ocurred." + "\r Check:" + creditcardValidator.ErrorMessage;
                }
                return(View());
            }
        }
Ejemplo n.º 3
0
        public void IsValidShouldReturnsTrueIfThereAreNoRules()
        {
            var myField = -1;
            var v       = new ValidatorRules();

            var actual = v.IsValid(nameof(myField), myField);

            Assert.That(actual, Is.True);
        }
        /// <summary>Instantiates an instance of the <see cref="ValidatorRules"/> class.</summary>
        /// <returns>Instance of <see cref="ValidatorRules"/>.</returns>
        public ValidatorRules GetValidatorRules()
        {
            this.rules = new ValidatorRules();
            foreach (var member in this.validatorDescriptor?.GetMembersWithValidators())
            {
                this.AddRulesForMember(this.validatorDescriptor, member.Key);
            }

            this.AddPropertyTypes(this.ModelType);

            return(this.rules);
        }
        void SetValidatorValues(string _fullname, string _email, string _phone, string _address, string _gender)
        {
            FullNameValidator = ValidatorRules.EmptyOrNullValueRule(_fullname);
            EmailValidator    = ValidatorRules.EmptyOrNullValueRule(_email);

            if (!EmailValidator.HasError)
            {
                EmailPatternValidator = ValidatorRules.EmailPatternRule(_email);
            }
            PhoneValidator  = ValidatorRules.EmptyOrNullValueRule(_phone);
            AddresValidator = ValidatorRules.EmptyOrNullValueRule(_address);
            GenderValidator = ValidatorRules.EmptyOrNullValueRule(_gender);
        }
Ejemplo n.º 6
0
        public void IsValidShouldReturnsRuleOneTime()
        {
            var myField = -1;
            var v       = new ValidatorRules();

            var rule = new Mock <IValidatorRule>();

            v.AddRule(nameof(myField), rule.Object);

            v.IsValid(nameof(myField), myField);

            rule.Verify(s => s.IsValid(It.IsAny <object>()), Times.Once);
        }
Ejemplo n.º 7
0
        public void AddRuleIncorrectShouldReturnException()
        {
            var myField = 400000000;
            var v       = new ValidatorRules();

            var rule = new Mock <IValidatorRule>();

            rule.Setup(s => s.IsValid(myField)).Throws <StackOverflowException>();

            v.AddRule(nameof(myField), rule.Object);

            void del() => v.IsValid(nameof(myField), myField);

            Assert.Throws <StackOverflowException>(del);
        }
Ejemplo n.º 8
0
        public void IsValidShouldReturnsTrueIfRuleIsValid()
        {
            var myField = -1;
            var v       = new ValidatorRules();

            var rule = new Mock <IValidatorRule>();

            rule.Setup(s => s.IsValid(myField)).Returns(true);

            v.AddRule(nameof(myField), rule.Object);

            var actual = v.IsValid(nameof(myField), myField);

            Assert.That(actual, Is.True);
        }
Ejemplo n.º 9
0
        void SetValidatorValues()
        {
            UsernameValidator        = ValidatorRules.EmptyOrNullValueRule(Username);
            FullNameValidator        = ValidatorRules.EmptyOrNullValueRule(Fullname);
            PhoneValidator           = ValidatorRules.EmptyOrNullValueRule(Phone);
            AddressValidator         = ValidatorRules.EmptyOrNullValueRule(Address);
            PasswordValidator        = ValidatorRules.EmptyOrNullValueRule(Password);
            ConfirmPasswordValidator = ValidatorRules.EmptyOrNullValueRule(ConfirmPassword);
            EmailValidator           = ValidatorRules.EmptyOrNullValueRule(Email);

            if (!EmailValidator.HasError)
            {
                EmailPatternValidator = ValidatorRules.EmptyOrNullValueRule(Email);
            }
            GenderValidator = ValidatorRules.EmptyOrNullValueRule(GenderSelected);
        }
Ejemplo n.º 10
0
        public LoginViewModel(INavigation _navigation)
        {
            Navigation = _navigation;

            popupNavigation = PopupNavigation.Instance;

            Task.Run(async() =>
            {
                Username = await SecureStorage.GetAsync("username");
                Password = await SecureStorage.GetAsync("password");
            });

            ValidatorsInitializer();

            //App.ComunicationService = new ComunicationService();
            Genders   = new List <string>(Enum.GetNames(typeof(Gender)).ToList());
            IsLoading = false;


            LoginCommand = new Command(async() =>
            {
                //var currentuserID = Xamarin.Forms.Application.Current.Properties["loginId "].ToString();
                IsLoading = true;

                if (!string.IsNullOrEmpty(Username) && !string.IsNullOrEmpty(Password))
                {
                    //Verifica si el telefono tiene acceso a internet


                    if (Connectivity.NetworkAccess == NetworkAccess.Internet)
                    {
                        //Obtine los credenciales del usuario
                        //var loginresult = userDataStore.CheckUserCredential(Username, Password);
                        //Obtiene el token de acceso
                        App.TokenDto = userDataStore.LoginCredential(Username, Password);

                        var loginresult = App.TokenDto.UserDetail;

                        //Verifica si el resultado del login no es vacio.
                        if (loginresult != null)
                        {
                            if (!loginresult.IsValidUser)
                            {
                                App.LogUser = loginresult;
                                await popupNavigation.PushAsync(new ValidateEmailCode());
                                IsLoading = false;
                            }
                            else
                            {
                                Task.Run(async() =>
                                {
                                    await App.ComunicationService.Connect();
                                }).Wait();

                                App.LogUser = loginresult;

                                bool hasPaymentCard = App.LogUser.PaymentCards.Count() > 0 ? true : false;

                                //Verfico si hay tarjetas registradas con el usuario
                                if (hasPaymentCard)
                                {
                                    var data = App.LogUser.PaymentCards;
                                    var card = new List <PaymentCard>(data);


                                    var userCardTokenId = await stripeServiceDS.GetCustomerCardId(App.LogUser.StripeUserId, card[0].StripeCardId);


                                    App.CardPaymentToken.CardTokenId = userCardTokenId;
                                }


                                if (!String.IsNullOrEmpty(App.ComunicationService.hubConnection.ConnectionId))
                                {
                                    App.UsersConnected = new UsersConnected()
                                    {
                                        HubConnectionID = App.ComunicationService.hubConnection.ConnectionId,
                                        UserID          = App.LogUser.UserId,
                                        IsDisable       = false,
                                        ConnecteDate    = DateTime.Now
                                    };

                                    var result = await userConnectedDataStore.ModifyOldConnections(App.UsersConnected);

                                    var hub_connected_Result = await userConnectedDataStore.AddItemAsync(App.UsersConnected);
                                }



                                App.Current.MainPage = new AppShell();
                                IsLoading            = false;
                            }
                        }
                        else
                        {
                            IsLoading = false;
                            await App.Current.MainPage.DisplayAlert("Notification", "Incorrect login...!", "OK");
                        }
                    }
                }
                else
                {
                    IsLoading = false;
                    await App.Current.MainPage.DisplayAlert("Notification", "Empty values...!", "OK");
                }
            });

            LoginEmployeeCommand = new Command(async() =>
            {
                IsLoading = true;
                if (!string.IsNullOrEmpty(Username) && !string.IsNullOrEmpty(Password))
                {
                    //var loginresult = userDataStore.CheckUserCredential(Username, Password);
                    App.TokenDto = userDataStore.LoginCredential(Username, Password);


                    var loginresult = App.TokenDto.UserDetail;
                    if (loginresult != null)
                    {
                        Task.Run(async() =>
                        {
                            await App.ComunicationService.Connect();
                        }).Wait();

                        var userEmployees = await EmployeeDataStore.GetUserEmployees(loginresult.UserId.ToString());
                        App.LogUser       = loginresult;


                        if (!String.IsNullOrEmpty(App.ComunicationService.hubConnection.ConnectionId))
                        {
                            App.UsersConnected = new UsersConnected()
                            {
                                HubConnectionID = App.ComunicationService.hubConnection.ConnectionId,
                                UserID          = App.LogUser.UserId,
                                IsDisable       = false,
                                ConnecteDate    = DateTime.Now
                            };

                            var result = await userConnectedDataStore.ModifyOldConnections(App.UsersConnected);

                            var hub_connected_Result = await userConnectedDataStore.AddItemAsync(App.UsersConnected);
                        }

                        //App.UsersConnected = new UsersConnected()
                        //{
                        //    HubConnectionID = App.ComunicationService.hubConnection.ConnectionId,
                        //    UserID = App.LogUser.UserId,
                        //    IsDisable = false,
                        //    ConnecteDate = DateTime.Now
                        //};
                        //var result = await userConnectedDataStore.ModifyOldConnections(App.UsersConnected);


                        //var hub_connected_Result = await userConnectedDataStore.AddItemAsync(App.UsersConnected);

                        App.Current.MainPage = new EmployeeShell();
                        IsLoading            = false;
                    }
                    else
                    {
                        await App.Current.MainPage.DisplayAlert("Notification", "Incorrect login.", "OK");
                    }
                }
                else
                {
                    await App.Current.MainPage.DisplayAlert("Notification", "Empty inputs.", "OK");
                }
            });

            RegisterCommand = new Command(async() =>
            {
                await App.Current.MainPage.Navigation.PushAsync(new RegisterPage());
            });



            DoneCommand = new Command(async() =>
            {
                SetValidatorValues();

                //Verficamos que las propiedades esten de con la informacion correcta y llenas.
                if (!UsernameValidator.HasError && !FullNameValidator.HasError && !PhoneValidator.HasError && !AddressValidator.HasError && !PasswordValidator.HasError && !ConfirmPasswordValidator.HasError && !EmailValidator.HasError && !GenderValidator.HasError && !EmailPatternValidator.HasError)
                {
                    if (!await userDataStore.EmailExist(Email))
                    {
                        ConfirmAndPasswordValidator = ValidatorRules.PasswordAndConfirmPasswordEquals(Password, ConfirmPassword);
                        //Verificamos que el password y el confirmpassword matcheen
                        if (!ConfirmAndPasswordValidator.HasError)
                        {
                            //Si el username y password existen tendra que reinsertar esa informacion
                            if (!await userDataStore.CheckIfUsernameAndPasswordExist(Username, Password))
                            {
                                var userlogin = new Login()
                                {
                                    LoginId     = Guid.NewGuid(),
                                    IsConnected = false,
                                    Password    = Password,
                                    Username    = Username
                                };

                                Gender value;
                                Enum.TryParse(GenderSelected, out value);
                                var newUser = new User()
                                {
                                    UserId    = Guid.NewGuid(),
                                    Email     = Email,
                                    Name      = Fullname,
                                    LoginId   = userlogin.LoginId,
                                    Phone     = Phone,
                                    Address   = Address,
                                    Gender    = value,
                                    UserLogin = userlogin,
                                };

                                userlogin.UserId = newUser.UserId;

                                try
                                {
                                    var optionsCustomers = new UserDTO
                                    {
                                        Name    = Fullname,
                                        Email   = Email,
                                        Phone   = Phone,
                                        Address = Address
                                    };


                                    //Create Customer
                                    var customertokenId = await stripeServiceDS.CreateStripeCustomer(optionsCustomers);


                                    if (!string.IsNullOrEmpty(customertokenId))
                                    {
                                        Task.Run(async() =>
                                        {
                                            await App.ComunicationService.Connect();
                                        }).Wait();

                                        newUser.StripeUserId = customertokenId;
                                        var result           = await userDataStore.AddItemAsync(newUser);

                                        //var credentialsResult = userDataStore.CheckUserCredential(Username, Password);
                                        App.TokenDto = userDataStore.LoginCredential(Username, Password);

                                        if (result)
                                        {
                                            App.LogUser = App.TokenDto.UserDetail;

                                            if (!String.IsNullOrEmpty(App.ComunicationService.hubConnection.ConnectionId))
                                            {
                                                App.UsersConnected = new UsersConnected()
                                                {
                                                    HubConnectionID = App.ComunicationService.hubConnection.ConnectionId,
                                                    UserID          = App.LogUser.UserId,
                                                    IsDisable       = false,
                                                    ConnecteDate    = DateTime.Now
                                                };

                                                //var oldConnectionModify = await userConnectedDataStore.ModifyOldConnections(App.UsersConnected);

                                                var hub_connected_Result = await userConnectedDataStore.AddItemAsync(App.UsersConnected);
                                            }


                                            try
                                            {
                                                await SecureStorage.SetAsync("username", Username);
                                                await SecureStorage.SetAsync("password", Password);
                                            }
                                            catch (Exception ex)
                                            {
                                                // Possible that device doesn't support secure storage on device.
                                            }


                                            await popupNavigation.PushAsync(new RegisterValidationEmail());
                                        }
                                    }
                                }
                                catch (Exception e)
                                {
                                    await App.Current.MainPage.DisplayAlert("Notification", e.Message, "OK");
                                }
                            }
                            else
                            {
                                await App.Current.MainPage.DisplayAlert("Notification", "Username or password exist try to change to other one.", "OK");
                            }
                        }
                    }
                    else
                    {
                        await App.Current.MainPage.DisplayAlert("Notification", "Email is in used.", "OK");
                    }
                }
                else
                {
                    await App.Current.MainPage.DisplayAlert("Notification", "Some error ocurred check the information.", "OK");
                }
            });



            GoForgotPasswordCommand = new Command(async() =>
            {
                await App.Current.MainPage.Navigation.PushAsync(new ForgotPasswordPage());
            });
        }
Ejemplo n.º 11
0
        public RegisterStoreViewModel()
        {
            ValidatorInitializer();
            StoreImage = ImageSource.FromFile("imgPlaceholder.jpg");
            StoreTypes = new List <string>(Enum.GetNames(typeof(StoreType)).ToList());
            #region WorkHourPresenter Initialize
            WorkHourPresenters = new ObservableCollection <WorkHourPresenter>();

            WorkHourPresenters.Add(new WorkHourPresenter(DayOfWeek.Monday.ToString()));
            WorkHourPresenters.Add(new WorkHourPresenter(DayOfWeek.Tuesday.ToString()));
            WorkHourPresenters.Add(new WorkHourPresenter(DayOfWeek.Wednesday.ToString()));
            WorkHourPresenters.Add(new WorkHourPresenter(DayOfWeek.Thursday.ToString()));
            WorkHourPresenters.Add(new WorkHourPresenter(DayOfWeek.Friday.ToString()));
            WorkHourPresenters.Add(new WorkHourPresenter(DayOfWeek.Saturday.ToString()));
            WorkHourPresenters.Add(new WorkHourPresenter(DayOfWeek.Sunday.ToString()));
            #endregion

            PickPhotoCommand = new Command(async() =>
            {
                //Stream stream = await DependencyService.Get<IPickPhotoService>().GetImageStreamAsync();
                //if (stream != null)
                //{
                //    ImgArray = ConvertToByteArray(stream);
                //    StoreImage = ImageSource.FromStream(() => stream);
                //}

                try
                {
                    await CrossMedia.Current.Initialize();

                    files.Clear();

                    if (!CrossMedia.Current.IsPickPhotoSupported)
                    {
                        await Shell.Current.DisplayAlert("Photos Not Supported", ":( Permission not granted to photos.", "OK");
                        return;
                    }

                    var mediOptions = new PickMediaOptions()
                    {
                        PhotoSize = PhotoSize.Full,
                    };

                    var selectedImgFile = await CrossMedia.Current.PickPhotoAsync(mediOptions);



                    if (selectedImgFile == null)
                    {
                        return;
                    }



                    ImgArray = ConvertToByteArray(selectedImgFile.GetStream());

                    StoreImage = ImageSource.FromStream(() => selectedImgFile.GetStream());
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                }
            });

            CompleteRegisterCommand = new Command(async() =>
            {
                TokenExpManger tokenExpManger = new TokenExpManger(App.TokenDto.Exp);
                if (tokenExpManger.IsExpired())
                {
                    await tokenExpManger.CloseSession();
                }
                else
                {
                    List <string> valuesToCheck = new List <string>();

                    valuesToCheck.Add(StoreName);
                    valuesToCheck.Add(LicenseCode);
                    valuesToCheck.Add(StripeSecretKey);
                    valuesToCheck.Add(StripePublicKey);


                    StoreNameValidator        = ValidatorRules.EmptyOrNullValueRule(StoreName);
                    StoreDescriptionValidator = ValidatorRules.EmptyOrNullValueRule(StoreDescription);
                    LicenseCodeValidator      = ValidatorRules.EmptyOrNullValueRule(LicenseCode);

                    SkStripeValidator   = ValidatorRules.EmptyOrNullValueRule(StripeSecretKey);
                    PKeyStripeValidator = ValidatorRules.EmptyOrNullValueRule(StripePublicKey);



                    if (!StoreNameValidator.HasError && !StoreDescriptionValidator.HasError && !LicenseCodeValidator.HasError && !SkStripeValidator.HasError && !PKeyStripeValidator.HasError && GlobalValidator.CheckNullOrEmptyImage(StoreImage))
                    {
                        bool isSKKeyCorrect = StripeSecretKey.StartsWith("sk");
                        bool isPBkeyCorrect = StripePublicKey.StartsWith("pk");
                        if (isSKKeyCorrect || isSKKeyCorrect)
                        {
                            Guid licenseCodeGuid = Guid.Parse(LicenseCode);
                            var licenseResult    = storeLicenseDataStore.StoreLicenseExists(licenseCodeGuid);

                            if (licenseResult)
                            {
                                var licenseIsInUsed = await storeLicenseDataStore.IsLicenseInUsed(LicenseCode);
                                if (!licenseIsInUsed)
                                {
                                    StoreType value;
                                    Enum.TryParse(StoreTypeSelected, out value);

                                    var newStoreRegister = new Store()
                                    {
                                        StoreId                = Guid.NewGuid(),
                                        StoreName              = StoreName,
                                        UserId                 = App.LogUser.UserId,
                                        StoreImage             = ImgArray,
                                        StoreType              = value,
                                        StoreRegisterLicenseId = licenseCodeGuid,
                                        StoreDescription       = StoreDescription,
                                        SKKey = StripeSecretKey,
                                        PBKey = StripePublicKey,
                                    };

                                    List <WorkHour> workHours = new List <WorkHour>();

                                    foreach (var item in WorkHourPresenters)
                                    {
                                        var workHour = new WorkHour()
                                        {
                                            CloseTime  = Convert.ToDateTime(item.Close.ToString()),
                                            Day        = item.Day,
                                            OpenTime   = Convert.ToDateTime(item.Open.ToString()),
                                            WorkHourId = Guid.NewGuid(),
                                            StoreId    = newStoreRegister.StoreId
                                        };

                                        workHours.Add(workHour);
                                    }

                                    newStoreRegister.WorkHours = workHours;

                                    var storeaddedResult = await StoreDataStore.AddItemAsync(newStoreRegister);

                                    if (storeaddedResult)
                                    {
                                        var licenceUpdateResult = await storeLicenseDataStore.UpdateLicenceInCode(licenseCodeGuid);

                                        if (licenceUpdateResult)
                                        {
                                            await Shell.Current.DisplayAlert("Notification", "Store Added...!", "OK");
                                        }
                                    }
                                }
                                else
                                {
                                    await Shell.Current.DisplayAlert("Notification", "This License is in used.", "OK");
                                }
                            }
                            else
                            {
                                await Shell.Current.DisplayAlert("Notification", "License Code Incorrect", "OK");
                            }
                        }
                        else
                        {
                            await Shell.Current.DisplayAlert("Notification", "Srtipe Secret Key or Public Key are set in incorrect entry check again.", "OK");
                        }
                    }
                    else
                    {
                        await Shell.Current.DisplayAlert("Notification", "Some fields are empty", "OK");
                    }
                }
            });
        }
        public RegisterCardViewModel()
        {
            PropertiesInitializer();


            CompleteRegisterCardCommand = new Command(async() =>
            {
                TokenExpManger tokenExpManger = new TokenExpManger(App.TokenDto.Exp);
                if (tokenExpManger.IsExpired())
                {
                    await tokenExpManger.CloseSession();
                }
                else
                {
                    HolderNameValidator = ValidatorRules.EmptyOrNullValueRule(HolderName);
                    CardNumberValidator = ValidatorRules.EmptyOrNullValueRule(CardNumber);
                    YearValidator       = ValidatorRules.EmptyOrNullValueRule(Year);
                    MonthVaidator       = ValidatorRules.EmptyOrNullValueRule(Month);
                    CVCValidator        = ValidatorRules.EmptyOrNullValueRule(CVC);


                    if (!HolderNameValidator.HasError && !CardNumberValidator.HasError && !YearValidator.HasError && !MonthVaidator.HasError && !CVCValidator.HasError)
                    {
                        try
                        {
                            var cardData = new PaymentCard()
                            {
                                CardNumber    = CardNumber,
                                Cvc           = CVC,
                                HolderName    = HolderName,
                                Month         = Month,
                                Year          = Year,
                                PaymentCardId = Guid.NewGuid(),
                                UserId        = App.LogUser.UserId
                            };

                            var cardserviceResult = await stripeServiceDS.InsertStripeCardToStripeUser(cardData, App.LogUser.StripeUserId);

                            if (!cardserviceResult.HasError)
                            {
                                cardData.StripeCardId = cardserviceResult.TokenId;
                                var result            = await CardDataStore.AddItemAsync(cardData);

                                if (result)
                                {
                                    await Shell.Current.DisplayAlert("Notification", "Card succefully added.", "OK");
                                }
                            }
                            else
                            {
                                await Shell.Current.DisplayAlert("Notification", cardserviceResult.ErrorMsg, "OK");
                            }
                        }
                        catch (Exception e)
                        {
                            await Shell.Current.DisplayAlert("Notification", e.Message, "OK");
                        }
                    }
                }
            });
        }
 public static JObject GetDeserialisedValidatorRules(ValidatorRules rules) =>
 JObject.Parse(JsonConvert.SerializeObject(
                   rules,
                   new JsonSerializerSettings {
     ContractResolver = new CamelCasePropertyNamesContractResolver()
 }));