Beispiel #1
0
        public void Should_invalid_wrong_name(string name)
        {
            Person person = new Person(name);

            ValidationResult results = validator.Validate(person);

            Assert.False(results.IsValid);
        }
Beispiel #2
0
    void exampleUsage()
    {
        var john            = new Person(28);
        var jane            = new Person(-29);
        var personValidator = new PersonValidator();
        var johnsResult     = personValidator.Validate(john);
        var janesResult     = personValidator.Validate(jane);

        displayResult(johnsResult);
        displayResult(janesResult);
    }
Beispiel #3
0
        private void createButton_Click(object sender, EventArgs e)
        {
            errors.Clear();

            if (!decimal.TryParse(accountBalanceText.Text, out decimal accountBalance))
            {
                errors.Add("Account Balance: Invalid Amount");
                return;
            }

            PersonModel person = new PersonModel();

            person.FirstName      = firstNameText.Text;
            person.LastName       = lastNameText.Text;
            person.AccountBalance = accountBalance;
            person.DateOfBirth    = dateOfBirthPicker.Value;

            // Validate my data
            PersonValidator validator = new PersonValidator();

            ValidationResult results = validator.Validate(person);

            if (results.IsValid == false)
            {
                foreach (ValidationFailure failure in results.Errors)
                {
                    errors.Add(failure.ErrorMessage);
                }
            }

            // Insert into the database

            MessageBox.Show("Operation Complete");
        }
        private void button1_Click(object sender, EventArgs e)
        {
            // decimal accountBalance = 0;
            errors.Clear();

            if (!decimal.TryParse(accountBalanceinput.Text, out decimal accountBalance))
            {
                errors.Add("accountBalance error !");
                return;
            }

            PersonalModel personal = new PersonalModel();

            personal.FirstName      = this.fisrtNameInput.Text;
            personal.LastName       = this.lastNameInput.Text;
            personal.AccountBalance = accountBalance;
            personal.DateOfBirth    = this.dateOfBirthInput.Value;

            // validate data
            PersonValidator validator = new PersonValidator();

            ValidationResult results = validator.Validate(personal);

            if (results.IsValid == false)
            {
                foreach (ValidationFailure failure in results.Errors)
                {
                    errors.Add($"{ failure.PropertyName }: { failure.ErrorMessage }");
                }
            }

            // insert into DB

            MessageBox.Show("Operation Complete");
        }
Beispiel #5
0
        public async Task <IActionResult> EditPerson(int id, Person person)
        {
            if (id != person.Id)
            {
                return(BadRequest());
            }

            var validator = new PersonValidator();

            if (!validator.Validate(person).IsValid)
            {
                return(BadRequest());
            }

            try
            {
                await this._repository.EditAsync(person);
            }
            catch (DbUpdateConcurrencyException)
            {
                if (this._repository.GetByIdAsync(id) is null)
                {
                    return(NotFound());
                }
                else
                {
                    return(Problem());
                }
            }

            return(NoContent());
        }
        public void NotValidateEmptyPerson()
        {
            var sut    = new PersonValidator();
            var actual = sut.Validate(new PersonInformation());

            Assert.False(actual);
        }
        public void NotValidateNullPerson()
        {
            var sut    = new PersonValidator();
            var actual = sut.Validate(null);

            Assert.False(actual);
        }
Beispiel #8
0
        static void Main(string[] args)
        {
            Person person = new Person
            {
                ID          = 0,
                DateOfBirth = new DateTime(2099, 1, 1),
                FirstName   = "",
                LastName    = "Doo",
                Salary      = 987
            };

            // Validate via Fluent Validator
            PersonValidator  validator         = new PersonValidator();
            ValidationResult validationResults = validator.Validate(person);

            if (!validationResults.IsValid)
            {
                foreach (var item in validationResults.Errors)
                {
                    Console.WriteLine(item.ErrorMessage);
                }
            }

            // Insert into DB

            Console.ReadKey();
        }
        private void Button_Create_Click(object sender, EventArgs e)
        {
            errors.Clear();

            if (!decimal.TryParse(text_AccountBalance.Text, out decimal accountBalance))
            {
                errors.Add("Account Balance: Invalid Amount");
                return;
            }

            PersonModel person = new PersonModel();

            person.FirstName      = text_FirstName.Text;
            person.LastName       = text_LastName.Text;
            person.AccountBalance = accountBalance;
            person.DateOfBirth    = picker_DateOfBirth.Value;

            // Validate my data
            PersonValidator validator = new PersonValidator();

            ValidationResult results = validator.Validate(person);

            if (!results.IsValid)
            {
                foreach (ValidationFailure failure in results.Errors)
                {
                    errors.Add($"{ failure.PropertyName }: { failure.ErrorMessage }");
                }
            }

            // Insert into database

            MessageBox.Show("Operation complete");
        }
Beispiel #10
0
        public (bool, List <string>) AddPerson(Person person)
        {
            PersonValidator validator  = new PersonValidator();
            List <string>   errorsList = new List <string>();
            var             results    = validator.Validate(person);

            if (results.IsValid)
            {
                bool dbAdded = _dataAccess.AddPerson(person);
                if (dbAdded)
                {
                    return(true, null);
                }
            }
            else if (results.IsValid == false)
            {
                foreach (ValidationFailure failure in results.Errors)
                {
                    errorsList.Add($" {failure.PropertyName} : {failure.ErrorMessage}");
                }
                return(false, errorsList);
            }
            errorsList.Add("Logic Error");
            return(false, errorsList);
        }
Beispiel #11
0
        public void RubberStamp_Validator_InheritedValidator_Valid_Test()
        {
            var validator = new PersonValidator();
            var summary   = validator.Validate(new Person("Taylor", "Ted", "New York"));

            Assert.IsTrue(summary.IsValid);
        }
Beispiel #12
0
 private async Task GoBack()
 {
     // display Alert for confirmation
     if (IsChanged)
     {
         PersonValidator  _personValidator  = new PersonValidator();
         ValidationResult validationResults = _personValidator.Validate(_person);
         if (validationResults.IsValid)
         {
             AddPerson(_selectedprojectid);
             Shell.Current.Navigating -= Current_Navigating;
             //     await Shell.Current.GoToAsync("..", true);
             await _navigation.PopAsync(true);
         }
         else
         {
             await Application.Current.MainPage.DisplayAlert("Add Person", validationResults.Errors[0].ErrorMessage, "Ok");
         }
     }
     else
     {
         Shell.Current.Navigating -= Current_Navigating;
         //     await Shell.Current.GoToAsync("..", true);
         await _navigation.PopAsync(true);
     }
 }
Beispiel #13
0
        public IActionResult Put(int personId, PersonRegisterDto receivedPerson)
        {
            var personExists = _peopleRepository.GetById(personId);

            if (personExists == null)
            {
                return(NotFound("Person not found"));
            }

            var person = _mapper.Map <Person>(receivedPerson);

            var personValidator   = new PersonValidator();
            var validationResults = personValidator.Validate(person);

            if (!validationResults.IsValid)
            {
                return(BadRequest(validationResults));
            }

            if (_peopleRepository.Update(person))
            {
                var personToReturn = _mapper.Map <PersonDto>(person);
                return(Ok(personToReturn));
            }

            return(BadRequest("There was a problem updating this person"));
        }
        // GET: People
        public ActionResult Index()
        {
            var sam       = new Person();
            var validator = new PersonValidator();
            var results   = validator.Validate(sam, ruleSet: "Combo");

            return(View(db.People.ToList()));
        }
Beispiel #15
0
        public void RubberStamp_Validator_InheritedValidator_Invalid_Test()
        {
            var validator = new PersonValidator();
            var summary   = validator.Validate(new Person("Taylor", "Tim", "New York"));

            Assert.IsFalse(summary.IsValid);
            Assert.AreEqual("Tim Taylor is not alowed", summary.ValidationResults.First().Message);
        }
Beispiel #16
0
        public void Person_InvalidUser()
        {
            Person user = new Person();

            user.FirstName = string.Empty;
            user.LastName  = string.Empty;

            Assert.False(PersonValidator.Validate(user), "Invalid User");
        }
Beispiel #17
0
        public void Person_ValidUser()
        {
            Person user = new Person();

            user.FirstName = "Andre";
            user.LastName  = "Galioni";

            Assert.True(PersonValidator.Validate(user), "Valid User");
        }
Beispiel #18
0
        public void RubberStamp_Validator_InheritedValidator_Extended_Rule_WithWhen_Valid_Test()
        {
            var validator = new PersonValidator();

            validator.AddRule(p => p.City, con => con.IsEqual("Mexico City"), r => r.When(p => p.Firstname != "Ted"));
            var summary = validator.Validate(new Person("Taylor", "Ted", "New York"));

            Assert.IsTrue(summary.IsValid);
        }
Beispiel #19
0
        public void RubberStamp_Validator_InheritedValidator_Extended_Rule_CustomMessage_Invalid_Test()
        {
            var validator = new PersonValidator();

            validator.AddRule(p => p.City, con => con.IsEqual("Mexico City"), r => r.SetMessage("The City has to be Mexico City"));
            var summary = validator.Validate(new Person("Taylor", "Ted", "New York"));

            Assert.IsFalse(summary.IsValid);
            Assert.AreEqual("The City has to be Mexico City", summary.ValidationResults.First().Message);
        }
Beispiel #20
0
 static void Main(string[] args)
 {
     var person = new Person
     {
         Name     = "Ada",
         NickName = "A"
     };
     var validator = new PersonValidator();
     var result    = validator.Validate(person);
     //Should be a problem with the NickName
 }
        public void PersonValidator_Test()
        {
            var person = new Person();

            person.EmailAddress = "*****@*****.**";

            var target = new PersonValidator();
            var actual = target.Validate(person);

            Assert.IsTrue(actual.IsValid);
        }
Beispiel #22
0
        public void RuleForEach()
        {
            var person    = new Person();
            var validator = new PersonValidator();

            var result = validator.Validate(person);

            result.Should().NotBeNull();

            DisplayErrors(result);
        }
Beispiel #23
0
        static void Main(string[] args)
        {
            StandardMessages.WelcomeMessage();

            Person person = PersonDataCapture.Capture();

            PersonValidator.Validate(person);

            StandardMessages.WelcomeMessage(person);

            StandardMessages.EndApplication();
        }
        public async Task <IActionResult> Create(Person person)
        {
            var validator = new PersonValidator();

            var validationResult = validator.Validate(person);

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

            return(Ok());
        }
Beispiel #25
0
        static void Main(string[] args)
        {
            Person          p  = new Person();
            PersonValidator pv = new PersonValidator();
            var             validationResult = pv.Validate(p);

            Console.WriteLine($"Validation result: {validationResult.IsValid}");

            foreach (var error in validationResult.Errors)
            {
                Console.WriteLine($"  Error: {error.ErrorMessage}");
            }
        }
        public ActionResult CreatePerson([FromBody] PersonFormDTO model)
        {
            PersonValidator  validator        = new PersonValidator();
            ValidationResult validationResult = validator.Validate(model);

            if (validationResult.IsValid)
            {
                model.Thumb = UploadFile(model.Picture);
                personOperations.Create(model);
                return(Ok());
            }

            return(BadRequest());
        }
        public ActionResult UpdatePerson([FromBody] PersonFormDTO model)
        {
            PersonValidator  validator        = new PersonValidator();
            ValidationResult validationResult = validator.Validate(model);

            if (validationResult.IsValid)
            {
                string thumb = UploadFile(model.Picture);
                model.Thumb = string.IsNullOrEmpty(thumb) ? model.Thumb : thumb;
                personOperations.Edit(model);
                return(Ok());
            }
            return(BadRequest());
        }
        public void ReturnsFalseGivenPersonWithNoForename()
        {
            var person = new Person()
            {
                Surname = "TestSurname",
            };

            var validator = new PersonValidator();

            var result = validator.Validate(person);

            Assert.False(result.IsValid);
            Assert.True(result.Errors.Any());
        }
        public void ReturnsTrueGivenValidPerson()
        {
            var person = new Person()
            {
                Surname  = "Testname",
                Forename = "Testname2"
            };

            var validator = new PersonValidator();

            var result = validator.Validate(person);

            Assert.True(result.IsValid);
        }
        public void ValidateNoEmailNoPhonePerson()
        {
            var sut    = new PersonValidator();
            var person = new PersonInformation
            {
                Name        = "John",
                Surname     = "Doe",
                Email       = string.Empty,
                IdNumber    = "x-1111111",
                PhoneNumber = null
            };
            var actual = sut.Validate(person);

            Assert.True(actual);
        }
Beispiel #31
0
        public HttpResponseMessage Post(Person person)
        {
            var personRepository = PersonRepositoryFactory.PersonRepository();

            personBL = new PersonBL(personRepository);

            HttpResponseMessage response;    

            // Initiate Validation.
            var validator = new PersonValidator();
            ValidationResult results = validator.Validate(person, ruleSet: "Names");            
            

            // Add error messages if any.
            ModelStateDictionary modelDictionary = new ModelStateDictionary();
            foreach(ValidationFailure result in results.Errors)
            {
                 modelDictionary.AddModelError(result.PropertyName, result.ErrorMessage);
            }     


            if (results.IsValid)
            {

                // Calls Business Logic to create.
                try
                {
                    personBL.CreatePerson(person);
                }
                catch (Exception ex)
                {
                    modelDictionary.AddModelError("Error", "Service Error");
                    return Request.CreateErrorResponse(HttpStatusCode.BadRequest, modelDictionary);
                }


                // Creates response
                response = Request.CreateResponse(HttpStatusCode.Created, person);
            }
            else
            {
                // Creates response
                response = Request.CreateErrorResponse(HttpStatusCode.BadRequest, modelDictionary);              
            }

            return response;
        }
Beispiel #32
0
        private void save(object obj)
        {
            var validator = new PersonValidator();
            var results = validator.Validate(this.Person);

            var jobErrors = Person.Jobs.Where(t=>!string.IsNullOrEmpty(t.Error)).Select(t => t.Error);
            var toDoErrors = Person.ToDoes.Where(t => !string.IsNullOrEmpty(t.Error)).Select(t => t.Error);

            if (results.IsValid && jobErrors.Count() == 0 && toDoErrors.Count() == 0)
            {
                try
                {
                    db.SaveChanges();
                    dialogService.ShowMessageAsync("Καταχώρηση", "Οι αλλαγές καταχωρήθηκαν επιτυχώς.");
                }
                catch (Exception ex)
                {
                    dialogService.ShowMessageAsync("Σφάλμα", ex.Message);
                }
            }
            else
            {
                var message = string.Join(Environment.NewLine, results.Errors.Select(t => t.ErrorMessage));
                message += string.Join(Environment.NewLine, jobErrors);
                message += string.Join(Environment.NewLine, toDoErrors);
                dialogService.ShowMessageAsync("Σφάλμα", message);
            }
        }