public void TestValidator()
        {
            var student = new Student()
            {
                Name = "TJ",
                GPA  = 4.1
            };

            var validator = new StudentValidator();

            Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo(string.Empty); // invariant

            var validationResult = validator.Validate(student);

            Assert.Equal(2, validationResult.Errors.Count);

            Assert.Equal("Name must be at least 3 characters long", validationResult.Errors[0].ErrorMessage);

            Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("de-DE");

            validationResult = validator.Validate(student);

            Assert.Equal(2, validationResult.Errors.Count);

            Assert.Equal("Das name must be at least 3 characters long", validationResult.Errors[0].ErrorMessage);
        }
Ejemplo n.º 2
0
        private static void ValidateStudent(Student student)
        {
            var validator = new StudentValidator();

            var results = validator.Validate(student);

            if (results.IsValid)
            {
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine("Student are successfully validated.");
                Console.ForegroundColor = ConsoleColor.Gray;
            }
            else
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Failed. Errors:");
                Console.ForegroundColor = ConsoleColor.DarkRed;

                foreach (ValidationFailure failure in results.Errors)
                {
                    Console.WriteLine(failure.ErrorMessage);
                }
                Console.ForegroundColor = ConsoleColor.Gray;
            }
            Console.WriteLine();
        }
        public AddStudentResponse AddStudent(Student student)
        {
            var validator = new StudentValidator();
            var results   = validator.Validate(student);


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

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


            using (var unitOfWork =
                       new UnitOfWork(new DatabaseContext()))
            {
                unitOfWork.Students.Add(student);
                unitOfWork.Complete();
            }
            return(new AddStudentResponse {
                Status = true
            });
        }
Ejemplo n.º 4
0
        public async Task CreateStudent(CreateStudentInput createStudentsInput)
        {
            try
            {
                var validationMaessage = string.Empty;
                var studentValidator   = new StudentValidator();
                var result             = studentValidator.Validate(createStudentsInput);
                if (result.IsValid)
                {
                    using (var unitOfWork = _unitOfWorkManager.Begin())
                    {
                        var student = base.ObjectMapper.Map <Student>(createStudentsInput);
                        await _studentRepository.InsertAsync(student);

                        unitOfWork.Complete();
                    }
                }
                else
                {
                    foreach (var failure in result.Errors)
                    {
                        validationMaessage += "Property " + failure.PropertyName + " failed validation. Error was: " + failure.ErrorMessage + Environment.NewLine;
                    }
                    throw new UserFriendlyException(validationMaessage);
                }
            }
            catch (Exception ex)
            {
                throw new UserFriendlyException(ex.Message);;
            }
        }
Ejemplo n.º 5
0
 public void AddParticipant(Student s)
 {
     if (validator.Validate(s))
     {
         participants.Add(s);
     }
 }
 public void Validate([CallerMemberName] string propertyName = "")
 {
     if (validator == null)
     {
         throw new NullReferenceException("An instance of the validator is required");
     }
     var result = validator.Validate(Student);
 }
Ejemplo n.º 7
0
        public override void Validate()
        {
            var validator        = new StudentValidator();
            var validationResult = validator.Validate(this);

            if (!validationResult.IsValid)
            {
                throw new ValidationException(validationResult.Errors.Select(i => i.ErrorCode));
            }
        }
Ejemplo n.º 8
0
        public void AddStudent(string CNP, string nume, string prenume, double mediaAnuala)
        {
            Student student = new Student(CNP, nume, prenume, mediaAnuala);
            string  errors  = studentValidator.Validate(student);

            if (errors != string.Empty)
            {
                throw new ValidationException(errors);
            }
            studentRepository.Save(student);
        }
Ejemplo n.º 9
0
        public void CreateSuccess()
        {
            var student = new StudentViewModel();

            student.Name      = "Alberto";
            student.CPF       = "44444444444";
            student.BirthDate = "30/06/1954";

            Assert.True(validator.Validate(student).IsValid);
        }
Ejemplo n.º 10
0
        public async Task <bool> Create(StudentViewModel svm)
        {
            if (!_studentValidator.Validate(svm).IsValid)
            {
                return(Task.Run(() => false).Result);
            }

            Student student = Student.Create(svm.Name, svm.CPF, DateTime.Parse(svm.BirthDate));
            await _uow.StudentRepository.Add(student);

            _uow.ExecuteTransaction();
            return(await Task.Run(() => true));
        }
        public void Validate_WhenAgeIsUnder18_ReturnsFalse()
        {
            //Arrange
            var validator = new StudentValidator(null);
            var student   = new Student();

            student.Age = 17;

            //Act
            var result = validator.Validate(student);

            //Assert
            Assert.IsFalse(result);
        }
Ejemplo n.º 12
0
        public IActionResult EditPersonalInfo(long id, StudentDto request)
        {
            Student student = _studentRepository.GetById(id);

            var validator = new StudentValidator();

            validator.Validate(request);

            var addresses = request.Addresses.Select(a => new Address(a.Street, a.City, a.State, a.ZipCode)).ToList();

            //student.EditPersonalInfo(new StudentName(request.Name), addresses);
            _studentRepository.Save(student);

            return(Ok());
        }
Ejemplo n.º 13
0
        public ActionResult Post(StudentDTO studentDTO)
        {
            Student student = studentDTO.Adapt <Student>();

            var validator = new StudentValidator();
            var results   = validator.Validate(student);

            if (!results.IsValid)
            {
                StatusCode(400);
                return(StatusCode(400));
            }

            return(Ok());
        }
        public ActionResult Index(Student student)
        {
            var validator = new StudentValidator();
            var result    = validator.Validate(student);

            if (!result.IsValid)
            {
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(error.PropertyName, error.ErrorMessage);
                }
            }

            return(View(student));
        }
        public async Task <SignUpToCourseCommandResponse> Handle(SignUpToCourseCommand command)
        {
            var student          = new Student(command.Name, command.Email, command.DateOfBirth);
            var studentValidator = new StudentValidator();
            var validationResult = studentValidator.Validate(student);
            var response         = new SignUpToCourseCommandResponse();

            if (validationResult.IsValid)
            {
                var course = await _repository.GetByIdAsync(command.CourseId);

                if (course == null)
                {
                    response.Message = "Course not found.";
                    response.AddError($"Course Id '{command.CourseId}' not found.");
                }
                else if (course.IsFull)
                {
                    response.Message = "Course max students number reached.";
                    response.AddError("Sorry, We this course is closed for new students.");
                }
                else
                {
                    course.NumberOfStudents += 1;
                    var success = await _repository.AddStudentToCourseAsync(course, student);

                    if (success)
                    {
                        response.Message = "OK";
                        response.Course  = course;
                        response.Student = student;
                    }

                    if (!success)
                    {
                        response.Message = "Oops, Something went wrong.";
                        response.AddError("Sorry, We had a problem enrolling you to this course, try later.");
                    }
                }
            }
            else
            {
                response.Message = "Oops, Something went wrong.";
                response.AddErrorsRange(validationResult.Errors.Select(v => v.ErrorMessage));
            }

            return(response);
        }
        public void Validate_WhenStudentIsValid_ReturnsTrue()
        {
            //Arrange
            var fakeRepo = new FakeStudentRepository();

            fakeRepo.HasRegistered = true;

            var validator = new StudentValidator(fakeRepo);
            var student   = new Student();

            student.Age = 20;

            //Act
            var result = validator.Validate(student);

            //Assert
            Assert.IsTrue(result);
        }
        public async Task <IHttpActionResult> PostStudentEntity(Guid classId, StudentEntity studentEntity)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            StudentValidator validator = new StudentValidator(classId);
            ValidationResult results   = validator.Validate(studentEntity);

            bool validationSucceeded = results.IsValid;

            if (!validationSucceeded)
            {
                return(BadRequest("Surname must be unique."));
            }


            db.StudentEntities.Add(studentEntity);

            try
            {
                await db.SaveChangesAsync();

                var classEntity = db.ClassEntities.Find(classId);
                classEntity.StudentEntities.Add(studentEntity);
                await db.SaveChangesAsync();
            }
            catch (DbUpdateException)
            {
                if (StudentEntityExists(studentEntity.ID))
                {
                    return(Conflict());
                }
                else
                {
                    throw;
                }
            }

            return(Ok(studentEntity.ID)); //CreatedAtRoute("DefaultApi", new { id = studentEntity.ID }, studentEntity);
        }
Ejemplo n.º 18
0
        private void btnAdd_Click(object sender, EventArgs e)
        {
            student studentModel = new student();

            try
            {
                studentModel.Id     = txtNationalId.Text.Trim();
                studentModel.name   = txtName.Text.Trim();
                studentModel.gender = cbGender.selectedValue.Trim();
                studentModel.nat    = txtNational.Text.Trim();
                //studentModel.dob =  DateTime.ParseExact(txtDOB.Text.Trim(), "d/M/yyyy", CultureInfo.InvariantCulture).Date;
                if (validDOB(txtDOB.Text.Trim()) != null)
                {
                    studentModel.dob = validDOB(txtDOB.Text.Trim()).Value.Date;
                }

                studentModel.date = DateTime.Now.Date;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            //Validate
            StudentValidator validator = new StudentValidator();

            var result = validator.Validate(studentModel);

            if (result.IsValid == false)
            {
                //foreach (ValidationFailure failure in result.Errors)
                //{
                //    //com.Alert($"{failure.ErrorMessage}", Alert.enmType.Error);
                //    MessageBox.Show($"{failure.ErrorMessage}");
                //}

                MessageBox.Show($"{result.Errors[0].ErrorMessage}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                this.DialogResult = DialogResult.None;
                return;
            }

            //Insert
            using (hcDataContext db = new hcDataContext())
            {
                try
                {
                    db.students.InsertOnSubmit(studentModel);
                    db.SubmitChanges();
                }
                catch (DbEntityValidationException ex)
                {
                    foreach (var errors in ex.EntityValidationErrors)
                    {
                        foreach (var validationError in errors.ValidationErrors)
                        {
                            // get the error message
                            string errorMessage = validationError.ErrorMessage;
                            MessageBox.Show(errorMessage);
                        }
                    }
                }
            }
        }