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> 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 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); }
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 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 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 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 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 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 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 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(); }
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 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 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 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 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 SpecificationInheritance_OnObject_WithSpecification_IsValid() { ValidationCatalog.AddSpecification <BaseClassSpecification>(); ValidationCatalog.AddSpecification <DerivedClassASpecification>(); var a = new DerivedClassA(); var n = ValidationCatalog.Validate(a); Assert.That(n.IsValid, Is.False); Assert.That(n.All().Count(), Is.EqualTo(2)); }
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 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)); }
public void ForEachSpecification_Warn_IsValid() { //Don't implicitly validate object graph ValidationCatalog.ValidateObjectGraph = false; //create list of contacts to validate var contacts = new List <Contact> { new Contact() { FirstName = String.Empty, LastName = "Smith" }, new Contact() { FirstName = String.Empty, LastName = String.Empty }, new Contact() { FirstName = "Joe", LastName = "Smith" } }; var customer = new Customer() { Name = "Smith Industries", Contacts = contacts }; //Add Specification for Customer and Address ValidationCatalog.AddSpecification <Customer>(spec => { spec.Check(c => c.Contacts).Required(); spec.Warn(c => c.Contacts).Optional().ForEachSpecification <Contact>( cspec => { cspec.Warn(c => c.LastName).Required(); cspec.Warn(c => c.FirstName).Required(); }); }); //Validate Customer var results = ValidationCatalog.Validate(customer); Assert.That(results.Errors, Is.Not.Empty); Assert.IsTrue(results.IsValid); var allerrors = results.Errors.First().AllErrorMessages().ToList(); Assert.That(results.Errors.First().NestedValidationResults, Is.Not.Empty); }
/// <summary> /// The validate. /// </summary> /// <param name="toValidationInstance"> /// The message. /// </param> /// <returns> /// The <see cref="ValidationNotification"/>. /// </returns> /// <exception cref="CommandValidationException"> /// If the message is not valid the exception will be thrown /// </exception> public ValidationNotification Validate(object toValidationInstance) { if (toValidationInstance == null) { throw new ArgumentNullException("toValidationInstance"); } if (this.logger == null) { this.logger = new NullLogger(); } var messageType = toValidationInstance.GetMessageType(); this.logger.Debug(() => "Unity Of Work Id: {0}".FormatWith(this.resolver.GetHashCode())); ValidationContextUnitOfWork.SetUnitOfWorkId(this.resolver); var spec = ValidationCatalog <ValidationContextUnitOfWork> .SpecificationContainer.TryGetSpecification(messageType); if (spec == null) { this.logger.Debug(() => string.Format("no specifications found for {0}", messageType.FullName)); return(new ValidationNotification()); } this.logger.Debug(() => string.Format("Validating {0}", messageType.FullName)); var validationResults = ValidationCatalog <ValidationContextUnitOfWork> .Validate(toValidationInstance); if (validationResults.IsValid) { this.logger.Debug(() => string.Format("Validation succeeded for message: {0}", messageType.FullName)); return(validationResults); } var errorMessage = new StringBuilder(); errorMessage.Append( string.Format( "Validation failed for message {0}, with the following errors/s: " + Environment.NewLine, messageType.FullName)); foreach (var validationResult in validationResults.Errors) { errorMessage.Append(string.Join(Environment.NewLine, validationResult.AllErrorMessages().ToArray())); } this.logger.Debug(this.ToErrorMessage(validationResults).ToString); return(validationResults); }
public void Enum_ValueIsFirstValue_IsRequired() { ValidationCatalog.AddSpecification <Person>(spec => spec.Check(p => p.PersonGender).Required()); var person = new Person() { PersonGender = Gender.Male }; var vn = ValidationCatalog.Validate(person); Assert.That(vn.IsValid, Is.True); }
public bool IsValid() { ValidationCatalog.AddSpecification <Contact>(x => { x.Check(contact => contact.LastName).Required(); x.Check(contact => contact.FirstName).Required(); x.Check(contact => contact.DateOfBirth).Optional(). GreaterThan(new DateTime(1950, 1, 1)); }); //Validate Errors = ValidationCatalog.Validate(this); return(Errors.IsValid); }
public void InvalidExpression_IsInvalid() { ValidationCatalog.AddSpecification <Contact>(x => x.Check(c => c.NumberOfDependents).Required(). GreaterThan(z => new BadWolf().Max(z.NumberOfDependents))); var contact = new Contact() { LastName = "Bill" }; var results = ValidationCatalog.Validate(contact); Assert.That(results.Errors, Is.Not.True); }
public void ValidationNotification_WithOneError_IsValid() { ValidationCatalog.AddSpecification <Customer>(spec => { spec.Check(c => c.Name).Required(); spec.Warn(c => c.Address).Required().Specification <AddressSpecification>(); }); var customer = new Customer(); var vn = ValidationCatalog.Validate(customer); Assert.That(vn.IsValid, Is.False); }
public void Validate_Property_Label_Is_Available_On_Error_When_Invalid() { const string expected = "This is a custom rule label"; ValidationCatalog.AddSpecification <Contact>(spec => spec.Check(c => c.FirstName).WithLabel(expected).Required()); var contact = new Contact(); var vn = ValidationCatalog.Validate(contact); Assert.That(vn.IsValid, Is.False); var error = vn.Errors.Single(); Assert.AreEqual(expected, error.Label); }
public void Validate_Property_With_CustomName_IsValid_And_Label_Is_Set() { const string expected = "This is a custom rule label"; ValidationCatalog.AddSpecification <Contact>(spec => spec.Check(c => c.FirstName).WithLabel(expected) .If(c => String.IsNullOrEmpty(c.Addresses[0].City)).Required()); var vn = ValidationCatalog.Validate(new Contact()); Assert.That(vn.IsValid, Is.True); var actual = ValidationCatalog.SpecificationContainer.GetAllSpecifications().Single().PropertyValidators.Single().Label; Assert.AreEqual(expected, actual); }