Ejemplo n.º 1
0
        public EntityValidationResult IsValid(Customer customer)
        {
            try
            {
                if (customer == null)
                {
                    throw new ArgumentException("Customer invalid");
                }

                var validation = new EntityValidationResult();

                validation.Status             = true;
                validation.ValidationMessages = new List <string>();

                if (!CpfCnpjService.IsCpfCnpj(customer.DocumentId))
                {
                    validation.Status = false;
                    validation.ValidationMessages.Add("CPF/CNPJ invalid");
                }

                if (customer.CustomerId == 0 && !IsDocumentIdUnique(customer.DocumentId))
                {
                    validation.Status = false;
                    validation.ValidationMessages.Add("CPF/CNPJ already exists");
                }

                return(validation);
            }
            catch (Exception)
            {
                throw;
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Determine if rules for a resetting a password are met using property data
        /// annotation in the class CustomerLogin. Rules for a password are done
        /// in <see cref="PasswordCheck"/> class.
        /// </summary>
        private void ProcessLogin()
        {
            EntityValidationResult validationResult = ValidationHelper.ValidateEntity(_customerLogin);

            if (validationResult.HasError)
            {
                _retryCount += 1;

                if (_retryCount >= 3)
                {
                    MessageBox.Show("Too many attempts");
                    Application.Current.Shutdown();
                }
                else
                {
                    MessageBox.Show(validationResult.ErrorMessageList());
                }
            }
            else
            {
                Hide();

                var workWindow = new WorkWindow();
                Application.Current.MainWindow = workWindow;
                workWindow.ShowDialog();

                Close();
            }
        }
        public CommandResult Handle(CreatePersonCommand command)
        {
            if (command == null)
            {
                throw new ArgumentNullException(nameof(command));
            }

            Person person = new Person(command.Name, command.BirthDay);
            EntityValidationResult validationResult = person.Validate();

            if (validationResult.IsValid)
            {
                _personRepository.Insert(person);
                _logger.InfoFormat($"Person создан успешно. Person ID = {person.Id}.");
                return(new CommandResult
                {
                    Succeeded = true,
                    Type = person.Id.GetType(),
                    Value = person.Id
                });
            }
            else
            {
                _logger.ErrorFormat($"Не удалось добавить новый объект Person в репозиторий. Person, созданный на " +
                                    $"основе входных данных, не валиден.");
                return(new CommandResult
                {
                    Succeeded = false,
                    Type = validationResult.Errors.GetType(),
                    Value = validationResult.Errors
                });
            }
        }
Ejemplo n.º 4
0
        public async Task <EntityValidationResult <Delivery> > SendJob(Delivery data)
        {
            try
            {
                var result           = new EntityValidationResult <Delivery>();
                var validationResult = _validator.Validate(data);

                result.IsValid = validationResult.IsValid;
                result.Object  = data;

                if (validationResult.IsValid)
                {
                    data.Id = Guid.NewGuid();

                    _deliveryRepository.Create(data);
                    await _deliveryRepository.SaveAsync();
                }
                else
                {
                    result.Errors = validationResult.Errors.Select(x => new EntityValidationFailure {
                        PropertyName = x.PropertyName, ErrorMessage = x.ErrorMessage
                    }).ToList();
                }

                return(result);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public async Task Then_If_Not_Valid_Then_Returns_Response_With_Errors(
            EntityValidationError entityValidationError,
            CreateVacancyCommand command,
            [Frozen] Mock <IRecruitVacancyClient> recruitVacancyClient,
            CreateVacancyCommandHandler handler)
        {
            command.ValidateOnly = false;
            var entityValidationResult = new EntityValidationResult {
                Errors = new List <EntityValidationError> {
                    entityValidationError
                }
            };

            recruitVacancyClient.Setup(x => x.Validate(It.IsAny <Vacancy>(), VacancyRuleSet.All))
            .Returns(entityValidationResult);

            var actual = await handler.Handle(command, CancellationToken.None);

            actual.ValidationErrors.Should().BeEquivalentTo(
                entityValidationResult.Errors.Select(error => new DetailedValidationError
            {
                Field   = error.PropertyName,
                Message = error.ErrorMessage
            }));
            actual.ResultCode.Should().Be(ResponseCode.InvalidRequest);
        }
        private void ProcessLogin()
        {
            var customerLogin = (CustomerLogin)_bindingSource.Current;

            EntityValidationResult validationResult = ValidationHelper.ValidateEntity(customerLogin);

            if (validationResult.HasError)
            {
                _retryCount += 1;

                if (_retryCount >= 3)
                {
                    MessageBox.Show("Too many attempts");
                    Application.Exit();
                }
                else
                {
                    MessageBox.Show(validationResult.ErrorMessageList());
                }
            }
            else
            {
                Hide();

                var workForm = new WorkForm();
                workForm.ShowDialog();

                Close();
            }
        }
Ejemplo n.º 7
0
        public async Task <EntityValidationResult <Map> > AddMap(Map map)
        {
            try
            {
                var result           = new EntityValidationResult <Map>();
                var validationResult = _validator.Validate(map);

                result.IsValid = validationResult.IsValid;
                result.Object  = map;

                if (validationResult.IsValid)
                {
                    map.Id = Guid.NewGuid();

                    _mapRepository.Create(map);
                    await _mapRepository.SaveAsync();
                }
                else
                {
                    result.Errors = validationResult.Errors.Select(x => new EntityValidationFailure {
                        PropertyName = x.PropertyName, ErrorMessage = x.ErrorMessage
                    }).ToList();
                }

                return(result);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Ejemplo n.º 8
0
        public EntityValidationResult ValidateAOI(AOI aoi, bool isNew, string oldName)
        {
            EntityValidationResult evr = new EntityValidationResult();

            if (isNew && (aoi.Name == null || aoi.Name.Length < 2))
            {
                evr.AddMessage("Device name must be at least 2 letters long");
            }

            if (isNew && (aoi.ID == 0))
            {
                evr.AddMessage("AOI ID cannot be zero");
            }

            if (!isNew && aoi.Name.Length > 0 &&
                oldName != aoi.Name &&
                AOINameExist(aoi.Name))
            {
                evr.AddMessage("AOI name already used");
            }


            if (isNew && aoi.Name.Length > 0 && AOINameExist(aoi.Name))
            {
                evr.AddMessage("AOI name already used");
            }

            return(evr);
        }
Ejemplo n.º 9
0
 private void AssertSingleError(EntityValidationResult result, string propertyName, string errorCode)
 {
     result.HasErrors.Should().BeTrue();
     result.Errors.Should().HaveCount(1);
     result.Errors[0].PropertyName.Should().Be(propertyName);
     result.Errors[0].ErrorCode.Should().Be(errorCode);
     result.Errors[0].RuleId.Should().Be((long)VacancyRuleSet.Qualifications);
 }
Ejemplo n.º 10
0
 private static void AddPermissionError <T>(EntityValidationResult <T> c) where T : class
 {
     c.AddError(new ValidationError
     {
         Title   = "Id",
         Message = "no permission for this entity"
     });
 }
        public void PersonPhoneExample()
        {
            Person person = new () { FirstName = "Bob", LastName = "Jones", SSN = "201518161" };

            EntityValidationResult validationResult = ValidationHelper.ValidateEntity(person);

            Assert.IsTrue(validationResult.HasError);
            Assert.IsTrue(validationResult.ErrorMessageList().Contains("Phone is required"));
        }
Ejemplo n.º 12
0
        /// <summary>
        /// 通过实现此方法来拦截调用并执行所需的拦截行为。
        /// </summary>
        /// <param name="input">调用拦截目标时的输入信息。</param>
        /// <param name="getNext">通过行为链来获取下一个拦截行为的委托。</param>
        /// <returns>从拦截目标获得的返回信息。</returns>
        public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
        {
            if (input == null)
            {
                throw new ArgumentNullException("input");
            }
            if (getNext == null)
            {
                throw new ArgumentNullException("getNext");
            }

            //执行验证操作;
            var tempMethod = input.MethodBase as System.Reflection.MethodInfo;

            var inputParameterCollection = input.Inputs;

            //根据反射获取对象的成员信息
            var realArguments = (object[])ReflectHelper.GetInstanceProperty(inputParameterCollection, "arguments");

            if (inputParameterCollection.Count == 0)
            {
                return(getNext().Invoke(input, getNext));
            }

            //获取方法参数
            //System.Reflection.ParameterInfo[] parameterInfos = input.MethodBase.GetParameters();

            IList <EntityValidationResult> tempResults = new List <EntityValidationResult>();

            foreach (var realArgument in realArguments)
            {
                var entityValidationResult = new EntityValidationResult(realArgument as IAggregateRoot, new List <EntityValidationError>());
                tempResults.Add(entityValidationResult);
            }

            var flag = true;

            //进行数据验证
            flag = this.ValidateInputParameter(realArguments, ref tempResults);
            //if (parameterInfos != null && parameterInfos.Length > 0)
            //{
            //    //验证所有的参数,判定参数类型,是否需要验证
            //    flag = this.ValidateInputParameter(parameterInfos, ref results);
            //}

            //进行业务逻辑验证
            var outMessage = string.Empty;

            //flag = this.ValidateInputParameter(tempMethod,inputParameterCollection, out outMessage);
            if (!flag)
            {
                return(new VirtualMethodReturn(input, new ValidationException(tempResults[0].ValidationErrors.First().ErrorMessage)));
            }

            return(getNext().Invoke(input, getNext));
        }
Ejemplo n.º 13
0
        public static bool Validate(T entity)
        {
            EntityValidationResult result = DataValidation.ValidateEntity(entity);

            if (result.HasError)
            {
                throw new Exception(result.MensagemErro());
            }
            return(true);
        }
Ejemplo n.º 14
0
        protected void ExibeErrosPreencimento(EntityValidationResult result)
        {
            string mensagem = "Erros encontrados no preenchimento dos campos.\n";

            foreach (ValidationResult error in result.ValidationErrors)
            {
                mensagem += error.ErrorMessage;
            }
            MessageBox.Show(mensagem, "Atenção!", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
 private void MapValidationPropertiesToViewModel(EntityValidationResult validationResult)
 {
     foreach (var error in validationResult.Errors)
     {
         if (_mappingDictionary.TryGetValue(error.PropertyName, out string replacementProperty))
         {
             error.PropertyName = replacementProperty;
         }
     }
 }
Ejemplo n.º 16
0
        /// <summary>
        /// Make Validation Operation for Insert/Update Object.
        /// </summary>
        /// <param name="isUpdate">Determines Validation is for update operation.
        /// If true, Validation is for Update operation else Validation Insert Operation.</param>
        /// <returns>Returns IEntityValidationResult object.</returns>
        public IEntityValidationResult ValidateObject(bool isUpdate = false)
        {
            IEntityValidationResult result = this.Validate();

            try
            {
                if (result.FailError == null && result.HasError)
                {
                    if (isUpdate && this.ChangeSetCount > 0)
                    {
                        IList <ValidationResult> resultError = new List <ValidationResult>();
                        List <string>            changeSet   = this.GetColumnChangeList();

                        IEnumerator <string> members;
                        string        errMessage;
                        List <string> lstMembers;

                        foreach (var item in result.Errors)
                        {
                            errMessage = item.ErrorMessage;
                            members    = item.MemberNames.GetEnumerator();
                            lstMembers = new List <string>();
                            while (members.MoveNext())
                            {
                                if (changeSet.Contains(members.Current))
                                {
                                    lstMembers.Add(members.Current);
                                }
                            }

                            if (lstMembers.Count > 0)
                            {
                                resultError.Add(new ValidationResult(errMessage, lstMembers.AsEnumerable()));
                            }
                        }

                        result = new EntityValidationResult(resultError);

                        /*
                         *  string idProp = this.GetIdColumn();
                         *  if (!string.IsNullOrWhiteSpace(idProp))
                         *  {
                         *      PropertyInfo prpId=
                         *  }
                         */
                    }
                }
            }
            catch (Exception e)
            {
                throw;
            }

            return(result);
        }
Ejemplo n.º 17
0
        protected void MapValidationPropertiesToViewModel(EntityValidationResult validationResult)
        {
            var mappingDictionary = BuildMappingDictionary();

            foreach (var error in validationResult.Errors)
            {
                if (mappingDictionary.TryGetValue(error.PropertyName, out string replacementProperty))
                {
                    error.PropertyName = replacementProperty;
                }
            }
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Combine error validation text for display, in this case a MessageBox.
        /// </summary>
        /// <param name="sender"></param>
        /// <returns>Current validation issue</returns>
        public static string ErrorMessageList(this EntityValidationResult sender)
        {
            var sb = new StringBuilder();

            sb.AppendLine("Validation issues\n");

            foreach (var errorItem in sender.Errors)
            {
                sb.AppendLine(errorItem.SanitizedErrorMessage() + "\n");
            }

            return(sb.ToString());
        }
Ejemplo n.º 19
0
        public void CustomerApplication_IsValid_ShouldReturnTrue()
        {
            // Arrange
            var customerApp = Fixture.GetCustomerAppService();
            var customer    = Fixture.GenerateValidCustomer();

            // Act
            EntityValidationResult validation = customerApp.IsValid(customer);

            // Assert Fluent Assertions
            validation.Status.Should().BeTrue();
            validation.ValidationMessages.Should().HaveCount(c => c == 0);
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Generic extension method yielding objects of specified type from table.
        /// </summary>
        /// <remarks>Exceptions are not catched. It works on all or nothing basis.
        /// Only primitives and enums are supported as property.
        /// Currently supports only tables with header.</remarks>
        /// <typeparam name="T">Type to map to. Type should be a class and should have parameterless constructor.</typeparam>
        /// <param name="table">Table object to fetch</param>
        /// <param name="skipCastErrors">Determines how the method should handle exceptions when casting cell value to property type.
        /// If this is true, invalid casts are silently skipped, otherwise any error will cause method to fail with exception.</param>
        /// <returns>An enumerable of the generating type</returns>
        public static IEnumerable <T> AsEnumerable <T>(this ExcelTable table, bool skipCastErrors = false) where T : class, new()
        {
            IList mapping = PrepareMappings <T>(table);

            ExcelAddress bounds = table.GetDataBounds();

            // Parse table
            for (int row = bounds.Start.Row; row <= bounds.End.Row; row++)
            {
                var item = (T)Activator.CreateInstance(typeof(T));

                foreach (KeyValuePair <int, PropertyInfo> map in mapping)
                {
                    object cell = table.WorkSheet.Cells[row, map.Key + table.Address.Start.Column].Value;

                    PropertyInfo property = map.Value;

                    try
                    {
                        TrySetProperty(item, property, cell);

                        // Validate parsed object according to data annotations
                        EntityValidationResult validationResult = DataAnnotation.ValidateEntity(item);
                        if (validationResult.HasError)
                        {
                            throw new AggregateException(validationResult.ValidationErrors.Select(x => new ValidationException(x.ErrorMessage)));
                        }
                    }
                    catch (Exception ex)
                    {
                        if (!skipCastErrors)
                        {
                            throw new ExcelTableConvertException(
                                      "An error occured while parsing the cell",
                                      ex,
                                      new ExcelTableConvertExceptionArgs
                            {
                                ColumnName   = table.Columns[map.Key].Name,
                                ExpectedType = property.PropertyType,
                                PropertyName = property.Name,
                                CellValue    = cell,
                                CellAddress  = new ExcelCellAddress(row, map.Key + table.Address.Start.Column)
                            }
                                      );
                        }
                    }
                }

                yield return(item);
            }
        }
Ejemplo n.º 21
0
        public void CustomerApplication_IsValid_ShouldReturnFalseAndMessageDocumentIdIsInvalid()
        {
            // Arrange
            var customerApp = Fixture.GetCustomerAppService();
            var customer    = Fixture.GenerateCustomerWithDocumentIdInvalid();

            // Act
            EntityValidationResult validation = customerApp.IsValid(customer);

            // Assert Fluent Assertions
            validation.Status.Should().BeFalse();
            validation.ValidationMessages.Should().HaveCount(c => c == 1);
            validation.ValidationMessages[0].Should().Be("CPF/CNPJ invalid");
        }
        public void FileExtensionsExample()
        {
            FileItem fileItem = new FileItem()
            {
                Name = "test.jpg"
            };

            EntityValidationResult validationResult = ValidationHelper.ValidateEntity(fileItem);

            Assert.IsFalse(validationResult.HasError);

            fileItem.Name    = "test.xsd";
            validationResult = ValidationHelper.ValidateEntity(fileItem);
            Assert.IsTrue(validationResult.HasError);
        }
Ejemplo n.º 23
0
        public void CustomerApplication_IsValid_ShouldReturnFalseAndMessageDocumentIdAlreadyExists()
        {
            // Arrange
            var customerApp = Fixture.GetCustomerAppService();
            var customer    = Fixture.GenerateCustomerWithDocumentIdDuplicated();

            Fixture.CustomerRepositoryMock.Setup(c => c.GetByDocumentId("34538886858")).Returns(Fixture.GenerateValidCustomerToQuery());

            // Act
            EntityValidationResult validation = customerApp.IsValid(customer);

            // Assert Fluent Assertions
            validation.Status.Should().BeFalse();
            validation.ValidationMessages.Should().HaveCount(c => c == 1);
            validation.ValidationMessages[0].Should().Be("CPF/CNPJ already exists");
        }
        public void PersonSocialSecurityExample()
        {
            Person person = new Person()
            {
                FirstName = "Jimmy Bob",
                LastName  = "Jones",
                Phone     = "(305) 444-9999",
                SSN       = "078-05-1120"
            };

            EntityValidationResult validationResult =
                ValidationHelper.ValidateEntity(person);

            Console.WriteLine(validationResult.ErrorMessageList());
            Assert.IsTrue(validationResult.HasError);
        }
Ejemplo n.º 25
0
        public void TestSuiteApplication_IsValid_ShouldReturnTrue()
        {
            // Arrange
            var TestPlanFixture = new TestPlansTestsFixture();

            var app       = Fixture.GetTestSuiteAppService();
            var testSuite = Fixture.GenerateValidTestSuite();

            Fixture.TestPlanAppServiceMock.Setup(c => c.GetById(2)).Returns(TestPlanFixture.GenerateValidTestPlanToQuery());

            // Act
            EntityValidationResult validation = app.IsValid(testSuite);

            // Assert Fluent Assertions
            validation.Status.Should().BeTrue();
            validation.ValidationMessages.Should().HaveCount(c => c == 0);
        }
        public static string ErrorMessageList(this EntityValidationResult sender)
        {
            string RemoveSpaces(string item)
            {
                return(Regex.Replace(item, @"\s+", " "));
            }

            var sb = new StringBuilder();

            sb.AppendLine("Validation issues");

            foreach (var validationResult in sender.Errors)
            {
                sb.AppendLine(RemoveSpaces(validationResult.ErrorMessage.SplitCamelCase()));
            }

            return(sb.ToString());
        }
Ejemplo n.º 27
0
        public void TestSuiteApplication_IsValid_ShouldReturnFalseAndMessageInvalidCustomer()
        {
            var TestPlanFixture = new TestPlansTestsFixture();

            // Arrange
            var app       = Fixture.GetTestSuiteAppService();
            var testSuite = Fixture.GenerateTestSuiteWithInvalidTestPlan();

            Fixture.TestPlanAppServiceMock.Setup(c => c.GetById(1)).Returns(TestPlanFixture.GenerateValidTestPlanToQuery());

            // Act
            EntityValidationResult validation = app.IsValid(testSuite);

            // Assert Fluent Assertions
            validation.Status.Should().BeFalse();
            validation.ValidationMessages.Should().HaveCount(c => c == 1);
            validation.ValidationMessages[0].Should().Be("Test Plan Not Found");
        }
Ejemplo n.º 28
0
        public EntityValidationResult IsValid(Project project)
        {
            try
            {
                if (project == null)
                {
                    throw new ArgumentException("Project invalid");
                }

                var validation = new EntityValidationResult();

                validation.Status             = true;
                validation.ValidationMessages = new List <string>();

                if (project.StartDate > project.FinishDate)
                {
                    validation.Status = false;
                    validation.ValidationMessages.Add("Finish Date must be greater than Start Date");
                }

                var customer = __customerService.GetById(project.CustomerId);
                if (customer == null)
                {
                    validation.Status = false;
                    validation.ValidationMessages.Add("Customer Not Found");
                }

                if (project.OwnerId.HasValue)
                {
                    var user = __userService.GetById(project.OwnerId.Value);
                    if (user == null)
                    {
                        validation.Status = false;
                        validation.ValidationMessages.Add("Owner Not Found");
                    }
                }

                return(validation);
            }
            catch (Exception)
            {
                throw;
            }
        }
Ejemplo n.º 29
0
        public EntityValidationResult IsValid(TestPlan testPlan)
        {
            try
            {
                if (testPlan == null)
                {
                    throw new ArgumentException("Test Plan invalid");
                }

                var validation = new EntityValidationResult();

                validation.Status             = true;
                validation.ValidationMessages = new List <string>();

                if (testPlan.StartDate > testPlan.FinishDate)
                {
                    validation.Status = false;
                    validation.ValidationMessages.Add("Finish Date must be greater than Start Date");
                }

                var project = __projectService.GetById(testPlan.ProjectId);
                if (project == null)
                {
                    validation.Status = false;
                    validation.ValidationMessages.Add("Project Not Found");
                }

                if (testPlan.OwnerId.HasValue)
                {
                    var user = __userService.GetById(testPlan.OwnerId.Value);
                    if (user == null)
                    {
                        validation.Status = false;
                        validation.ValidationMessages.Add("Owner Not Found");
                    }
                }

                return(validation);
            }
            catch (Exception)
            {
                throw;
            }
        }
        public void UsersInProjectsApplication_IsValid_ShouldReturnTrue()
        {
            // Arrange
            var UserFixture    = new UsersTestsFixture();
            var ProjectFixture = new ProjectsTestsFixture();

            var userApp = Fixture.GetUsersInProjectsAppService();
            var user    = Fixture.GenerateValidUsersInProjects();

            Fixture.UserAppServiceMock.Setup(c => c.GetById(2)).Returns(UserFixture.GenerateValidUserToQuery());
            Fixture.ProjectAppServiceMock.Setup(c => c.GetById(1)).Returns(ProjectFixture.GenerateValidProjectToQuery());

            // Act
            EntityValidationResult validation = userApp.IsValid(user);

            // Assert Fluent Assertions
            validation.Status.Should().BeTrue();
            validation.ValidationMessages.Should().HaveCount(c => c == 0);
        }