public void Validate_ContextUsesDefinedSpecifications() { //Scan all ValidationCatalog.Scan(x => x.TheCallingAssembly()); //Setup entity var customer = new Customer() { Active = true, Employees = new List <Contact>() { new Contact() { Active = true } } }; //Validate var results = ValidationCatalog <DeleteValidationContext> .Validate(customer); Assert.That(results.Errors.First().Message, Is.EqualTo("Active must be false.")); Assert.That(results.Errors[1].NestedValidationResults.First().Message, Is.EqualTo("Contact 1 in Employees is invalid.")); Assert.That(results.Errors[1].NestedValidationResults.First().NestedValidationResults.First().Message, Is.EqualTo("Active must be false.")); }
public void SpecificationAbstract_OnObject_WithSpecification_IsValid() { ValidationCatalog.AddSpecification <BaseClassSpecification>(); ValidationCatalog.AddSpecification <DerivedClassASpecification>(); ValidationCatalog.AddSpecification <DerivedClassBSpecification>(); ValidationCatalog.AddSpecification <ClassWithAbstractPropertySpecification>(); var t = new DerivedClassA(); var a = new ClassWithAbstractProperty { BaseClassProperty = t }; //collection a.BaseClassCollectionProperty = new List <BaseClass>(); //a.BaseClassCollectionProperty.Add(new DerivedClassA()); a.BaseClassCollectionProperty.Add(new DerivedClassB() { BaseName = "Valid" }); var n = ValidationCatalog.Validate(a); Assert.That(n.IsValid, Is.False); Assert.That(n.All().Count(), Is.EqualTo(3)); }
public async Task <IActionResult> CreateUser(UserDto model) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var item = Mapper.Map <UserDto, User>(model); item.CreatedOn = DateTime.UtcNow; item.PasswordHash = _passwordStorage.HashPassword(item, model.Password); var validation = ValidationCatalog.Validate(item); if (validation.IsValid) { var result = await _administrationManager.Create(item); return(new JsonResult(result)); } // Add the errors foreach (var error in validation.Errors) { foreach (var allErrorMessage in error.AllErrorMessages()) { ModelState.AddModelError("Error(s): ", allErrorMessage); } } return(BadRequest(ModelState)); }
public void Collection() { var contact1 = new Contact() { FirstName = "Something", LastName = "Else", Addresses = new List <Entities.Address>() //{ // new Entities.Address()B // { // Street = "Main", // City = "Someplace", // Country = new Country() // { // Id = "US", // Name = "United States" // }, // PostalCode = "12345", // Province = "AA" // } //} }; var results = ValidationCatalog.Validate <ContactSpecification>(contact1); Assert.That(results.IsValid, Is.False); }
protected override bool OnServerValidate(string value) { object objectToValidate; if (GetObject == null) { //Build object from Validators objectToValidate = BuildObjectToValidateFromControls(); } else { //Get the object to validate from the Page objectToValidate = GetObject(); } //Validate the object using the ValidationCatalog var vldNotification = ValidationCatalog.Validate(objectToValidate, GetSpecification()); if (!vldNotification.IsValid) { //Invalid //Raise notification to controls Notify(vldNotification); //Raise OnValidationNotification Event if (ValidationNotification != null) { ValidationNotification(this, new ValidationNotificationEventArgs(vldNotification)); } } return(vldNotification.IsValid); }
/// <summary> /// Set Property on an entity, validate entity and if any errors for property on entity, throw an ArgumentException. /// If Property is updated raises the PropertyChanged event by calling OnPropertyChanged(). /// </summary> /// <typeparam name="T">Type of Entity</typeparam> /// <typeparam name="TProperty">Type of Property being set</typeparam> /// <param name="entity">Instance of entity to change property on.</param> /// <param name="propertyName">Name of property to set.</param> /// <param name="value">Value of to set property to.</param> protected virtual void SetEntityPropertyValue <T, TProperty>(T entity, string propertyName, TProperty value) { PropertyInfo propertyInfo = typeof(T).GetProperty(propertyName); TProperty currentValue = (TProperty)propertyInfo.GetValue(entity, null); propertyInfo.SetValue(entity, value, null); var results = ValidationCatalog.Validate(entity); if (!results.IsValid) { StringBuilder sb = new StringBuilder(); foreach (var result in results.Errors) { if (result.Property.Name == propertyName) { sb.AppendLine(result.Message); } } if (sb.Length > 0) { throw new ArgumentException(sb.ToString()); } } if (!currentValue.Equals(value)) { OnPropertyChanged(propertyName); } }
public async Task <IActionResult> CreateUserAddress(UserAddressDto model) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var item = Mapper.Map <UserAddressDto, UserAddress>(model); var validation = ValidationCatalog.Validate(item); if (validation.IsValid) { var result = await _administrationManager.Create(model.UserId, item); return(new JsonResult(result)); } // Add the errors foreach (var error in validation.Errors) { foreach (var allErrorMessage in error.AllErrorMessages()) { ModelState.AddModelError("Error(s): ", allErrorMessage); } } return(BadRequest(ModelState)); }
public void NoRulesValidationsAreSelected() { //Arrange var catalog = new ValidationCatalog(); catalog.AddValidations(ValidationFinder.ScanAssembly(GetType().Assembly, t => t == typeof(CustomerSimple))); var targetSet = new TargetSet(); targetSet.Add(new CustomerInstance()); //Act var selected = ValidationSelector.Select(catalog, targetSet); //Assert var output = new Output(); output.FormatTable(selected.Select(s => new { Method = s.Validation.Method.Name, Inputs = string.Join(", ", s.Targets.Select(t => t.GetType().Name)) })); output.Report.Verify(); }
public void ValidateMethodCallPropertyOnClass_IsSuccessful() { ValidationCatalog.AddSpecification <StubClass>(validates => validates.Check(x => x.GetCollection()).Required().CountGreaterThan(1)); var c = new StubClass(); Assert.DoesNotThrow(() => ValidationCatalog.Validate(c)); }
public void Validate_Collection_Using_Specified_Specification_WithoutValidateObjectGraph() { //Build test data var validContact = new Contact() { FirstName = "Johnny B", LastName = "Good" }; var invalidContact = new Contact() { FirstName = "Baddy" }; var contacts = new List <Contact>() { validContact, invalidContact }; //Create specification ValidationCatalog.AddSpecification <Contact>(spec => { spec.Check(c => c.FirstName).Required(); spec.Check(c => c.LastName).Required(); }); //Validate var results = ValidationCatalog.Validate(contacts); Assert.That(results.Errors.Count, Is.AtLeast(1)); }
public void FindDescendents_IsValid() { var addressToFind = new Address() { City = "Gatlinburg" }; var primaryAddress = new Address(); var contact = new SpecExpress.Test.Domain.Entities.Contact() { FirstName = "Charles", LastName = "radar", Addresses = new List <Address>() { addressToFind }, PrimaryAddress = primaryAddress }; var allNotfication = ValidationCatalog.Validate <SpecExpress.Test.Domain.Specifications.ContactSpecification>(contact); var filteredNotfication = ValidationCatalog.Validate <SpecExpress.Test.Domain.Specifications.ContactSpecification>(contact) .FindDescendents(v => v.Target == addressToFind) .SelectMany(vr => vr.NestedValidationResults) .ToNotification(); Assert.That(filteredNotfication.IsValid, Is.False); }
public async Task <IActionResult> UpdateUserAddress(UserAddressDto model) { if (!ModelState.IsValid || model.Id == Guid.Empty) { return(BadRequest(ModelState)); } // Find user var found = await _administrationManager.UserAddress(model.Id); if (found != null) { var item = Mapper.Map <UserAddressDto, UserAddress>(model, found); var validation = ValidationCatalog.Validate(item); if (validation.IsValid) { var result = await _administrationManager.Update(item); return(new JsonResult(result)); } // Add the errors foreach (var error in validation.Errors) { foreach (var allErrorMessage in error.AllErrorMessages()) { ModelState.AddModelError("Error(s): ", allErrorMessage); } } return(BadRequest(ModelState)); } return(BadRequest("User address not found")); }
public void When_WithMessageIsSuppliedWithCustomPropetyValueFormat() { var customMessage = "Dope! It's required!"; //Add a rule ValidationCatalog.AddSpecification <Contact>( spec => spec.Check(c => c.DateOfBirth).Required() .IsInPast().With(m => { m.Message = "Date must be in the past. You entered {PropertyValue}."; m.FormatProperty = s => s.ToShortDateString(); })); //String.Format("{0} must be less than {1}", m.PropertyName, m.PropertyValue.ToString("mm/dd/yyyy")))); //dummy data var contact = new Contact() { FirstName = "Joesph", LastName = "Smith", DateOfBirth = System.DateTime.Now.AddYears(1) }; //Validate var valNot = ValidationCatalog.Validate(contact); Assert.That(valNot.Errors, Is.Not.Empty); Assert.That(valNot.Errors.First().Message, Is.EqualTo("Too long 5")); }
public async Task <IActionResult> CreateClaim(UserClaimDto model) { if (!ModelState.IsValid || model.UserId == Guid.Empty) { return(BadRequest(ModelState)); } var item = Mapper.Map <UserClaimDto, UserClaim>(model); var validation = ValidationCatalog.Validate(item); if (validation.IsValid) { await _administrationManager.Create(model.UserId, new List <UserClaim> { item }); return(new JsonResult(true)); } // Add the errors foreach (var error in validation.Errors) { foreach (var allErrorMessage in error.AllErrorMessages()) { ModelState.AddModelError("Error(s): ", allErrorMessage); } } return(BadRequest(ModelState)); }
public void When_validated_with_ExplicitSpecification() { //Don't implicitly validate object graph ValidationCatalog.ValidateObjectGraph = false; var customer = new Customer { Name = "SampleCustomer", Address = new Address() { Country = new Country() { Id = "DE", Name = "Germany" }, Street = "1234 Offenbacher Strasse" } }; //Add Specification for Customer for international addresses ValidationCatalog.SpecificationContainer.Add(new InternationalAddressSpecification()); ValidationCatalog.AddSpecification <Customer>(spec => spec.Check(c => c.Address).Required().Specification <InternationalAddressSpecification>()); //Validate Customer var results = ValidationCatalog.Validate(customer); Assert.That(results.Errors, Is.Not.Empty); Assert.That(results.Errors.First().NestedValidationResults, Is.Not.Empty); }
public void SpecificationExpression() { var customer = new Customer { Name = "SampleCustomer", Contacts = new List <Contact>() { new Contact() { LastName = "Smith" } }, Address = new Address() { Country = new Country() { Id = "DE", Name = "Germany" }, Street = "1234 Offenbacher Strasse" } }; ValidationCatalog.SpecificationContainer.Add(new CustomerAddressSpecification()); var results = ValidationCatalog.Validate(customer); Assert.That(results.Errors, Is.Not.Empty); }
public void ValidateConcurrently() { ValidationCatalog.AddSpecification <Customer>(s => s.Check(c => c.Name).Required().MaxLength(50)); Customer customer1 = new Customer() { Name = string.Empty.PadLeft(55, 'X') }; Customer customer2 = new Customer() { Name = string.Empty.PadLeft(45, 'X') }; var childThread = new Thread(() => { var customer1Notification = ValidationCatalog.Validate(customer1); Assert.IsFalse(customer1Notification.IsValid); }); childThread.Start(); var customer2Notification = ValidationCatalog.Validate(customer2); Assert.IsTrue(customer2Notification.IsValid); childThread.Join(); }
public void InheritedSpecifications_PolymorphicListProperty() { var invalidInheritedClassA = new InheritedClassA(); invalidInheritedClassA.Name = "valid"; //NULL: invalidInheritedClassA.AdditionalProperty var validInheritedClassB = new InheritedClassB(); validInheritedClassB.Name = "valid"; var classA = new ClassA(); classA.BaseProperty = validInheritedClassB; classA.BasePropertyList = new List <MyBaseClass>() { invalidInheritedClassA, validInheritedClassB }; var vn = ValidationCatalog.Validate(classA); var d = vn.FindDescendents(desc => desc.Property.Name == "BasePropertyList").ToList(); Assert.That(d.Any(), Is.True); }
public TestValidationRuleChecker() { var validationCatalog = new ValidationCatalog(); _validations = validationCatalog; validationCatalog.AddValidations(ValidationFinder.ScanAssembly(GetType().Assembly)); }
public void AssertConfigurationValid_IsInvalid() { Assert.Throws <SpecExpressConfigurationException>( () => { ValidationCatalog.AssertConfigurationIsValid(); }); }
public void Validate_Property_With_NullCondition_IsValid() { // String.IsNullOrEmpty(c.Addresses[0].City) should throw an exception ValidationCatalog.AddSpecification <Contact>(spec => spec.Check(c => c.FirstName).If(c => String.IsNullOrEmpty(c.Addresses[0].City)).Required()); var vn = ValidationCatalog.Validate(new Contact()); Assert.That(vn.IsValid, Is.True); }
public void Setup() { ValidationCatalog.Reset(); //Load specifications Assembly assembly = Assembly.LoadFrom("SpecExpress.Test.Domain.dll"); ValidationCatalog.Scan(x => x.AddAssembly(assembly)); }
public void Scan_AppDomainForSpecification_SpecsFound() { //In Resharper Unit Test, generates: //NotSupportedException: The invoked member is not supported in a dynamic assembly //Set Assemblies to scan for Specifications ValidationCatalog.Scan(x => x.AddAssemblies(AppDomain.CurrentDomain.GetAssemblies().ToList())); Assert.That(ValidationCatalog.SpecificationContainer.GetAllSpecifications().Any(), Is.True); }
private List <ValidationResult> validateProperty() { var controlValue = GetControlValidationValue(ControlToValidate); var value = TryConvertControlValue(controlValue); var objToValidate = setPropertyOnProxyObject(value); var results = ValidationCatalog.ValidateProperty(objToValidate, PropertyName, CurrentSpecificationBase).Errors; return(results); }
public static IValidationCatalog Seek(params Assembly[] assemblies) { var catalog = new ValidationCatalog(); foreach (var assembly in assemblies) { catalog.AddValidations(ValidationFinder.ScanAssembly(assembly)); } return(catalog); }
public void TheCallingAssembly_FindsSpecifications() { Assembly assembly = Assembly.LoadFrom("SpecExpress.Test.Domain.dll"); //Set Assemblies to scan for Specifications ValidationCatalog.Scan(x => x.AddAssembly(assembly)); //Assert.That(ValidationCatalog.Registry, Is.Not.Empty); Assert.That(ValidationCatalog.SpecificationContainer.GetSpecification <Address>(), Is.Not.Null); }
public void Advanced() { var contact1 = new Contact() { FirstName = "Something", LastName = "Else" }; var results = ValidationCatalog.Validate <ContactSpecification>(contact1); Assert.That(results.IsValid, Is.False); }
public void Scan_PathForSpecification_SpecsFound() { //Set Assemblies to scan for Specifications Assembly assembly = Assembly.LoadFrom("SpecExpress.Test.Domain.dll"); ValidationCatalog.Scan(x => x.AddAssembly(assembly)); //ValidationCatalog.Scan(x => x.AddAssembliesFromPath(@"C:\Dev\SpecExpress\trunk\SpecExpress\src\SpecExpressTest\bin\Debug")); Assert.That(ValidationCatalog.SpecificationContainer.GetAllSpecifications().Any(), Is.True); }
public void Validate_OptionalNestedProperty_WithNullValue_IsValid() { var customer = new Customer(); ValidationCatalog.AddSpecification <Customer>(spec => spec.Check(cust => cust.Address.Street).Optional() .MaxLength(255)); var results = ValidationCatalog.Validate(customer); Assert.That(results.Errors, Is.Empty); }
public void Validate_CustomerWithNullContact_WithNestedRequiredRegisteredTypes_IsInValid() { var customerWithMissingContact = new Customer { Name = "Customer" }; ValidationNotification results = ValidationCatalog.Validate(customerWithMissingContact); Assert.That(results.Errors, Is.Not.Empty); //Check that null PrimaryContact only generates 1, error and the validator doesn't continue down the tree Assert.That(results.Errors.Count, Is.EqualTo(1)); }