Exemplo n.º 1
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);
     }
 }
Exemplo n.º 2
0
 public PersonValidationTests()
 {
     personValidator = new PersonValidator();
     validator       = new Validator();
     // personValidator.Define(engine);
     report = new ValidationReport(engine);
 }
Exemplo n.º 3
0
        public AttendeeServiceInterceptor(AttendeeValidator attendeeValidator, EventValidator eventValidator, PersonValidator personValidator)
        {
            _attendeeValidator = attendeeValidator;
            _eventValidator    = eventValidator;
            _personValidator   = personValidator;
            var mappings = new Dictionary <string, Action <IInvocation> >
            {
                {
                    nameof(CreateAttendeeRelationshipAsync),
                    x => CreateAttendeeRelationshipAsync((AttendeeRelationship)x.Arguments[0])
                },
                {
                    nameof(DeleteAttendeeRelationshipAsync),
                    x => DeleteAttendeeRelationshipAsync((int)x.Arguments[0], (int)x.Arguments[1])
                },
                {
                    nameof(GetAllRelationshipsForEventAsync),
                    x => GetAllRelationshipsForEventAsync((int)x.Arguments[0])
                },
                {
                    nameof(GetSingleRelationshipAsync),
                    x => GetSingleRelationshipAsync((int)x.Arguments[0], (int)x.Arguments[1])
                },
                {
                    nameof(UpdateAttendeeRelationshipAsync),
                    x => UpdateAttendeeRelationshipAsync((AttendeeRelationship)x.Arguments[0])
                }
            };

            BuildUp(mappings);
        }
Exemplo n.º 4
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);
        }
        public void NotValidateNullPerson()
        {
            var sut    = new PersonValidator();
            var actual = sut.Validate(null);

            Assert.False(actual);
        }
Exemplo n.º 6
0
        /// <summary>
        /// Sorts the names in the given file
        /// outputs sorted names into a file named "sorted-names-list.txt".
        /// </summary>
        /// <param name="inputFilename">The file to sort.</param>
        private static void SortNames(string inputFilename)
        {
            try
            {
                var delimiter      = " ";
                var outputFilename = "sorted-names-list.txt";

                var reader     = new PersonFileReader(inputFilename);
                var parser     = new PersonFileParser(delimiter);
                var writer     = new PersonFileWriter(outputFilename);
                var sorter     = new PersonSorter(new PersonNameComparer());
                var validator  = new PersonValidator();
                var processor  = new PersonProcessor(reader, parser, writer, validator, sorter);
                var sortedList = processor.Process();

                foreach (var person in sortedList)
                {
                    System.Console.WriteLine(person.ToString());
                }
            }
            catch (Exception ex)
            {
                System.Console.WriteLine(ex.Message);
            }
        }
Exemplo n.º 7
0
        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");
        }
Exemplo n.º 8
0
        public async Task <IActionResult> PostWithManualValidation2([FromBody][CustomizeValidator(Skip = true)] Person person)
        {
            var validator = new PersonValidator();
            await validator.ValidateAndThrowAsync(person);

            return(await new ValueTask <IActionResult>(Ok()));
        }
Exemplo n.º 9
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"));
        }
Exemplo n.º 10
0
Arquivo: Person.cs Projeto: akkgr/cms
        public Person()
        {
            Jobs = new List<Job>();
            ToDoes = new List<ToDo>();

            Validator = new PersonValidator();
        }
Exemplo n.º 11
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");
        }
        public void NotValidateEmptyPerson()
        {
            var sut    = new PersonValidator();
            var actual = sut.Validate(new PersonInformation());

            Assert.False(actual);
        }
        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");
        }
Exemplo n.º 14
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 EventServiceInterceptor(EventValidator eventValidator, PersonValidator personValidator)
 {
     _eventValidator  = eventValidator;
     _personValidator = personValidator;
     BuildUp(new Dictionary <string, Action <IInvocation> >
     {
         {
             nameof(CreateEventAsync),
             x => CreateEventAsync((Event)x.Arguments[0])
         },
         {
             nameof(UpdateEventAsync),
             x => UpdateEventAsync((Event)x.Arguments[0])
         },
         {
             nameof(DeleteEventAsync),
             x => DeleteEventAsync((int)x.Arguments[0])
         },
         {
             nameof(GetEventAsync),
             x => GetEventAsync((int)x.Arguments[0])
         },
         {
             nameof(GetAllEventsForCurrentUserAsync),
             x => GetAllEventsForCurrentUserAsync()
         },
         {
             nameof(UpdateHostAsync),
             x => UpdateHostAsync((int)x.Arguments[0], (int)x.Arguments[1])
         }
     });
 }
Exemplo n.º 16
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();
        }
Exemplo n.º 17
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);
        }
Exemplo n.º 18
0
        public Response Create(string personGroupId, PersonDto dto)
        {
            try
            {
                if (dto == null)
                {
                    throw new ArgumentNullException("dto", "The object that you provided cannot be null.");
                }

                if (string.IsNullOrWhiteSpace(personGroupId))
                {
                    throw new ArgumentNullException("personGroupId", "The person group ID that you entered is invalid");
                }

                var validationResults = new PersonValidator().Validate(dto);

                if (validationResults.IsValid)
                {
                    var result = _personAPI.Create(personGroupId, dto.Name)
                                 .Result;

                    return(_responseHelper.CreateResponse <PersonDto>(
                               result, $"'{ dto.Name }' has been successfully created in the '{ personGroupId }' person-group."));
                }
                else
                {
                    throw new InvalidOperationException("The person name that you have provided is invalid.");
                }
            }

            catch (AggregateException aex)
            {
                throw new Exception($"Error Message:  { aex.Message }");
            }
        }
Exemplo n.º 19
0
        public void UpdatePerson(Person person)
        {
            PersonValidator validator = new PersonValidator();

            validator.ValidateAndThrow(person);

            this._personRepository.Update(person);
        }
Exemplo n.º 20
0
        public async Task UpdatePersonAsync(Person person)
        {
            PersonValidator validator = new PersonValidator();

            validator.ValidateAndThrow(person);

            await this._personRepository.UpdateAsync(person);
        }
Exemplo n.º 21
0
        public bool IsValid(out string message)
        {
            PersonValidator validator = new PersonValidator(this);
            bool            flag      = validator.IsValid();

            message = validator.Message;
            return(flag);
        }
Exemplo n.º 22
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);
        }
Exemplo n.º 23
0
        // 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()));
        }
Exemplo n.º 24
0
        public void Person_InvalidUser()
        {
            Person user = new Person();

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

            Assert.False(PersonValidator.Validate(user), "Invalid User");
        }
Exemplo n.º 25
0
        public void Person_ValidUser()
        {
            Person user = new Person();

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

            Assert.True(PersonValidator.Validate(user), "Valid User");
        }
Exemplo n.º 26
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);
        }
Exemplo n.º 27
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);
        }
Exemplo n.º 28
0
        public void PersonValidator_Test()
        {
            var person = new Person();

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

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

            Assert.IsTrue(actual.IsValid);
        }
Exemplo n.º 29
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
 }
Exemplo n.º 30
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);
    }
Exemplo n.º 31
0
        public void RuleForEach()
        {
            var person    = new Person();
            var validator = new PersonValidator();

            var result = validator.Validate(person);

            result.Should().NotBeNull();

            DisplayErrors(result);
        }
Exemplo n.º 32
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;
        }
        public void BadSystemFails()
        {
            // Assert
            var start = new DateTime(1999, 1, 1);
            var finish = new DateTime(2020, 12, 31);
            var validity = new DateRange(start, finish);
            var system = new SourceSystem { Name = "Test" };
            var personMapping = new PersonMapping { System = system, MappingValue = "1", Validity = validity };

            var list = new List<PersonMapping> { personMapping };
            var repository = new Mock<IRepository>();
            repository.Setup(x => x.Queryable<PersonMapping>()).Returns(list.AsQueryable());

            var badSystemIdentifier = new EnergyTrading.Mdm.Contracts.MdmId
            {
                SystemName = "Jim",
                Identifier = "1",
                StartDate = start.AddHours(-10),
                EndDate = start.AddHours(-5)
            };

            var identifierValidator = new NexusIdValidator<PersonMapping>(repository.Object);
            var validatorEngine = new Mock<IValidatorEngine>();
            validatorEngine.Setup(x => x.IsValid(It.IsAny<EnergyTrading.Mdm.Contracts.MdmId>(), It.IsAny<IList<IRule>>()))
                           .Returns((EnergyTrading.Mdm.Contracts.MdmId x, IList<IRule> y) => identifierValidator.IsValid(x, y));
            var validator = new PersonValidator(validatorEngine.Object, null);

            var person = new EnergyTrading.MDM.Contracts.Sample.Person { Identifiers = new EnergyTrading.Mdm.Contracts.MdmIdList { badSystemIdentifier } };

            // Act
            var violations = new List<IRule>();
            var result = validator.IsValid(person, violations);

            // Assert
            Assert.IsFalse(result, "Validator succeeded");
        }
        public void ValidPersonPasses()
        {
            // Assert
            var start = new DateTime(1999, 1, 1);
            var system = new SourceSystem { Name = "Test" };

            var systemList = new List<SourceSystem> { system };
            var systemRepository = new Mock<IRepository>();
            systemRepository.Setup(x => x.Queryable<MDM.SourceSystem>()).Returns(systemList.AsQueryable());

            var identifier = new EnergyTrading.Mdm.Contracts.MdmId
            {
                SystemName = "Test",
                Identifier = "1",
                StartDate = start.AddHours(-10),
                EndDate = start.AddHours(-5)
            };

            var validatorEngine = new Mock<IValidatorEngine>();
            var validator = new PersonValidator(validatorEngine.Object, null);

            var person = new EnergyTrading.MDM.Contracts.Sample.Person { Details = new EnergyTrading.MDM.Contracts.Sample.PersonDetails{Surname = "Test"}, Identifiers = new EnergyTrading.Mdm.Contracts.MdmIdList { identifier } };

            // Act
            var violations = new List<IRule>();
            var result = validator.IsValid(person, violations);

            // Assert
            Assert.IsTrue(result, "Validator failed");
            Assert.AreEqual(0, violations.Count, "Violation count differs");
        }
Exemplo n.º 35
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);
            }
        }