Exemple #1
0
        public async Task <Guid> Handle(CreateCustomerCommand request, CancellationToken cancellationToken)
        {
            var newCustomer = new Customer
            {
                FirstName      = request.FirstName,
                LastName       = request.LastName,
                Address        = request.Address,
                Email          = request.Email,
                CreateDateUtc  = DateTime.UtcNow,
                DeletedDateUtc = null,
            };

            var doesCustomerExist = _context.Customers.FirstOrDefault(x =>
                                                                      x.FirstName.Equals(newCustomer.FirstName) &&
                                                                      x.LastName.Equals(newCustomer.LastName)) != null;

            if (doesCustomerExist)
            {
                return(await Task.FromResult(Guid.Empty));
            }

            await _context.Customers.AddAsync(newCustomer, cancellationToken);

            var customerValidator        = new CustomerValidator();
            var customerValidationResult = await customerValidator.ValidateAsync(newCustomer, cancellationToken);

            if (!customerValidationResult.IsValid)
            {
                return(await Task.FromResult(Guid.Empty));
            }

            await _context.SaveChangesAsync(cancellationToken);

            return(await Task.FromResult(newCustomer.Id));
        }
        public void TestCustomerValidation()
        {
            IValidator <Customer> validator = new CustomerValidator();

            Customer validCustomer = new Customer()
            {
                Name    = "Maria Popescu",
                Contact = "+40 103820944",
                Address = "Santana Street"
            };

            Customer invalidCustomer = new Customer()
            {
                Name    = "",
                Contact = "",
                Address = ""
            };

            //validating a valid customer
            validator.Validate(validCustomer);

            //trying to validate a customer with invalid name, address and contact
            try
            {
                validator.Validate(invalidCustomer);
                Assert.Fail();
            }
            catch (ValidationException ve)
            {
                Assert.AreEqual(ve.Message, "Invalid name!\nInvalid contact!\nInvalid address!\n");
            }
        }
Exemple #3
0
        public void RegisterValidatorAndRetrieve()
        {
            IIocContainer iocContainer = Substitute.For <IIocContainer>();
            IocContainerValidatorFactory iocContainerValidatorFactory = new IocContainerValidatorFactory(iocContainer);
            CustomerValidator            customerValidator            = new CustomerValidator();

            Dictionary <string, IEntityValidator <Customer> > registry = new Dictionary <string, IEntityValidator <Customer> >();

            iocContainer.WhenForAnyArgs(x => x.RegisterSingleInstanceNamed <IEntityValidator <Customer> >(null, null)).Do(x =>
            {
                Func <IIocContainerResolver, IEntityValidator <Customer> > func = x.Arg <Func <IIocContainerResolver, IEntityValidator <Customer> > >();
                string name = x.Arg <string>();

                IEntityValidator <Customer> validator = func(iocContainer);

                registry.Add(name, validator);
            });

            iocContainer.GetInstanceOptionalByName(null, null).ReturnsForAnyArgs(x =>
            {
                string name = x.Arg <string>();

                return(registry[name]);
            });

            iocContainerValidatorFactory.RegisterValidator(customerValidator);
            IEntityValidator <Customer> entityValidator = iocContainerValidatorFactory.GetValidatorFor <Customer>();

            Assert.IsNotNull(entityValidator);
            Assert.AreSame(customerValidator, entityValidator);
        }
        public async Task <IActionResult> CheckContract([FromBody] PostWrapper post)
        {
            //Trim & clean special chars here
            var contractId = post.Post?.Trim() ?? string.Empty;

            if (string.IsNullOrEmpty(contractId))
            {
                return(BadRequest());
            }
            using (_context)
            {
                _context.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;
                //Check if any request with this contract id exists
                var rq = await _context.Request.SingleOrDefaultAsync(r => r.LoanNo == contractId);

                if (rq != null)
                {
                    //Not valid
                    return(Ok(new ResultWrapper()
                    {
                        Message = $"Khách hàng này đã request với ID: {rq.RequestId}", Valid = false
                    }));
                }
                //Get info from indus
                var customerInfo = await _indus.GetCustomerInfo(contractId.Trim());

                //Check if customer meet bussiness' requirement
                if (CustomerValidator.CheckAndClean(customerInfo, contractId, out var mess, out var cleaned))
                {
                    //Valid
                    return(Ok(new ResultWrapper()
                    {
                        Message = mess, Valid = true
                    }));
                }
Exemple #5
0
        static void Main(string[] args)
        {
            PetValidator petValidator = new PetValidator();
            string petsFilename = "..\\..\\..\\data\\pets.txt";
            PetsRepository petsRepository = new PetsRepository(petValidator, petsFilename);

            CustomerValidator customerValidator = new CustomerValidator();
            string customersFilename = "..\\..\\..\\data\\customers.txt";
            CustomersRepository customersRepository = new CustomersRepository(customerValidator, customersFilename);

            ServiceValidator serviceValidator = new ServiceValidator();
            string servicesFilename = "..\\..\\..\\data\\services.txt";
            ServicesRepository servicesRepository = new ServicesRepository(serviceValidator, servicesFilename);

            VetValidator vetValidator = new VetValidator();
            string vetsFilename = "..\\..\\..\\data\\vets.txt";
            VetsRepository vetsRepository = new VetsRepository(vetValidator, vetsFilename);

            AppointmentValidator appointmentValidator = new AppointmentValidator();
            string appointmentsFilename = "..\\..\\..\\data\\appointments.txt";
            AppointmentsRepository appointmentsRepository = new AppointmentsRepository(appointmentValidator, appointmentsFilename);

            Controller controller = new Controller(petsRepository, customersRepository, servicesRepository, vetsRepository,appointmentsRepository);

            runApp(controller);

        }
        private static AbstractOrderValidator BuildCustomerValidator()
        {
            AbstractOrderValidator validator = new CustomerValidator();

            validator.AddValidator(BuildContributorValidator());
            return(validator);
        }
        public string Create(Customer customer)
        {
            Result r = new Result { ErrorCode = 0, ErrorMessage = "Create customer successful." };

            CustomerValidator validator = new CustomerValidator();
            ValidationResult results = validator.Validate(customer);

            if (!results.IsValid)
            {
                r.ErrorCode = -1;
                r.ErrorMessage = results.Errors.First().ErrorMessage;

                return JsonConvert.SerializeObject(r, _settings);
            }

            customer.Id = Guid.NewGuid();
            CustomerDS.Customers.Add(customer);
            CustomerDS.Serialize(DateTime.Now);

            r.Data = customer; // Return current customer

            // Broadcast to all clients
            CustomerHub.Instance.Clients.All.add(JsonConvert.SerializeObject(customer, _settings));

            return JsonConvert.SerializeObject(r, _settings);
        }
Exemple #8
0
        public static async Task Run(
            [QueueTrigger("requestreceived", Connection = "registration2storage_STORAGE")] Customer customer,
            [Queue("requestaccepted", Connection = "registration2storage_STORAGE")] CloudQueue requestAcceptedQueue,
            [Table("processingStatus", Connection = "registration2storage_STORAGE")] CloudTable proccessingStatusTable,
            TraceWriter log)
        {
            log.Info($"RequestValidation function processed: {customer.RowKey} ({customer.Name} - {customer.Surname})");

            var validator            = new CustomerValidator();
            ValidationResult results = validator.Validate(customer);

            var processingStatus = new ProcessingStatus(customer.RowKey)
            {
                ETag = "*"
            };

            if (results.IsValid)
            {
                await requestAcceptedQueue.AddMessageAsync(new CloudQueueMessage(JsonConvert.SerializeObject(customer)));

                processingStatus.ProcessingState = ProcessingState.Accepted.ToString();
            }
            else
            {
                processingStatus.ProcessingState = ProcessingState.Error.ToString();
                processingStatus.Message         = "Validation failed: " +
                                                   results.Errors.Select(error => error.ErrorMessage)
                                                   .Aggregate((a, b) => a + "; " + b);
            }

            TableOperation updateOperation = TableOperation.Replace(processingStatus);
            await proccessingStatusTable.ExecuteAsync(updateOperation);
        }
        public void ForenameRule_ShouldMatchEFModelConfiguration()
        {
            var validator = new CustomerValidator();

            // Get the rules for the Forename field in the CustomerValidator
            var foreNameLengthValidator = validator
                                          .GetValidatorsForMember(t => t.Forename).OfType <MaximumLengthValidator>().First();

            var foreNameNotEmptyValidator = validator
                                            .GetValidatorsForMember(t => t.Forename).OfType <NotEmptyValidator>().FirstOrDefault();

            // Get the EF EntityTypeBuilder<T> for our Customer entity
            var entityTypeBuilder = TestExtensions
                                    .GetEntityTypeBuilder <Customer, CustomerEntityTypeConfiguration>();

            var foreNameDbProperty = entityTypeBuilder.Metadata.FindDeclaredProperty(nameof(Customer.Forename));

            // Rule Should have the same length as EF Configuration
            Assert.Equal(foreNameDbProperty.GetMaxLength(), foreNameLengthValidator.Max);

            // If the Column is required (NOTNULL) in the EF configuration, the rule should exist
            if (!foreNameDbProperty.IsColumnNullable())
            {
                Assert.NotNull(foreNameNotEmptyValidator);
            }
            else
            {
                Assert.Null(foreNameNotEmptyValidator);
            }
        }
Exemple #10
0
        public IActionResult Post([FromBody] Customer customer)
        {
            if (!ModelState.IsValid)
            {
                return(new JsonResult("Data model not valid"));
            }

            CustomerValidator validator = new CustomerValidator();
            ValidationResult  results   = validator.Validate(customer);

            bool validationSucceeded           = results.IsValid;
            IList <ValidationFailure> failures = results.Errors;

            Debug.WriteLine(ModelState.Values);

            // protect the payload
            string protectedPayload = protector.Protect("ciccio");

            Debug.WriteLine($"Protect returned: {protectedPayload}");

            // unprotect the payload
            string unprotectedPayload = protector.Unprotect(protectedPayload);

            Debug.WriteLine($"Unprotect returned: {unprotectedPayload}");

            return(new JsonResult(unprotectedPayload));
        }
 private void ValidateCustomer()
 {
     if (mCart.Customer != null)
     {
         Customer = mCart.Customer.Validate();
     }
 }
        /// <summary>
        /// Generate test data using Faker.dll.
        /// TO DO - Inject log object
        /// </summary>
        /// <param name="noOfCustomersToBeGenerated">No of customers to be generated</param>
        /// <returns>List of customers that has been generated successfully.</returns>
        public List <ICustomer> GenerateData(int noOfCustomersToBeGenerated)
        {
            List <ICustomer> customerList = new List <ICustomer>();

            try
            {
                using (ICustomerValidator customerValidator = new CustomerValidator())
                {
                    for (int count = 0; count < noOfCustomersToBeGenerated; count++)
                    {
                        Customer customer = new Customer
                        {
                            FirstName    = Faker.Name.First(),
                            LastName     = Faker.Name.Last(),
                            MiddleName   = Faker.Name.Middle(),
                            CompanyName  = Faker.Company.Name(),
                            RoadName     = Faker.Address.StreetName(),
                            City         = Faker.Address.City(),
                            PostCode     = Faker.Address.ZipCode(),
                            District     = Faker.Address.UsState(),
                            MobileNumber = Faker.Phone.Number(),
                            Email        = Faker.Internet.Email()
                        };

                        customerList.Add(customer);
                    }
                }
            }
            catch (Exception ex)
            {
                //log exception - TO DO
            }

            return(customerList);
        }
Exemple #13
0
        // Update Customer database manipulations
        public void Update(Customer customer)
        {
            Car car = new Car();
            CustomerValidator validator    = new CustomerValidator();
            ValidationResult  result       = validator.Validate(customer);
            PrintColorMessage colorMessage = new PrintColorMessage();

            // Input Customer Name Validation
            if (!result.IsValid)
            {
                colorMessage.Print(ConsoleColor.Red, "\n Customer is not Updated! See reason below:");

                //data validation
                foreach (var failure in result.Errors)
                {
                    Console.WriteLine("\n '" + failure.PropertyName + "' written incorrectly . \n Details: " + failure.ErrorMessage);
                }
            }
            else
            {
                //EF
                using (var context = new ApplicationDbContext())
                {
                    var customerToUpdate =
                        context.Customers.First(x => x.CustomerID == customer.CustomerID);
                    customerToUpdate.Name      = customer.Name;
                    customerToUpdate.BirthDate = customer.BirthDate;

                    context.SaveChanges();
                }
            }
        }
        /// <summary>
        /// Initailises valid customer object to be used in all tests. Also defines <see cref="ValidatorConfig"/>
        /// </summary>
        public CustomerValidatorTests()
        {
            this._customer = new CustomerDto()
            {
                FirstName             = "John",
                LastName              = "Test",
                PolicyReferenceNumber = "AA-000001",
                Email       = "*****@*****.**",
                DateOfBirth = DateTime.Now.AddYears(-20)
            };

            // Set up mock config to inject in Cstomer Validator
            ValidatorConfig config = new ValidatorConfig()
            {
                MinimumCustomerAge     = 18,
                MinimumNameLength      = 3,
                MaximumNameLength      = 50,
                PolicyReferencePattern = @"^[A-Z]{2}-\d{6}$",
                EmailPattern           = @"^[\w]{4,}@\w{2,}(.com|.co.uk)$"
            };

            IOptions <ValidatorConfig> options = Options.Create(config);

            this._customerValidator = new CustomerValidator(options);
        }
Exemple #15
0
        public async Task <BusinessPartner> AddBusinessPartnerAsync(BusinessPartner businessPartner,
                                                                    CancellationToken cancellation)
        {
            var validator = new CustomerValidator(ValidateCardGroupExist, ValidateSalesmanCodeExist);

            validator.RuleFor(x => x.Name).NotEmpty();
            validator.RuleFor(x => x.GroupSn).Must(ValidateCardGroupExist)
            .WithMessage(x => $"Card Group {x.GroupSn} is invalid");
            validator.RuleFor(x => x.SalesmanCode).Must(ValidateSalesmanCodeExist)
            .WithMessage(x => $"Salesman with code {x.SalesmanCode} is  invalid");
            validator.RuleFor(x => x.Key).Null();
            validator.RuleFor(x => x.CreationDateTime).Null();
            var isBusinessPannerValid = await validator.ValidateAsync(businessPartner, cancellation);

            if (!isBusinessPannerValid.IsValid)
            {
                throw new InvalidStateException(isBusinessPannerValid.Errors
                                                .Select(x => x.ErrorMessage).Aggregate((s1, s2) => $"{s1},{s2}"));
            }


            using var transaction            = _dalService.CreateUnitOfWork();
            businessPartner.CreationDateTime = DateTime.Now;
            var result = await transaction.BusinessPartners.AddAsync(businessPartner);

            await transaction.CompleteAsync(cancellation);

            return(result);
        }
Exemple #16
0
        public async Task <Customer> Handle(UpdateCustomerInfoCommand request, CancellationToken cancellationToken)
        {
            var customer = await _context.Customers.FindAsync(request.Id);

            if (customer is null)
            {
                return(await Task.FromResult <Customer>(null));
            }

            customer.FirstName = request.FirstName ?? customer.FirstName;
            customer.LastName  = request.LastName ?? customer.LastName;
            customer.Address   = request.Address ?? customer.Address;
            customer.Email     = request.Email ?? customer.Email;
            customer.Phone     = request.Phone ?? customer.Phone;

            var customerValidator = new CustomerValidator();
            var validationResult  = await customerValidator.ValidateAsync(customer, cancellationToken);

            if (!validationResult.IsValid)
            {
                return(await Task.FromResult <Customer>(null));
            }

            await _context.SaveChangesAsync(cancellationToken);

            return(await Task.FromResult <Customer>(customer));
        }
Exemple #17
0
        public async Task <ActionResult <CustomerAPIModel> > UpdateCustomer(string id, CustomerAPIModel customer)
        {
            var validator        = new CustomerValidator();
            var validationResult = await validator.ValidateAsync(customer);

            if (!validationResult.IsValid)
            {
                return(BadRequest(validationResult.Errors));
            }

            var customerToUpdate = await _customersService.GetCustomerById(id);

            if (customerToUpdate == null)
            {
                return(NotFound());
            }

            var customerModel = _mapper.Map <CustomerAPIModel, Customers>(customer);

            await _customersService.UpdateCustomer(customerToUpdate, customerModel);

            customerModel = await _customersService.GetCustomerById(id);

            customer = _mapper.Map <Customers, CustomerAPIModel>(customerModel);

            return(Ok(customer));
        }
        public async Task <IActionResult> UpdateV2([FromBody] Customer customer)
        {
            try
            {
                //valida a entidade
                var validator = new CustomerValidator();
                validator.Validate(customer);

                if (validator.Errors.Count > 0)
                {
                    return(BadRequest(new ResultViewModel
                    {
                        Message = "Dados inválidos! Corriga os erros e tente novamente.",
                        Success = false,
                        Data = validator.Errors
                    }));
                }

                var customerUpdated = await _customerRepository.Update(customer);

                return(Ok(new ResultViewModel
                {
                    Message = "Cliente atualizado com sucesso!",
                    Success = true,
                    Data = customerUpdated
                }));
            }
            catch (Exception)
            {
                return(StatusCode(500, errorResultViewModel));
            }
        }
Exemple #19
0
        public async Task <BusinessPartner> UpdateBusinessPartnerAsync(string cid, BusinessPartner businessPartner,
                                                                       CancellationToken cancellation)
        {
            var validator = new CustomerValidator(ValidateCardGroupExist, ValidateSalesmanCodeExist);

            validator.RuleFor(x => x.Key).Must(x => x == cid);
            validator.RuleFor(x => x.Name).Must(x => x == null || !string.IsNullOrWhiteSpace(x));
            validator.RuleFor(x => x.GroupSn).Must(x => !x.HasValue || ValidateCardGroupExist(x))
            .WithMessage(x => $"Card Group {x.GroupSn} is invalid");
            validator.RuleFor(x => x.SalesmanCode).Must(x => !x.HasValue || ValidateSalesmanCodeExist(x))
            .WithMessage(x => $"Salesman with code {x.SalesmanCode} is  invalid");
            var isBusinessPannerValid = await validator.ValidateAsync(businessPartner, cancellation);

            if (!isBusinessPannerValid.IsValid)
            {
                throw new InvalidStateException(isBusinessPannerValid.Errors
                                                .Select(x => x.ErrorMessage).Aggregate((s1, s2) => $"{s1},{s2}"));
            }

            using var transaction = _dalService.CreateUnitOfWork();
            //TODO check which field are updateable
            var result = await transaction.BusinessPartners.UpdateAsync(businessPartner);

            await transaction.CompleteAsync(cancellation);

            return(result);
        }
 public ActionResponse Save(CustomerDto obj, Guid?userId = null)
 {
     try
     {
         if (obj.Password == null)
         {
             var c = _customerRepository.GetById(obj.Id);
             obj.Password = c.Data.Password;
         }
         var valResult = new CustomerValidator().Validate(obj);
         if (valResult.IsValid)
         {
             var customer = _customerRepository.GetById(obj.Id);
             obj.Email = customer.Data.Email;
             var response = _customerRepository.Save(obj);
             return(response);
         }
         else
         {
             var valErrors = valResult.Errors.Select(e => e.ErrorMessage).ToArray();
             return(ActionResponse.Failure(valErrors));
         }
     }
     catch (Exception ex)
     {
         return(ActionResponse.Failure(ex.Message));
     }
 }
        public string Create(Customer customer)
        {
            Result r = new Result {
                ErrorCode = 0, ErrorMessage = "Create customer successful."
            };

            CustomerValidator validator = new CustomerValidator();
            ValidationResult  results   = validator.Validate(customer);

            if (!results.IsValid)
            {
                r.ErrorCode    = -1;
                r.ErrorMessage = results.Errors.First().ErrorMessage;

                return(JsonConvert.SerializeObject(r, _settings));
            }

            customer.Id = Guid.NewGuid();
            CrudDS <Customer> .Items.Add(customer);

            CrudDS <Customer> .Serialize(DateTime.Now);

            r.Data = customer; // Return current customer

            // Broadcast to all clients
            CustomerHub.Instance.Clients.All.add(JsonConvert.SerializeObject(customer, _settings));

            return(JsonConvert.SerializeObject(r, _settings));
        }
        public AddCustomerResponse AddCustomer(Customer customer)
        {
            var validator = new CustomerValidator();
            var results   = validator.Validate(customer);


            if (results.IsValid == false)
            {
                var messages = new List <string>();
                foreach (var item in results.Errors)
                {
                    messages.Add(item.ErrorCode);
                }

                return(new AddCustomerResponse()
                {
                    ErrorMessage = messages,
                    Status = false
                });
            }


            using (var unitOfWork =
                       new UnitOfWork(new DatabaseContext()))
            {
                unitOfWork.Customers.Add(customer);
                unitOfWork.Complete();
            }
            return(new AddCustomerResponse {
                Status = true
            });
        }
Exemple #23
0
 public override void Context()
 {
     base.Context();
     _customer            = new CustomerEntity();
     _configuredException = new RulesViolationException("test");
     CustomerValidator.Validate(_customer).Throws(_configuredException);
 }
 public CustomerCreateViewModel()
 {
     //This is a concrete implementation which some may have an issue with here.
     //If you are a DI purist, then you will need to declare a custom model validator to be injected
     //    public class CustomModelValidator : AssociatedValidatorProvider
     //See my demos on completedevelopment.blogspot.com
     _validator = new CustomerValidator();
 }
 public PatchCustomerService(
     IDefaultDbContext context,
     CustomerValidator entityValidator,
     PatchCustomerSpecificationsValidator domainValidator
     ) : base(entityValidator, domainValidator)
 {
     Context = context;
 }
        public void IsValid_WithContext_ShouldNotBeNull()
        {
            var sut = new CustomerValidator();

            var result = sut.IsValid(new Customer(), new {});

            result.ShouldNotBeNull();
        }
        Given_ValidatorWhichIsValidatingProperty_When_ValidatingWithNeededPassingValidator_Then_ValidationPass()
        {
            // Arrange
            var customerValidator = new CustomerValidator();

            // Act & assert
            AssertExtension.NotThrows(() => customerValidator.ShouldHaveRules(x => x.Name, new FakeValidatorVerifier()));
        }
        public void WhenCustomerIsNull_ThenArgumentNullExceptionIsThrown()
        {
            var validator = new CustomerValidator();

            Action action = () => validator.Validate(null);

            action.Should().Throw <ArgumentNullException>();
        }
Exemple #29
0
        public void MockExample()
        {
            var customerValidator = new CustomerValidator();
            var customer          = Mock.Of <ICustomer>(c => c.GetAge() == 21); // Mock

            customerValidator.Validate(customer);

            Mock.Get(customer).Verify(x => x.GetAge()); // Verification of Mock
        }
Exemple #30
0
        public void SpyExample()
        {
            var customerValidator = new CustomerValidator();
            var customer          = Mock.Of <ICustomer>(c => c.GetAge() == 21); // Spy

            customerValidator.Validate(customer);

            Mock.Get(customer).Verify(x => x.GetAge(), Times.Once); // Verification of Spy
        }
Exemple #31
0
        public void WhenCustomerHasAgeLessThan18_ThenValidationFails()
        {
            var validator = new CustomerValidator();
            var customer  = new CustomerMock(16);

            bool validate = validator.Validate(customer);

            validate.Should().BeFalse();
        }
Exemple #32
0
        public void StubExample()
        {
            var customerValidator = new CustomerValidator();
            var customer          = Mock.Of <ICustomer>(c => c.GetAge() == 21); // Stub

            bool validate = customerValidator.Validate(customer);

            validate.Should().BeTrue();
        }
        public void Store(Customer customer)
        {
            var customerValidator = new CustomerValidator();
            var validationResult = customerValidator.Validate(customer);

            if (!validationResult.IsValid)
                throw new Exception(string.Join(" ",validationResult.Errors.Select(p => p.ErrorMessage)));

            //Store into database
        }
        public CustomerService(
			IUserContext applicationContext,
			IRepositorySessionFactory repositorySessionFactory,
			ICustomerRepository customerRepository,
			IQueueDispatcher<IMessage> dispatcher)
            : base(applicationContext, repositorySessionFactory, dispatcher)
        {
            _customerRepository = customerRepository;
            _customerValidator = new CustomerValidator(customerRepository);
        }
        void CustomerValidate_Pass_Test()
        {
            //Assign
            Customer cus = TestStubs.GetCustomer();

            CustomerValidator cv = new CustomerValidator();

            //Act
            ValidationResult results = cv.Validate(cus);

            //Assert
            Assert.True(results.IsValid);
        }
        public void InValidCustomerTest() {
            var customer = new Customer()
                           {
                               Name = "",
                               Company = "",
                               HasDiscount = true,
                           };

            var customerValidator = new CustomerValidator();

            var result = customerValidator.Validate(customer);
            result.IsValid.Should().Be.False();
            result.Errors.Count.Should().Be.GreaterThan(0);
        }
        void CustomerValidate_Fail_Pass_Test()
        {
            //Assign
            Customer cus = TestStubs.GetCustomer();
            cus.LastName = String.Empty;

            CustomerValidator cv = new CustomerValidator();

            //Act
            ValidationResult results = cv.Validate(cus);

            //Assert
            Assert.False(results.IsValid);
        }
        public FormCustomer(string customerId)
        {
            InitializeComponent();
            validator = new CustomerValidator(customerRepo);
            persister = new GenericPersister<Customer>(customerRepo, validator, caster);

            if (customerId != null)
            {
                var customer = customerRepo.FindById(customerId);
                txtName.Text = customer.Name;
                mTxtCpf.Text = customer.Cpf;
                caster.SetModel(customer);
            }
        }
        public void ValidCustomerTest() {
            var customer = new Customer()
                           {
                               Name = "배성혁",
                               Company = "리얼웹",
                               Discount = 12.5m,
                               ZipCode = "135-010"
                           };

            var customerValidator = new CustomerValidator();

            var result = customerValidator.Validate(customer);
            result.IsValid.Should().Be.True();
            result.Errors.Count.Should().Be(0);
        }
        static void Main(string[] args)
        {
            var customer = new Customer {
            };

            var validator = new CustomerValidator();

            var result = validator.Validate(customer);

            foreach(var error in result.Errors) {
                Console.WriteLine("Property: {0} Error Message: {1}", error.PropertyName, error.ErrorMessage);
            }

            Console.WriteLine("Press any key to exit");
            Console.ReadKey();
        }
        public string Update(Customer customer)
        {
            Result r = new Result { ErrorCode = 0, ErrorMessage = "Update customer successful." };

            Customer item = CrudDS<Customer>.Items.Find(c => c.Id == customer.Id);
            if (customer == null)
            {
                r.ErrorCode = -1;
                r.ErrorMessage = "Could not find customer with id=" + customer.Id + ".";
            }
            else
            {
                CustomerValidator validator = new CustomerValidator();
                ValidationResult results = validator.Validate(customer);

                if (!results.IsValid)
                {
                    r.ErrorCode = -1;
                    r.ErrorMessage = results.Errors.First().ErrorMessage;

                    return JsonConvert.SerializeObject(r, _settings);
                }

                item.FirstName = customer.FirstName;
                item.LastName = customer.LastName;
                item.Email = customer.Email;
                item.Phone = customer.Phone;
                CrudDS<Customer>.Serialize(DateTime.Now);
            }

            r.Data = customer;

            // Broadcast to all clients
            CustomerHub.Instance.Clients.All.update(JsonConvert.SerializeObject(customer, _settings));

            return JsonConvert.SerializeObject(r, _settings);
        }
        /// <summary>
        /// Parses the tax line for CSV
        /// </summary>
        /// <param name="line"></param>
        public void ProcessLine(string line)
        {
            if (!string.IsNullOrEmpty(line))
            {
                string[] processLine = line.Split(',');

                if (processLine.Length > 0)
                {
                    ProcessingPayLineVm pvm = new ProcessingPayLineVm
                    {
                        FirstName = processLine[Convert.ToInt32(CsvProcessingIndex.FirstName)],
                        LastName = processLine[Convert.ToInt32(CsvProcessingIndex.LastName)],
                        AnnualGrossSalary = processLine[Convert.ToInt32(CsvProcessingIndex.GrossIncome)],
                        SuperAnnuationRate = processLine[Convert.ToInt32(CsvProcessingIndex.SuperAnnuationRate)],
                        StartDateTime = processLine[Convert.ToInt32(CsvProcessingIndex.DatePeriod)],
                    };

                    Customer customer = Mapper.Map<Customer>(pvm);

                    // This is ensure the model mapping from the automapper is valid domain model
                    CustomerValidator cv = new CustomerValidator();
                    var results = cv.Validate(customer);

                    if (results.IsValid)
                    {
                        var outputLine = _salarySlipService.GenerateSalarySlip(customer, TimeFrequency.Monthly);

                        if (outputLine != null)
                        {
                            _outputWriter.WriteLine(" "+outputLine.ToConsoleLineString());
                        }
                        else
                        {
                            throw new Exception("Customer salary slip details not valid");
                        }
                    }
                    else
                    {
                        throw new Exception("Customer details not valid");
                    }

                }
            }
        }
        public void ShouldHaveValidationErrorFor_WithRuleSet_ShouldThrowException()
        {
            var sut = new CustomerValidator();

            Should.Throw<ValidationException>(() => { sut.ShouldHaveValidationErrorFor(new Customer() { Name = "Name", Age = 22 }, "GreaterThan21"); });
        }
        public void IsValid_WithRuleSet_ShouldNotBeNull()
        {
            var sut = new CustomerValidator();

            var result = sut.IsValid(new Customer(), "ruleset");

            result.ShouldNotBeNull();
        }
        public void ShouldNotHaveValidationErrorFor_With_ShouldThrowException()
        {
            var sut = new CustomerValidator();

            Should.Throw<ValidationException>(() => { sut.ShouldNotHaveValidationErrorFor(new Customer() ); });
        }
        public void ShouldNotHaveValidationErrorFor_With_ShouldNotThrowException()
        {
            var sut = new CustomerValidator();

            sut.ShouldNotHaveValidationErrorFor(new Customer() { Name = "Name", Age = 20 });
        }
        public void ShouldNotHaveValidationErrorFor_WithRuleSetAnContext_ShouldThrowException()
        {
            var sut = new CustomerValidator();

            Should.Throw<ValidationException>(() => { sut.ShouldNotHaveValidationErrorFor(new Customer(), "GreaterThan21", new { }); });
        }
        public void ShouldNotHaveValidationErrorFor_WithRuleSetAndContext_ShouldNotThrowException()
        {
            var sut = new CustomerValidator();

            sut.ShouldNotHaveValidationErrorFor(new Customer() { Name = "Name", Age = 22 }, "GreaterThan21", new { }); 
        }
        public void ShouldHaveValidationErrorFor_WithContext_ShouldNotThrowException()
        {
            var sut = new CustomerValidator();

            sut.ShouldHaveValidationErrorFor(new Customer(),new {});
        }
        public void ShouldHaveValidationErrorFor_WithContext_ShouldThrowException()
        {
            var sut = new CustomerValidator();

            Should.Throw<ValidationException>(() => { sut.ShouldHaveValidationErrorFor(new Customer() { Name = "Name", Age = 20 }, new {}); });
        }
        public void ShouldHaveValidationErrorFor_WithRuleSet_ShouldNotThrowException()
        {
            var sut = new CustomerValidator();

            sut.ShouldHaveValidationErrorFor(new Customer(), "GreaterThan21");
        }