Ejemplo n.º 1
0
        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));
        }
Ejemplo n.º 4
0
        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);
        }
Ejemplo n.º 5
0
        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);
        }
Ejemplo n.º 6
0
        /// <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));
        }
Ejemplo n.º 8
0
        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();
        }
Ejemplo n.º 9
0
        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));
        }
Ejemplo n.º 10
0
        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"));
        }
Ejemplo n.º 13
0
        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));
        }
Ejemplo n.º 15
0
        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);
        }
Ejemplo n.º 16
0
        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);
        }
Ejemplo n.º 17
0
        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();
        }
Ejemplo n.º 18
0
        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);
        }
Ejemplo n.º 19
0
        public TestValidationRuleChecker()
        {
            var validationCatalog = new ValidationCatalog();

            _validations = validationCatalog;
            validationCatalog.AddValidations(ValidationFinder.ScanAssembly(GetType().Assembly));
        }
Ejemplo n.º 20
0
 public void AssertConfigurationValid_IsInvalid()
 {
     Assert.Throws <SpecExpressConfigurationException>(
         () =>
     {
         ValidationCatalog.AssertConfigurationIsValid();
     });
 }
Ejemplo n.º 21
0
        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);
        }
Ejemplo n.º 22
0
        public void Setup()
        {
            ValidationCatalog.Reset();

            //Load specifications
            Assembly assembly = Assembly.LoadFrom("SpecExpress.Test.Domain.dll");

            ValidationCatalog.Scan(x => x.AddAssembly(assembly));
        }
Ejemplo n.º 23
0
        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);
        }
Ejemplo n.º 24
0
        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);
        }
Ejemplo n.º 25
0
        public static IValidationCatalog Seek(params Assembly[] assemblies)
        {
            var catalog = new ValidationCatalog();

            foreach (var assembly in assemblies)
            {
                catalog.AddValidations(ValidationFinder.ScanAssembly(assembly));
            }
            return(catalog);
        }
Ejemplo n.º 26
0
        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);
        }
Ejemplo n.º 27
0
        public void Advanced()
        {
            var contact1 = new Contact()
            {
                FirstName = "Something", LastName = "Else"
            };

            var results = ValidationCatalog.Validate <ContactSpecification>(contact1);

            Assert.That(results.IsValid, Is.False);
        }
Ejemplo n.º 28
0
        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);
        }
Ejemplo n.º 29
0
        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);
        }
Ejemplo n.º 30
0
        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));
        }