public ServiceResult <Entity> Post([FromBody] Entity model)
        {
            ServiceResult <Entity> result = null;
            var validatorResult           = validator.Validate(model);

            if (validatorResult.IsValid)
            {
                try
                {
                    result = this.appService.Insert(model);
                }
                catch (Exception ex)
                {
                    result         = new ServiceResult <Entity>();
                    result.Errors  = new string[] { ex.Message };
                    result.Success = false;
                }
            }
            else
            {
                result         = new ServiceResult <Entity>();
                result.Errors  = validatorResult.GetErrors();
                result.Success = false;
            }

            return(result);
        }
        public void validate_property_strongly_typed()
        {
            var person          = new Person();
            var entityValidator = new EntityValidator();
            var result          = entityValidator.Validate(person, p => p.Name);

            result[0].PropertyName.Should().Be.EqualTo("Name");
            result[0].Message.Should().Be.EqualTo(Person.NameErrorMessage);
            result[0].EntityType.Should().Be.EqualTo(typeof(Person));

            person.Name = "jose";
            entityValidator.Validate(person, p => p.Name).Should().Be.Empty();
        }
Example #3
0
        public void validate_property_not_strongly_typed()
        {
            var person          = new Person();
            var entityValidator = new EntityValidator(new ValidatorRunner(new CachedValidationRegistry()));
            var result          = entityValidator.Validate(person, "Name");

            result[0].PropertyName.Should().Be.EqualTo("Name");
            result[0].Message.Should().Be.EqualTo(Person.NameErrorMessage);
            result[0].EntityType.Should().Be.EqualTo(typeof(Person));

            person.Name = "jose";
            entityValidator.Validate(person, "Name").Should().Be.Empty();
        }
Example #4
0
        public virtual void Invalidate()
        {
            _validationResults.Clear();
            ClearValidationErrors();

            ValidationResults results = EntityValidator.Validate(this);

            foreach (var result in results)
            {
                if (result.Key == null)
                {
                    continue;
                }

                var validateEntity = result.Target as IValidate;
                if (validateEntity == null)
                {
                    continue;
                }

                validateEntity.AddValidationErrors(new List <ValidationResult>()
                {
                    result
                });
            }
            OnPropertyChanged(() => HasErrors);
            OnPropertyChanged(() => HasGraphErrors);
        }
Example #5
0
        /// <inheritdoc cref="RepositoryBase{TEntity,TDbContext}.CreateAsync(TEntity)"/>
        public override async Task <(bool success, Guid id)> CreateAsync(TrainingSession entity)
        {
            using EntityLoadLock.Releaser loadLock = EntityLoadLock.Shared.Lock();
            bool saveSuccess;

            try
            {
                EntityValidator.Validate(entity);
                DbContext.Entry(entity.TrainingRoom).State = EntityState.Unchanged;
                DbContext.Set <TrainingSession>().Add(entity);
                int saveResult = await DbContext.SaveChangesAsync();

                // Force the DbContext to fetch the species anew on next query.
                foreach (TrainingSession session in entity.TrainingRoom.TrainingSessions)
                {
                    DbContext.Entry(session).State = EntityState.Detached;
                }
                saveSuccess = Convert.ToBoolean(saveResult);
            }
            catch (Exception ex)
            {
                CreatingEntityFailedException creatingEntityFailedException = new CreatingEntityFailedException($"The entity of type {typeof(TrainingSession).Name} could not be created.", ex);
                Logger.LogError(creatingEntityFailedException, creatingEntityFailedException.Message);
                throw creatingEntityFailedException;
            }
            return(success : saveSuccess, id : entity.Id);
        }
        public void EntityValidator_does_not_run_other_validation_if_property_validation_failed()
        {
            var mockValidator = new Mock <IValidator>();

            mockValidator
            .Setup(v => v.Validate(It.IsAny <EntityValidationContext>(), It.IsAny <InternalMemberEntry>()))
            .Returns(() => new[] { new DbValidationError("ID", "error") });

            var mockUncalledValidator = new Mock <IValidator>(MockBehavior.Strict);

            var entityValidator = new EntityValidator(
                new[]
            {
                new PropertyValidator(
                    "ID",
                    new[] { mockValidator.Object })
            },
                new[] { mockUncalledValidator.Object });

            var mockInternalEntityEntry = Internal.MockHelper.CreateMockInternalEntityEntry(
                new Dictionary <string, object>
            {
                { "ID", -1 }
            });

            var entityValidationResult = entityValidator.Validate(MockHelper.CreateEntityValidationContext(mockInternalEntityEntry.Object));

            Assert.NotNull(entityValidationResult);

            ValidationErrorHelper.VerifyResults(
                new[] { new Tuple <string, string>("ID", "error") }, entityValidationResult.ValidationErrors);
        }
Example #7
0
        public void Core_Validator_Validate()
        {
            var validator   = new EntityValidator <CustomerInfo>(new CustomerInfo());
            var failedRules = validator.Validate();

            Assert.IsTrue(failedRules.Any());
        }
Example #8
0
        /**
         * Check fields and border them in red
         *
         * Return false if any error occured
         */
        private Boolean validate()
        {
            currentAddress = this.addressAdmin.UCAddress.Address;

            Boolean hasNoErrors = true;

            try
            {
                this.resetFieldsColors();

                EntityValidator.Validate <Address>(currentAddress);
            }
            catch (ValidationException)
            {
                hasNoErrors = false;

                String errorMessages = currentAddress.GetValidationErrorMessages();

                if (errorMessages.Contains("PostalCode"))
                {
                    this.addressAdmin.UCAddress.txtBPostalCode.BorderBrush = Brushes.Red;
                }
                if (errorMessages.Contains("City"))
                {
                    this.addressAdmin.UCAddress.txtBCity.BorderBrush = Brushes.Red;
                }
                if (errorMessages.Contains("Street"))
                {
                    this.addressAdmin.UCAddress.txtBStreet.BorderBrush = Brushes.Red;
                }
            }

            return(hasNoErrors);
        }
        public void EntityValidator_does_not_return_error_if_entity_is_valid()
        {
            var mockValidator = new Mock <IValidator>();

            mockValidator
            .Setup(v => v.Validate(It.IsAny <EntityValidationContext>(), It.IsAny <InternalMemberEntry>()))
            .Returns(() => Enumerable.Empty <DbValidationError>());

            var entityValidator = new EntityValidator(
                new[]
            {
                new PropertyValidator(
                    "Name",
                    new[] { mockValidator.Object })
            }, new ValidationAttributeValidator[0]);

            var mockInternalEntityEntry = Internal.MockHelper.CreateMockInternalEntityEntry(
                new Dictionary <string, object>
            {
                { "Name", "abc" }
            });

            var validationResult = entityValidator.Validate(MockHelper.CreateEntityValidationContext(mockInternalEntityEntry.Object));

            Assert.NotNull(validationResult);
            Assert.True(validationResult.IsValid);
        }
        protected override void OnModelUpdated(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var validator = new EntityValidator();

            var result = validator.Validate(bindingContext.Model);

            result.AddToModelState(bindingContext.ModelState);
        }
        public void ValidationError_When_Outside_Bounds()
        {
            var validator = new EntityValidator();

            var entityOutsideRightBound = new Entity()
            {
                Values = new[] { "1234", "12345", "1252", "1234", "4534" }
            };

            var entityOutsideLeftBound = new Entity()
            {
                Values = new List <string>()
            };

            Assert.AreEqual(false, validator.Validate(entityOutsideLeftBound).IsValid);
            Assert.AreEqual(false, validator.Validate(entityOutsideRightBound).IsValid);
        }
        public void No_ValidationError_When_Inclusive_Bounds()
        {
            var validator = new EntityValidator();

            var entityLeftBound = new Entity()
            {
                Values = new[] { "1234" }
            };

            var entityRightBound = new Entity()
            {
                Values = new[] { "1234", "123", "1252", "124323" }
            };


            Assert.AreEqual(true, validator.Validate(entityLeftBound).IsValid);
            Assert.AreEqual(true, validator.Validate(entityRightBound).IsValid);
        }
Example #13
0
 partial void OnContextCreated()
 {
     // Adding validation support when saving.
     this.SavingChanges += (sender, e) =>
     {
         // Throws an exception when invalid.
         EntityValidator.Validate(
             this.GetChangedEntities());
     }
 }
        public static IEntityValidationResult ValidateEntity <T>(T entity)
            where T : IBaseBO
        {
            IEntityValidationResult result = null;

            EntityValidator <T> validator = new EntityValidator <T>();

            result = validator.Validate(entity);

            return(result);
        }
        public void ValidationError_When_Null()
        {
            var validator = new EntityValidator();

            var entityNull = new Entity()
            {
                Values = null
            };

            Assert.AreEqual(false, validator.Validate(entityNull).IsValid);
        }
        public void ValidateReturnsListOfValidationErrorWhenValidationFails()
        {
            var validator = new EntityValidator <TestEntity, TestEntityRules>(new TestEntityFluentValidator());

            var testEntity = new TestEntity
            {
                TestProperty = 3
            };

            var result = validator.Validate(testEntity, TestEntityRules.All);

            result.Errors.Should().HaveCountGreaterThan(0);
        }
        public void ValidateReturnsFailWhenValidationFails()
        {
            var validator = new EntityValidator <TestEntity, TestEntityRules>(new TestEntityFluentValidator());

            var testEntity = new TestEntity
            {
                TestProperty = 3
            };

            var result = validator.Validate(testEntity, TestEntityRules.All);

            result.HasErrors.Should().BeTrue();
        }
Example #18
0
        public void ValidationError_When_More_Than_Or_Equal_5_Characters()
        {
            var validator = new EntityValidator();

            var entity = new Entity()
            {
                Values = new[] { "1234", "12345", "1252" }
            };

            var result = validator.Validate(entity);

            Assert.AreEqual(false, result.IsValid);
        }
Example #19
0
        public void No_ValidationError_When_Less_Than_5_Characters()
        {
            var validator = new EntityValidator();

            var entity = new Entity()
            {
                Values = new[] { "1234", "123", "1252" }
            };

            var result = validator.Validate(entity);

            Assert.AreEqual(true, result.IsValid);
        }
Example #20
0
        public void validate_entire_instance_should_work()
        {
            var person = new Person();

            var entityValidator = new EntityValidator(new ValidatorRunner(new CachedValidationRegistry()));

            var results = entityValidator.Validate(person);

            results.Count.Should().Be.EqualTo(2);

            results[0].PropertyName.Should().Be.EqualTo("Name");
            results[0].EntityType.Should().Be.EqualTo(typeof(Person));
            results[0].Message.Should().Be.EqualTo(Person.NameErrorMessage);

            results[1].PropertyName.Should().Be.EqualTo("Age");
            results[1].EntityType.Should().Be.EqualTo(typeof(Person));
            results[1].Message.Should().Be.EqualTo(Person.AgeErrorMessage);

            person.Name = "Jose";
            person.Age  = 20;
            entityValidator.Validate(person).Should().Be.Empty();
        }
        public void ValidateReturnsNoErrorWhenValidationPasses()
        {
            var validator = new EntityValidator <TestEntity, TestEntityRules>(new TestEntityFluentValidator());

            var testEntity = new TestEntity
            {
                TestProperty = 6
            };

            var result = validator.Validate(testEntity, TestEntityRules.All);

            result.HasErrors.Should().BeFalse();
            result.Errors.Should().HaveCount(0);
        }
Example #22
0
        private ValidationResult ValidateVolunteer(Volunteer volunteer)
        {
            EntityValidator <Volunteer> entityValidator = new EntityValidator <Volunteer>();

            entityValidator.Add("Phone Is Unique"
                                , new ValidationRule <Volunteer>(new VolunteerPhoneIsUniqueSpecifications(_volunteerUnitOfWork.VolunteerRepository)
                                                                 , nameof(volunteer.Phone), VolunteerResource.PhoneExist));

            entityValidator.Add("Email Is Unique"
                                , new ValidationRule <Volunteer>(new VolunteerEmailIsUniqueSpecifications(_volunteerUnitOfWork.VolunteerRepository)
                                                                 , nameof(volunteer.Phone), VolunteerResource.EmailExist));

            return(entityValidator.Validate(volunteer));
        }
Example #23
0
            public void Can_use_UnlessPresent_IsValid()
            {
                // Arrange
                var entity = new Entity {
                    Name = "NotAge", Age = default(int).Some()
                };
                var sut = new EntityValidator();

                // Act
                var result = sut.Validate(entity);

                // Assert
                result.Should().NotBeNull();
                result.IsValid.Should().BeTrue(because: "'Name' is 'NotAge' and 'Age' is Some");
            }
Example #24
0
            public void Can_use_UnlessPresent_IsNotValid()
            {
                // Arrange
                var entity = new Entity {
                    Name = "NotAge", Age = Option.None <int>()
                };
                var sut = new EntityValidator();

                // Act
                var result = sut.Validate(entity);

                // Assert
                result.Should().NotBeNull();
                result.IsValid.Should().BeFalse(because: "'Name' is 'NotAge' and 'Age' is None");
            }
Example #25
0
            public void Can_use_WhenPresent_IsNotValid(int value)
            {
                // Arrange
                var entity = new Entity {
                    Age = value.Some()
                };
                var sut = new EntityValidator();

                // Act
                var result = sut.Validate(entity);

                // Assert
                result.Should().NotBeNull();
                result.IsValid.Should().BeFalse(because: "'Age' is not greater than or equal to 0");
            }
Example #26
0
            public void Can_use_None_IsValid()
            {
                // Arrange
                var entity = new Entity {
                    Age = Option.None <int>()
                };
                var sut = new EntityValidator();

                // Act
                var result = sut.Validate(entity);

                // Assert
                result.Should().NotBeNull();
                result.IsValid.Should().BeTrue(because: "'Age' is None");
            }
Example #27
0
            public void Can_use_None_IsNotValid()
            {
                // Arrange
                var entity = new Entity {
                    Age = 0.Some()
                };
                var sut = new EntityValidator();

                // Act
                var result = sut.Validate(entity);

                // Assert
                result.Should().NotBeNull();
                result.IsValid.Should().BeFalse(because: "'Age' is not None");
            }
Example #28
0
        public virtual DbEntityValidationResult GetValidationResult(
            IDictionary <object, object> items)
        {
            EntityValidator entityValidator    = this.InternalContext.ValidationProvider.GetEntityValidator(this);
            bool            lazyLoadingEnabled = this.InternalContext.LazyLoadingEnabled;

            this.InternalContext.LazyLoadingEnabled = false;
            try
            {
                return(entityValidator != null?entityValidator.Validate(this.InternalContext.ValidationProvider.GetEntityValidationContext(this, items)) : new DbEntityValidationResult(this, Enumerable.Empty <DbValidationError>()));
            }
            finally
            {
                this.InternalContext.LazyLoadingEnabled = lazyLoadingEnabled;
            }
        }
Example #29
0
        public async Task BulkInsert(IList <Transaction> transactions)
        {
            ICollection <ValidationResult> results;
            bool isValid = true;

            foreach (Transaction entity in transactions)
            {
                if (!EntityValidator.Validate <Transaction>(entity, out results))
                {
                    //string jsonString = JsonSerializer.;
                    Log.Information("Invalid Record:" + entity.ToString());
                    isValid = false;
                }
            }
            if (isValid)
            {
                await this.paymentUnitOfWork.TransactionRepository.BulkInsert(transactions);
            }
        }
        protected void ValidateEntity(TEntity entity)
        {
            var validateResult = EntityValidator.Validate(entity);

            if (!validateResult.IsValid)
            {
                var innerExceptions = new List <Exception>();

                foreach (var error in validateResult.Errors)
                {
                    var errorMessage = string.Format(error.ErrorMessage, error.PropertyName);
                    innerExceptions.Add(new BusinessException(errorMessage));
                }

                var exception = new BusinessException("Operation failed in entity validation!", innerExceptions);

                throw exception;
            }
        }
        public void EntityValidator_returns_an_error_if_IValidatableObject_validation_failed()
        {
            var entity = new FlightSegmentWithNestedComplexTypes
            {
            };

            var mockInternalEntityEntry = Internal.MockHelper.CreateMockInternalEntityEntry(entity);

            var entityValidator = new EntityValidator(
                new PropertyValidator[0],
                new[] { MockHelper.CreateValidatableObjectValidator("object", "IValidatableObject is invalid") });

            var entityValidationResult = entityValidator.Validate(MockHelper.CreateEntityValidationContext(mockInternalEntityEntry.Object));

            Assert.NotNull(entityValidationResult);

            ValidationErrorHelper.VerifyResults(
                new[] { new Tuple <string, string>("object", "IValidatableObject is invalid") }, entityValidationResult.ValidationErrors);
        }