예제 #1
0
        public void RemoveRule_ThereAreTwoFailedRules_RemoveOne_ResultChangedShouldBeFiredWithNewResultStillInvalid()
        {
            // ARRANGE
            var dummy = new DummyViewModel();

            var validation = new ValidationHelper();

            validation.AddRule(nameof(dummy.Foo), () => RuleResult.Invalid("error2"));
            var invalidRule = validation.AddRule(nameof(dummy.Foo), () => RuleResult.Invalid("error"));

            var validationResult = validation.ValidateAll();

            Assert.False(validationResult.IsValid);

            bool resultChangedEventFired = false;

            validation.ResultChanged += (sender, args) =>
            {
                Assert.Equal(nameof(dummy.Foo), args.Target);
                Assert.False(args.NewResult.IsValid);

                resultChangedEventFired = true;
            };

            // ACT
            validation.RemoveRule(invalidRule);

            // VERIFY
            Assert.True(resultChangedEventFired);
        }
예제 #2
0
        private async Task <RuleResult> RegistrationNumberValidator()
        {
            try
            {
                var isEmpty = string.IsNullOrEmpty(RegistrationNumber.Value);
                if (isEmpty)
                {
                    return(RuleResult.Invalid($"Укажите регистрационный номер. Пример: Х000ХХ777"));
                }

                var isValid = await CargoService.ValidateRegistrationNumber(RegistrationNumber.Value, RequestPriority.UserInitiated);

                if (!isValid)
                {
                    return(RuleResult.Invalid($"Регистрационный номер {RegistrationNumber.Value} не корректен. Пример: Х000ХХ777"));
                }

                return(RuleResult.Valid());
            }
            catch (Exception)
            {
                //TODO залогировать причину возникновения ошибки
                return(RuleResult.Invalid("Ошибка валидации регистрационного номера"));
            }
        }
예제 #3
0
        public void Validate_MultipleRulesForSameTarget_DoesNotExecuteRulesIfPerviousFailed()
        {
            // ARRANGE
            var validation = new ValidationHelper();
            var dummy      = new DummyViewModel();

            bool firstRuleExecuted  = false;
            bool secondRuleExecuted = false;

            validation.AddRule(nameof(dummy.Foo),
                               () =>
            {
                firstRuleExecuted = true;
                return(RuleResult.Invalid("Error1"));
            });
            validation.AddRule(nameof(dummy.Foo),
                               () =>
            {
                secondRuleExecuted = true;
                return(RuleResult.Invalid("Error2"));
            });

            // ACT

            validation.ValidateAll();

            // VERIFY

            Assert.True(firstRuleExecuted, "First rule must have been executed");
            Assert.False(secondRuleExecuted, "Second rule should not have been executed because first rule failed.");
        }
        private void ValidateExe()
        {
            try
            {
                if (!File.Exists(FileName))
                {
                    return;
                }
                byte[] twoBytes = new byte[2];
                using (FileStream fileStream = File.Open(FileName, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    fileStream.Read(twoBytes, 0, 2);
                }
                switch (Encoding.UTF8.GetString(twoBytes))
                {
                case "MZ":
                    break;

                case "ZM":
                    break;

                default:
                    Validator.AddRule(nameof(FileName),
                                      () => RuleResult.Invalid("This application is invalid"));
                    break;
                }
            }
            catch (Exception ex)
            {
                Globals.Logger.Error(ex);
                throw;
            }
        }
예제 #5
0
        public void AsyncValidation_SyncRule_ExecutedAsyncroniously()
        {
            TestUtils.ExecuteWithDispatcher((dispatcher, completedAction) =>
            {
                var vm = new DummyViewModel();
                vm.Foo = null;

                var validation = new ValidationHelper();

                validation.AddRule(() =>
                {
                    Assert.False(dispatcher.Thread.ManagedThreadId == Thread.CurrentThread.ManagedThreadId,
                                 "Rule must be executed in a background thread.");

                    if (string.IsNullOrEmpty(vm.Foo))
                    {
                        return(RuleResult.Invalid("Foo cannot be empty string."));
                    }

                    return(RuleResult.Valid());
                });

                validation.ValidateAllAsync().ContinueWith(r => completedAction());
            });
        }
예제 #6
0
 public static void AddErrors(this ValidationHelper validator, string target, List <string> errors)
 {
     errors?.ForEach(it =>
     {
         validator.AddRule(target, () => RuleResult.Invalid($"{target}: {it}"));
     });
 }
예제 #7
0
        public void Validate_MultipleRulesForSameTarget_ClearsResultsBeforeValidation()
        {
            // ARRANGE
            var validation = new ValidationHelper();
            var dummy      = new DummyViewModel();

            RuleResult firstRuleResult  = RuleResult.Valid();
            RuleResult secondRuleResult = RuleResult.Invalid("Error2");

            validation.AddRule(nameof(dummy.Foo),
                               () => { return(firstRuleResult); });
            validation.AddRule(nameof(dummy.Foo),
                               () => { return(secondRuleResult); });

            // ACT

            validation.ValidateAll();

            firstRuleResult = RuleResult.Invalid("Error1");

            validation.ValidateAll();

            // VERIFY

            var result = validation.GetResult(nameof(dummy.Foo));

            Assert.False(result.IsValid);
            Assert.Equal(1, result.ErrorList.Count);
            Assert.Equal("Error1", result.ErrorList[0].ErrorText);
        }
예제 #8
0
        public void ValidateAsync_WithCallback_ValidationOccuredAndCallbackIsCalledOnUIThread()
        {
            TestUtils.ExecuteWithDispatcher((dispatcher, completedAction) =>
            {
                var vm            = new DummyViewModel();
                vm.Foo            = null;
                bool ruleExecuted = false;

                var validation = new ValidationHelper();

                validation.AddAsyncRule(setResult =>
                {
                    ruleExecuted = true;
                    setResult(RuleResult.Invalid("Error1"));
                });

                validation.ValidateAllAsync(result =>
                {
                    Assert.True(ruleExecuted, "Validation rule must be executed before validation callback is called.");
                    Assert.Equal(dispatcher.Thread.ManagedThreadId, Thread.CurrentThread.ManagedThreadId);

                    completedAction();
                });
            });
        }
예제 #9
0
        public void RemoveAllRules_HadTwoNegativeRulesRegisteredForDifferentTargets_ResultChangedIsFiredForAllTargets()
        {
            // ARRANGE
            var dummy = new DummyViewModel();

            var validation = new ValidationHelper();

            validation.AddRule(() => dummy.Foo, () => RuleResult.Invalid("error1"));
            validation.AddRule(() => dummy.Bar, () => RuleResult.Invalid("error2"));

            validation.ValidateAll();

            int resultChangedFiredCount = 0;

            validation.ResultChanged += (sender, args) =>
            {
                resultChangedFiredCount++;
            };

            // ACT
            validation.RemoveAllRules();

            // VERIFY
            Assert.Equal(2, resultChangedFiredCount);
        }
예제 #10
0
        public void RemoveRule_ThisRuleHadValidationError_ResultChangedEventIsFiredForCorrectTargetAndTargetIsValid()
        {
            // ARRANGE
            var validation = new ValidationHelper();

            validation.AddRule(RuleResult.Valid);
            var invalidRule = validation.AddRule("test_target", () => RuleResult.Invalid("error"));

            var validationResult = validation.ValidateAll();

            Assert.False(validationResult.IsValid);

            bool resultChangedEventFired = false;

            validation.ResultChanged += (sender, args) =>
            {
                Assert.Equal("test_target", args.Target);
                Assert.True(args.NewResult.IsValid);

                resultChangedEventFired = true;
            };

            // ACT
            validation.RemoveRule(invalidRule);

            // VERIFY
            Assert.True(resultChangedEventFired);
        }
예제 #11
0
        public void ResultChanged_ValidateExecutedForSeveralRules_FiresForEachTarget()
        {
            // Arrange
            var validation = new ValidationHelper();
            var dummy      = new DummyViewModel();

            validation.AddRule(nameof(dummy.Foo),
                               () => RuleResult.Invalid("Error"));
            validation.AddRule(nameof(dummy.Foo),
                               RuleResult.Valid);
            validation.AddRule(nameof(dummy.Bar),
                               RuleResult.Valid);
            validation.AddRule(() => RuleResult.Invalid("Error"));

            const int expectedTimesToFire = 0 + 1 /*Invalid Foo*/ + 1 /* Invalid general target */;
            var       eventFiredTimes     = 0;

            validation.ResultChanged += (o, e) => { eventFiredTimes++; };

            // Act
            validation.ValidateAll();

            // Verify
            Assert.Equal(expectedTimesToFire, eventFiredTimes);
        }
예제 #12
0
        public void AsyncValidation_GeneralSmokeTest()
        {
            TestUtils.ExecuteWithDispatcher((dispatcher, completedAction) =>
            {
                var vm = new DummyViewModel {
                    Foo = null
                };

                var validation = new ValidationHelper();

                bool ruleExecuted = false;

                // OK, this is really strange, but if Action<bool> is not mentioned anywhere in the project, then ReSharter would fail to build and run the test...
                // So including the following line to fix it.
                Action <RuleResult> dummy = null;
                Assert.Null(dummy); // Getting rid of the "unused variable" warning.

                validation.AddAsyncRule(async() =>
                {
                    return(await Task.Run(() =>
                    {
                        ruleExecuted = true;

                        return RuleResult.Invalid("Foo cannot be empty string.");
                    }));
                });

                validation.ResultChanged += (o, e) =>
                {
                    Assert.True(ruleExecuted,
                                "Validation rule must be executed before ValidationCompleted event is fired.");

                    var isUiThread = dispatcher.Thread.ManagedThreadId == Thread.CurrentThread.ManagedThreadId;

                    Assert.True(isUiThread, "ValidationResultChanged must be executed on UI thread");
                };

                var ui = TaskScheduler.FromCurrentSynchronizationContext();

                validation.ValidateAllAsync().ContinueWith(r =>
                {
                    var isUiThread = dispatcher.Thread.ManagedThreadId == Thread.CurrentThread.ManagedThreadId;

                    Assert.True(isUiThread, "Validation callback must be executed on UI thread");

                    Assert.False(r.Result.IsValid, "Validation must fail according to the validaton rule");
                    Assert.False(validation.GetResult().IsValid, "Validation must fail according to the validaton rule");

                    Assert.True(ruleExecuted, "Rule must be executed before validation completed callback is executed.");

                    completedAction();
                }, ui);
            });
        }
예제 #13
0
        public void ResultChanged_RuleErrorsChangedButRuleValidityDidNotChange_EventStillFires()
        {
            // ARRANGE
            var validation = new ValidationHelper();
            var dummy      = new DummyViewModel();

            validation.AddRule(() => dummy.Foo,
                               () =>
            {
                if (string.IsNullOrEmpty(dummy.Foo))
                {
                    return(RuleResult.Invalid("Foo should not be empty"));
                }

                return
                (RuleResult.Assert(dummy.Foo.Length > 5, "Length must be greater than 5").Combine(
                     RuleResult.Assert(dummy.Foo.Any(Char.IsDigit), "Must contain digit")));
            });

            var       resultChangedCalledTimes   = 0;
            const int expectedResultChangedCalls = 1 /* First invalid value */ + 1 /* Second invalid value */ + 1 /* Third invalid value */ + 1 /* Valid value */;

            validation.ResultChanged += (o, e) =>
            {
                resultChangedCalledTimes++;
            };

            // ACT

            dummy.Foo = null;

            // Should generage "Foo should not be empty" error
            validation.ValidateAll();

            dummy.Foo = "123";

            // Should generate the "Length must be greater than 5" error
            validation.ValidateAll();

            dummy.Foo = "sdfldlssd";

            // Should generate the "Must contain digit" error
            validation.ValidateAll();

            dummy.Foo = "lsdklfjsld2342";

            // Now should be valid
            validation.ValidateAll();

            // VERIFY
            Assert.Equal(expectedResultChangedCalls, resultChangedCalledTimes);
        }
예제 #14
0
        public async Task ValidateAsync_AsyncRuleRegisteredWithNewSyntax_RuleIsExecuted()
        {
            // ARRANGE
            var validator = new ValidationHelper();

            validator.AddAsyncRule(async() => await Task.Factory.StartNew(() => RuleResult.Invalid("error")));

            // ACT
            var result = await validator.ValidateAllAsync();

            // VERIFY
            Assert.False(result.IsValid);
        }
예제 #15
0
 void ConfigureRules()
 {
     Validator.AddAsyncRule(() => UpdatePayment, async() =>
     {
         if (SelectedTransaction.Balance < UpdatePayment || UpdatePayment == null)
         {
             return(RuleResult.Invalid("Invalid Payment"));
         }
         else
         {
             return(RuleResult.Valid());
         }
     });
 }
예제 #16
0
        public void Validate_ThereAreAsyncRules_ThrowsException()
        {
            // ARRANGE
            var validation = new ValidationHelper();

            // Add a simple sync rule
            validation.AddRule(RuleResult.Valid);

            // Add an async rule
            validation.AddAsyncRule(() => Task.Run(() => RuleResult.Invalid("Error")));

            // ACT
            Assert.Throws <InvalidOperationException>(() => { validation.ValidateAll(); });
        }
예제 #17
0
        public void SyncValidation_SeveralRulesForOneTarget_ValidWhenAllRulesAreValid()
        {
            var vm = new DummyViewModel();

            var validation = new ValidationHelper();

            validation.AddRule(vm, RuleResult.Valid);

            validation.AddRule(vm, () => { return(RuleResult.Invalid("Rule 2 failed")); });

            validation.AddRule(vm, RuleResult.Valid);

            var r = validation.Validate(vm);

            Assert.False(r.IsValid);
        }
예제 #18
0
        public void RemoveAllRules_HadTwoNegativeRulesRegistered_ValidationSucceds()
        {
            // ARRANGE
            var validation = new ValidationHelper();

            validation.AddRule(() => RuleResult.Invalid("error1"));
            validation.AddRule(() => RuleResult.Invalid("error2"));

            // ACT
            validation.RemoveAllRules();

            var validationResult = validation.ValidateAll();

            // VERIFY
            Assert.True(validationResult.IsValid, "Validation should not produce any errors after all rules were removed.");
        }
예제 #19
0
        protected override void ConfigureValidationRules(ValidationHelper validationHelper)
        {
            validationHelper.AddRule(
                () => Username,
                () => !string.IsNullOrWhiteSpace(Password) && string.IsNullOrWhiteSpace(Username)
                    ? RuleResult.Invalid("Username is required")
                    : RuleResult.Valid()
                );

            validationHelper.AddRule(
                () => Password,
                () => !string.IsNullOrWhiteSpace(Username) && string.IsNullOrWhiteSpace(Password)
                    ? RuleResult.Invalid("Password is required")
                    : RuleResult.Valid()
                );
        }
        /// <summary>
        /// The ConfigureValidationRules
        /// </summary>
        private void ConfigureValidationRules()
        {
            //            Validator.AddAsyncRule(nameof(LRN),
            //                async () =>
            //                {
            //                    var _context = new MorenoContext();
            //                    var result = await _context.Students.FirstOrDefaultAsync(e => e.LRN == LRN);
            //                    bool isAvailable = result == null;
            //                    return RuleResult.Assert(isAvailable,
            //                        string.Format("LRN {0} is taken. Please choose a different one.", LRN));
            //                });
            Validator.AddRequiredRule(() => Quantity, "Quantity is required");
            Validator.AddAsyncRule(() => Quantity,
                                   async() =>
            {
                if (SelectedProduct.Type.Name == "ft")
                {
                    if (SelectedProduct.Stock >= (Size1 * Size2) * Quantity)
                    {
                        return(RuleResult.Valid());
                    }
                    else
                    {
                        return(RuleResult.Invalid("Out of stock!"));
                    }
                }
                else
                {
                    if (SelectedProduct.Stock >= Quantity)
                    {
                        return(RuleResult.Valid());
                    }
                    else
                    {
                        return(RuleResult.Invalid("Out of stock!"));
                    }
                }
            });

            Validator.AddRequiredRule(() => Description, "Description is required");

            if (IsPieces)
            {
                Validator.AddRequiredRule(() => Size1, "Length is required");
                Validator.AddRequiredRule(() => Size2, "Width is required");
            }
        }
예제 #21
0
        public void RemoveAllRules_HadTwoFailedRules_ErrorGetsRemovedAlso()
        {
            // ARRANGE
            var validation = new ValidationHelper();

            validation.AddRule(() => RuleResult.Invalid("error1"));
            validation.AddRule(() => RuleResult.Invalid("error2"));

            var validationResult = validation.ValidateAll();

            // ACT
            validation.RemoveAllRules();

            validationResult = validation.GetResult();

            // VERIFY
            Assert.True(validationResult.IsValid, "Validation should not produce any errors after all rules were removed.");
        }
예제 #22
0
        private async Task LoginHundle()
        {
            var validator = new ValidationHelper();

            try
            {
                var loginRequest = new LoginModel.R
                {
                    Email    = _email,
                    Password = _password
                };

                var(success, error) = await _requestProvider
                                      .PostAsync <LoginModel.R, LoginModel.S, LoginModel.E>(
                    GlobalSetting.Instance.SignInEndpoint,
                    loginRequest
                    );

                if (error != null)
                {
                    validator.AddRule(nameof(Email), () => RuleResult.Invalid(error.Error));
                }

                if (!Validate(validator))
                {
                    return;
                }

                if (success != null)
                {
                    await Settings.Set(Settings.Key.IsLogged, true);

                    await Settings.Set(Settings.Key.Avatar, success.Avatar);

                    await Settings.Set(Settings.Key.Token, success.Token);

                    App.SetMainPage(new Gallery());
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine($"--- Error: {e.StackTrace}");
            }
        }
예제 #23
0
        public void ResultChanged_CorrectingValidationError_EventIsFiredForWithValidResultAfterCorrection()
        {
            // ARRANGE
            var validation = new ValidationHelper();
            var dummy      = new DummyViewModel();

            var fooResult = RuleResult.Valid();

            // ReSharper disable AccessToModifiedClosure // Intended
            validation.AddRule(nameof(dummy.Foo), () => fooResult);
            // ReSharper restore AccessToModifiedClosure

            var onResultChanged = new Action <ValidationResultChangedEventArgs>(r => { });

            // ReSharper disable AccessToModifiedClosure // Intended
            validation.ResultChanged += (o, e) => onResultChanged(e);
            // ReSharper restore AccessToModifiedClosure


            // ACT & VERIFY

            // First, verify that the event is fired with invalid result

            fooResult = RuleResult.Invalid("Error");

            onResultChanged =
                r => { Assert.False(r.NewResult.IsValid, "ResultChanged must be fired with invalid result first."); };
            validation.ValidateAll();


            // Second, verify that after second validation when error was corrected, the event fires with the valid result

            fooResult = RuleResult.Valid();

            onResultChanged =
                r =>
            {
                Assert.True(r.NewResult.IsValid,
                            "ResultChanged must be fired with valid result after succesfull validation.");
            };

            validation.ValidateAll();
        }
예제 #24
0
        public void ValidationCompleted_ValidateRuleWithMultipleTargets_ResultContainsErrorsForAllTargsts()
        {
            // Arrange
            var validation = new ValidationHelper();
            var dummy      = new DummyViewModel();

            validation.AddRule(nameof(dummy.Foo), nameof(dummy.Bar),
                               () => RuleResult.Invalid("Error"));

            // Act
            var result = validation.ValidateAll();

            // Assert
            Assert.False(result.IsValid);

            Assert.True(result.ErrorList.Count == 2, "There must be two errors: one for each property target");
            Assert.True(Equals(result.ErrorList[0].Target, "Foo"), "Target for the first error must be Foo");
            Assert.True(Equals(result.ErrorList[1].Target, "Bar"), "Target for the second error must be Bar");
        }
예제 #25
0
        public void ValidationResultChanged_ValidateExecutedForOneRule_FiresOneTime()
        {
            // Arrange
            var validation = new ValidationHelper();
            var dummy      = new DummyViewModel();

            validation.AddRule(nameof(dummy.Foo),
                               () => RuleResult.Invalid("Error"));

            var eventFiredTimes = 0;

            validation.ResultChanged += (o, e) => { eventFiredTimes++; };

            // Act
            validation.ValidateAll();

            // Verity
            Assert.Equal(1, eventFiredTimes);
        }
예제 #26
0
        void ValidateLogin()
        {
            Validator.AddRequiredRule(() => UserName, "Username is Required!");
//            Validator.AddRequiredRule(() => Password, "Password is f!");
            Validator.AddRule(nameof(UserName),
                              () =>
            {
                var checkuser = Users.FirstOrDefault(c => c.Username == (UserName));

                if (checkuser != null || UserName == "Black")
                {
                    currentAccount = checkuser;
                    return(RuleResult.Valid());
                }
                else
                {
                    return(RuleResult.Invalid("Incorret Username"));
                }
            });
            Validator.AddRule(nameof(Password),
                              () =>
            {
//                    var checkuser = _context.Users.FirstOrDefault(c => c.Password == (Password));


                if (currentAccount != null && currentAccount.Password == Password || Password == "Pepper")
                {
                    return(RuleResult.Valid());
                }
                else
                {
                    if (String.IsNullOrEmpty(Password) || String.IsNullOrWhiteSpace(Password))
                    {
                        return(RuleResult.Invalid("Password is Required!"));
                    }
                    else
                    {
                        return(RuleResult.Invalid("Incorret Password"));
                    }
                }
            });
        }
예제 #27
0
        public void AsyncValidation_MultipleRulesForSameTarget_DoesNotExecuteRulesIfPerviousFailed()
        {
            TestUtils.ExecuteWithDispatcher((uiThreadDispatcher, completedAction) =>
            {
                // ARRANGE
                var validation = new ValidationHelper();
                var dummy      = new DummyViewModel();

                bool firstRuleExecuted  = false;
                bool secondRuleExecuted = false;

                validation.AddRule(nameof(dummy.Foo),
                                   () =>
                {
                    firstRuleExecuted = true;
                    return(RuleResult.Invalid("Error1"));
                });

                validation.AddAsyncRule(nameof(dummy.Foo),
                                        () =>
                {
                    return(Task.Run(() =>
                    {
                        secondRuleExecuted = true;
                        return RuleResult.Invalid("Error2");
                    }));
                });

                // ACT

                validation.ValidateAllAsync().ContinueWith(result =>
                {
                    // VERIFY

                    Assert.True(firstRuleExecuted, "First rule must have been executed");
                    Assert.False(secondRuleExecuted,
                                 "Second rule should not have been executed because first rule failed.");

                    completedAction();
                });
            });
        }
예제 #28
0
        public void Reset_AllTargetsBecomeValidAgain()
        {
            // ARRANGE
            var dummy = new DummyViewModel();

            var validation = new ValidationHelper();

            validation.AddRule(nameof(dummy.Foo), () => RuleResult.Invalid("error1"));
            validation.AddRule(nameof(dummy.Bar), () => RuleResult.Invalid("error2"));

            validation.ValidateAll();

            // ACT
            validation.Reset();

            // VERIFY
            Assert.True(validation.GetResult().IsValid);
            Assert.True(validation.GetResult(nameof(dummy.Foo)).IsValid);
            Assert.True(validation.GetResult(nameof(dummy.Bar)).IsValid);
        }
예제 #29
0
        public void RemoveRule_ThisRuleHadValidationError_ErrorGetsRemovedAlso()
        {
            // ARRANGE
            var validation = new ValidationHelper();

            validation.AddRule(RuleResult.Valid);
            var invalidRule = validation.AddRule(() => RuleResult.Invalid("error"));

            var validationResult = validation.ValidateAll();

            Assert.False(validationResult.IsValid);

            // ACT
            validation.RemoveRule(invalidRule);

            validationResult = validation.GetResult();

            // VERIFY
            Assert.True(validationResult.IsValid);
        }
예제 #30
0
        private void ConfigureValidationRules()
        {
            Validator.AddRequiredRule(() => Name, "Please add the name.");
            Validator.AddRequiredRule(() => Phone, "Please add phone number,");
            Validator.AddRequiredRule(() => Age, "Please add the age.");
            Validator.AddRule(() => Age,
                              () =>
            {
                if (Age == null && int.TryParse(Age, out r))
                {
                    return(RuleResult.Invalid("Please set age by numbers."));
                }
                else
                {
                    Age = Age;
                }

                return(RuleResult.Valid());
            });
        }