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()); }); }
public void AddChildValidatableCollection_OneRuleThrowsException_EntireValidationFails() { TestUtils.ExecuteWithDispatcher((uiThreadDispatcher, completedAction) => { // ARRANGE var parent = new ValidatableViewModel(); var child1 = new ValidatableViewModel(); var child2 = new ValidatableViewModel(); parent.Children = new List <IValidatable> { child1, child2 }; parent.Validator.AddAsyncRule(() => TaskEx.FromResult(RuleResult.Valid())); child1.Validator.AddAsyncRule( () => Task.Factory.StartNew <RuleResult>(() => { throw new FakeException(); })); child2.Validator.AddAsyncRule(() => TaskEx.FromResult(RuleResult.Valid())); parent.Validator.AddChildValidatableCollection(() => parent.Children); // ACT parent.Validator.ValidateAllAsync().ContinueWith(r1 => { uiThreadDispatcher.BeginInvoke(new Action(() => { Assert.NotNull(r1.Exception); Assert.IsType <FakeException>(ExceptionUtils.UnwrapException(r1.Exception)); completedAction(); })); }); }); }
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); }
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("Ошибка валидации регистрационного номера")); } }
public void AsyncValidation_ExecutedInsideUIThreadTask_ValidationRunsInBackgroundThread() { // This test checks the situation described here: // http://stackoverflow.com/questions/6800705/why-is-taskscheduler-current-the-default-taskscheduler // In short: if a continuation of a task runs on the UI thread, then the tasks that you start using // Task.Factory.StartNew will run also on the UI thread. This is unexpected an may cause a deadlock, or freezing UI. TestUtils.ExecuteWithDispatcher((uiThreadDispatcher, completedAction) => { // ARRANGE var validation = new ValidationHelper(); var dummy = new DummyViewModel(); int uiThreadId = Thread.CurrentThread.ManagedThreadId; int validationThreadId = uiThreadId; validation.AddAsyncRule(nameof(dummy.Foo), () => { return(Task.Run(() => { validationThreadId = Thread.CurrentThread.ManagedThreadId; return RuleResult.Valid(); })); }); // ACT // Execute validation within a continuation of another task that runs on // current synchronization context, so that the TaskScheduler.Current is set to the // UI context. Task.Factory.StartNew(() => { }).ContinueWith(t => { Task <ValidationResult> task = validation.ValidateAllAsync(); task.ContinueWith(result => { // VERIFY // Schedule the varification code with the dispatcher in order to take it // out of the ContinueWith continuation. Otherwise the exceptions will be stored inside the task and // unit testing framework will not know about them. uiThreadDispatcher.BeginInvoke(new Action(() => { Assert.False(uiThreadId == validationThreadId, "Validation must be executed in a background thread, so that the UI thread is not blocked."); completedAction(); })); }); }, TaskScheduler.FromCurrentSynchronizationContext()); }); }
public void AsyncValidation_SeveralAsyncRules_AllExecutedBeforeValidationCompleted() { TestUtils.ExecuteWithDispatcher((dispatcher, completedAction) => { var vm = new DummyViewModel(); vm.Foo = null; var validation = new ValidationHelper(); bool rule1Executed = false; validation.AddAsyncRule(() => { return(Task.Run(() => { rule1Executed = true; return RuleResult.Valid(); })); }); bool rule2Executed = false; validation.AddAsyncRule(() => { return(Task.Run(() => { rule2Executed = true; return RuleResult.Valid(); })); }); bool rule3Executed = false; validation.AddAsyncRule(() => { return(Task.Run(() => { rule3Executed = true; return RuleResult.Valid(); })); }); validation.ValidateAllAsync().ContinueWith(r => { Assert.True(rule1Executed); Assert.True(rule2Executed); Assert.True(rule3Executed); Assert.True(r.Result.IsValid); completedAction(); }); }); }
void ConfigureRules() { Validator.AddAsyncRule(() => UpdatePayment, async() => { if (SelectedTransaction.Balance < UpdatePayment || UpdatePayment == null) { return(RuleResult.Invalid("Invalid Payment")); } else { return(RuleResult.Valid()); } }); }
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"); } }
public async void AsyncValidation_RuleThrowsException_ExceptionIsPropogated() { // ARRANGE var validator = new ValidationHelper(); validator.AddAsyncRule(async() => { await Task.Factory.StartNew(() => { throw new InvalidOperationException("Test"); }, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default); return(RuleResult.Valid()); }); // ACT & VERIFY await Assert.ThrowsAsync <ValidationException>(() => validator.ValidateAllAsync()); }
public void AsyncValidation_SeveralAsyncRules_AllExecutedBeforeValidationCompleted() { TestUtils.ExecuteWithDispatcher((dispatcher, completedAction) => { var vm = new DummyViewModel(); vm.Foo = null; var validation = new ValidationHelper(); bool rule1Executed = false; validation.AddAsyncRule(setResultDelegate => ThreadPool.QueueUserWorkItem(_ => { rule1Executed = true; setResultDelegate(RuleResult.Valid()); })); bool rule2Executed = false; validation.AddAsyncRule(setResultDelegate => ThreadPool.QueueUserWorkItem(_ => { rule2Executed = true; setResultDelegate(RuleResult.Valid()); })); bool rule3Executed = false; validation.AddAsyncRule(setResultDelegate => ThreadPool.QueueUserWorkItem(_ => { rule3Executed = true; setResultDelegate(RuleResult.Valid()); })); validation.ValidateAllAsync().ContinueWith(r => { Assert.True(rule1Executed); Assert.True(rule2Executed); Assert.True(rule3Executed); Assert.True(r.Result.IsValid); completedAction(); }); }); }
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(); }
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")); } } }); }
public async void MixedValidation_SyncRuleThrowsExceptionAfterSuccesfullAsyncRule_ExceptionIsPropogated() { // ARRANGE var validator = new ValidationHelper(); validator.AddAsyncRule(async() => { return(await Task.Run(() => RuleResult.Valid())); }); validator.AddRule(() => { throw new InvalidOperationException("Test"); }); // ACT & VERIFY var task = Assert.ThrowsAsync <ValidationException>(() => validator.ValidateAllAsync()); if (task != await Task.WhenAny(task, Task.Delay(TimeSpan.FromSeconds(5)))) { Assert.True(false, "Looks like the validation is stuck (didn't complete in a timeout), which means it didn't handle the exception properly."); } }
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()); }); }
private void AddRules() { Validator.AddRequiredRule(() => FirstName, "Vorname ist ein Pflichtfeld"); Validator.AddRequiredRule(() => LastName, "Nachname ist ein Pflichtfeld"); Validator.AddRequiredRule(() => Street, "Strasse ist ein Pflichtfeld"); Validator.AddRequiredRule(() => Zip, "Postleitzahl ist ein Pflichtfeld"); Validator.AddRequiredRule(() => City, "Ort ist ein Pflichtfeld"); Validator.AddRule(nameof(Email), () => { if (!string.IsNullOrEmpty(Email)) { return(RuleResult.Assert(Regex.IsMatch(Email, @"\A(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)\Z", RegexOptions.IgnoreCase), "Email-Adresse ungültig")); } return(RuleResult.Valid()); }); }
private void ConfigureValidationRules() { //Validator.AddRequiredRule(() => FilePath, "لطفا ویدئوی مربوطه را وارد کنید"); Validator.AddRule(() => euser, () => { if (euser == null) { return(RuleResult.Invalid("لطفا فرد وارد کننده لغت را وارد کنید")); } return(RuleResult.Valid()); }); Validator.AddRule(() => User_id, () => { if (User_id == 0) { return(RuleResult.Invalid("لطفا فرد وارد کننده لغت را وارد کنید")); } return(RuleResult.Valid()); }); }
public void ValidateAllAsync_SimilteniousCalls_DoesNotFail() { TestUtils.ExecuteWithDispatcher((dispatcher, completedAction) => { const int numThreadsPerIternation = 4; const int iterationCount = 10; const int numThreads = numThreadsPerIternation * iterationCount; var resetEvent = new ManualResetEvent(false); int toProcess = numThreads; var validation = new ValidationHelper(); for (int i = 0; i < iterationCount; i++) { var target1 = new object(); var target2 = new object(); validation.AddAsyncRule(setResult => { setResult(RuleResult.Invalid("Error1")); }); validation.AddAsyncRule(target1, setResult => { setResult(RuleResult.Valid()); }); validation.AddRule(target2, () => { return(RuleResult.Invalid("Error2")); }); validation.AddRule(target2, RuleResult.Valid); Action <Action> testThreadBody = exercise => { try { exercise(); if (Interlocked.Decrement(ref toProcess) == 0) { resetEvent.Set(); } } catch (Exception ex) { dispatcher.BeginInvoke(new Action(() => { throw new AggregateException(ex); })); } }; var thread1 = new Thread(() => { testThreadBody(() => { validation.ValidateAllAsync().Wait(); }); }); var thread2 = new Thread(() => { testThreadBody(() => { validation.ValidateAllAsync().Wait(); }); }); var thread3 = new Thread(() => { testThreadBody(() => { validation.Validate(target2); }); }); var thread4 = new Thread(() => { testThreadBody(() => { validation.Validate(target2); }); }); thread1.Start(); thread2.Start(); thread3.Start(); thread4.Start(); } ThreadPool.QueueUserWorkItem(_ => { resetEvent.WaitOne(); completedAction(); }); }); }
private void ConfigureValidationRules() { Validator.AddRequiredRule(() => Name, "لطفا عبارت مورد نظر را وارد کنید"); Validator.AddRequiredRule(() => wordType, "لطفا نوع عبارت را وارد کنید"); Validator.AddRequiredRule(() => SelectedWordType, "لطفا نوع لغت را انتخاب کنید"); Validator.AddRule(() => SelectedWordType, () => { if (SelectedWordType.ID == null || object.Equals(SelectedWordType.ID, string.Empty)) { return(RuleResult.Invalid("نوع لغت نامعتبر است")); } else { wordType = UtilityClass.ParseEnum <WordType>(SelectedWordType.ID.Value.ToString()); } return(RuleResult.Valid()); }); Validator.AddRequiredRule(() => SelectedLanguage, "لطفا زبان مورد نظر این لغت را انتخاب کنید"); Validator.AddRule(() => SelectedLanguage, () => { if (SelectedLanguage.ID == null || object.Equals(SelectedLanguage.ID, string.Empty)) { return(RuleResult.Invalid("زبان لغت نامعتبر است")); } else { elang = new Languages { lang_id = SelectedLanguage.ID.Value, Name = SelectedLanguage.Value }; } return(RuleResult.Valid()); }); //Validator.AddRule(() => Langid, // () => // { // if (Langid == 0) // { // return RuleResult.Invalid("لطفا زبان مورد نظر این لغت را انتخاب کنید"); // } // return RuleResult.Valid(); //// }); //Validator.AddRule(() => euser, // () => // { // if (euser == null) // { // return RuleResult.Invalid("لطفا فرد وارد کننده لغت را وارد کنید"); // } // return RuleResult.Valid(); // }); //Validator.AddRule(() => User_id, // () => // { // if (User_id == 0) // { // return RuleResult.Invalid("لطفا فرد وارد کننده لغت را وارد کنید"); // } // return RuleResult.Valid(); // }); }
private void ConfigureValidationRules() { Validator.AddRequiredRule(() => UserName, "User Name is required"); Validator.AddAsyncRule(nameof(UserName), async() => { var isAvailable = await UserRegistrationService.IsUserNameAvailable(UserName).ToTask(); return(RuleResult.Assert(isAvailable, string.Format("User Name {0} is taken. Please choose a different one.", UserName))); }); Validator.AddRequiredRule(() => FirstName, "First Name is required"); Validator.AddRequiredRule(() => LastName, "Last Name is required"); Validator.AddRequiredRule(() => Email, "Email is required"); Validator.AddRule(nameof(Email), () => { const string regexPattern = @"^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$"; return(RuleResult.Assert(Regex.IsMatch(Email, regexPattern), "Email must by a valid email address")); }); Validator.AddRequiredRule(() => Password, "Password is required"); Validator.AddRule(nameof(Password), () => RuleResult.Assert(Password.Length >= 6, "Password must contain at least 6 characters")); Validator.AddRule(nameof(Password), () => RuleResult.Assert((!Password.All(char.IsLower) && !Password.All(char.IsUpper) && !Password.All(char.IsDigit)), "Password must contain both lower case and upper case letters")); Validator.AddRule(nameof(Password), () => RuleResult.Assert(Password.Any(char.IsDigit), "Password must contain at least one digit")); Validator.AddRule(nameof(PasswordConfirmation), () => { if (!string.IsNullOrEmpty(Password) && string.IsNullOrEmpty(PasswordConfirmation)) { return(RuleResult.Invalid("Please confirm password")); } return(RuleResult.Valid()); }); Validator.AddRule(nameof(Password), nameof(PasswordConfirmation), () => { if (!string.IsNullOrEmpty(Password) && !string.IsNullOrEmpty(PasswordConfirmation)) { return(RuleResult.Assert(Password == PasswordConfirmation, "Passwords do not match")); } return(RuleResult.Valid()); }); Validator.AddChildValidatable(() => InterestSelectorViewModel); }