예제 #1
0
        public IActionResult Put(int id, [FromBody] Applicant a)
        {
            ApplicantValidator v      = new ApplicantValidator();
            ValidationResult   result = v.Validate(a);

            if (result.IsValid)
            {
                var queryApplicant = _applicantContext.Applicants.Find(id);
                if (queryApplicant != null)
                {
                    queryApplicant.Address         = a.Address;
                    queryApplicant.Age             = a.Age;
                    queryApplicant.CountryOfOrigin = a.CountryOfOrigin;
                    queryApplicant.EMailAdress     = a.EMailAdress;
                    queryApplicant.FamilyName      = a.FamilyName;
                    queryApplicant.Hired           = a.Hired;
                    queryApplicant.Name            = a.Name;
                    _applicantContext.SaveChanges();

                    return(Ok());
                }
                else
                {
                    return(NotFound());
                }
            }
            else
            {
                return(BadRequest());
            }
        }
예제 #2
0
        public async Task <IActionResult> Post([FromBody] ApplicantViewModel inputApplicant)
        {
            // mapping shoud be done using Automapper or similar libraries but for simplicity it is mapped manually
            var applicant = new Applicant {
                Name = inputApplicant.Name, FamilyName = inputApplicant.FamilyName, Address = inputApplicant.Address, Age = inputApplicant.Age, CountryOfOrigin = inputApplicant.CountryOfOrigin, EmailAdress = inputApplicant.EmailAdress, Hired = inputApplicant.Hired
            };
            var applicantValidator = new ApplicantValidator();
            var result             = await applicantValidator.ValidateAsync(applicant);

            if (result.IsValid)
            {
                var addedApplicant = applicantManager.Add(applicant);
                if (addedApplicant != null)
                {
                    logger.Information($"Added new Apllicant with Id:{applicant.ID}");
                    return(CreatedAtAction("Get", new { id = applicant.ID }, applicant));
                }
                else
                {
                    logger.Warning("Failed to Add a new Applicant with Post request");
                    return(BadRequest());
                }
            }
            else
            {
                logger.Warning("Failed to Add a new Applicant with Post request, validation failed");
                return(BadRequest());
            }
        }
예제 #3
0
        public static async Task <List <KeyValue> > ApplicantValidationErrors(Applicant applicant)
        {
            var validationErrors = new List <KeyValue>();
            var validator        = new ApplicantValidator();

            var results = await validator.ValidateAsync(applicant);

            var validatedResponseForCountry = await HttpClientService.ValidateCountryName(applicant.CountryOfOrigin);

            if (!results.IsValid)
            {
                validationErrors.AddRange(results.Errors.Select(error => new KeyValue
                {
                    PropertyName        = error.PropertyName,
                    PropertyValue       = error.ErrorMessage,
                    HasValidationErrors = true
                }));

                return(validationErrors);
            }

            if (!validatedResponseForCountry.Success)
            {
                validationErrors.Add(new KeyValue
                {
                    PropertyName        = "Country",
                    PropertyValue       = validatedResponseForCountry.Message,
                    HasValidationErrors = true
                });
            }

            return(validationErrors);
        }
예제 #4
0
        public async Task <IActionResult> Put([FromBody] Applicant inputApplicant)
        {
            var applicant          = inputApplicant;
            var applicantValidator = new ApplicantValidator();
            var result             = await applicantValidator.ValidateAsync(applicant);

            if (result.IsValid)
            {
                var updatedApplicant = applicantManager.Update(applicant);
                if (updatedApplicant != null)
                {
                    logger.Information($"updated Apllicant with Id:{applicant.ID}");
                    return(Ok(updatedApplicant));
                }
                else
                {
                    logger.Warning("Failed to update Applicant with Put request");
                    return(BadRequest());
                }
            }
            else
            {
                logger.Warning("Failed to update Applicant with Put request, validation failed!");
                return(BadRequest());
            }
        }
예제 #5
0
        public bool UpdateApplicant(ApplicantObj applicant)
        {
            try
            {
                ApplicantValidator validator = new ApplicantValidator();

                ValidationResult results = validator.Validate(applicant);
                if (!results.IsValid)
                {
                    return(false);
                }
                Applicant app = _context.Applicants.Where(a => a.ID == applicant.ID).FirstOrDefault();
                if (app != null)
                {
                    app.Address         = applicant.Address;
                    app.Age             = applicant.Age;
                    app.CountryOfOrigin = applicant.CountryOfOrigin;
                    app.EMailAdress     = applicant.EMailAdress;
                    app.FamilyName      = applicant.FamilyName;
                    app.Hired           = applicant.Hired;
                    app.Name            = applicant.Name;
                    _context.SaveChangesAsync();
                    return(true);
                }

                return(false);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.Message + " " + ex.StackTrace);
                return(false);
            }
        }
        public async Task <IActionResult> Add(ApplicantViewModel applicantViewModel)
        {
            try
            {
                var validator = new ApplicantValidator();
                var result    = validator.Validate(applicantViewModel);
                if (!result.IsValid)
                {
                    return(BadRequest(result.Errors));
                }

                var addTuple = await _applicantService.Add(applicantViewModel);

                if (string.IsNullOrEmpty(addTuple.errorMessage))
                {
                    return(CreatedAtAction(nameof(Get), new { id = addTuple.applicantViewModel.Id }, addTuple.applicantViewModel));
                }
                else
                {
                    return(BadRequest(addTuple.errorMessage));
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.Message);
                return(StatusCode((int)HttpStatusCode.InternalServerError));
            }
        }
예제 #7
0
        public void WhenFamilyNameIsEmpty_ShouldHaveError()
        {
            _fakeHttpMessageHandler.Setup(f => f.Send(It.IsAny <HttpRequestMessage>())).Returns(new HttpResponseMessage
            {
                StatusCode = HttpStatusCode.OK,
                Content    = new StringContent(@"{
          'name': 'Germany'
        }")
            });

            var model = new ApplicantModel
            {
                ID              = 1,
                Age             = 24,
                Hired           = true,
                Name            = "John Doe",
                FamilyName      = "",
                CountryOfOrigin = "Germany",
                EmailAddress    = "*****@*****.**",
                Address         = "Block 10A New State Avenue",
            };
            var sut     = new ApplicantValidator(_httpClient);
            var isValid = sut.Validate(model).IsValid;

            Assert.False(isValid);
        }
예제 #8
0
        public void WhenModelIsValid_ShouldNotHaveError()
        {
            _fakeHttpMessageHandler.Setup(f => f.Send(It.IsAny <HttpRequestMessage>())).Returns(new HttpResponseMessage
            {
                StatusCode = HttpStatusCode.OK,
                Content    = new StringContent(@"{
          'name': 'Nigeria',
          'message': 'Not Found'
        }")
            });

            var model = new ApplicantModel
            {
                ID              = 1,
                Age             = 24,
                Hired           = true,
                Name            = "James",
                FamilyName      = "Smith",
                CountryOfOrigin = "Nigeria",
                EmailAddress    = "*****@*****.**",
                Address         = "Block 10A New State Avenue",
            };
            var sut     = new ApplicantValidator(_httpClient);
            var isValid = sut.Validate(model).IsValid;

            Assert.True(isValid);
        }
예제 #9
0
 public ApplicantManager(ApplicantValidator validator,
                         IApplicantRepository applicantRepository,
                         IMapper mapper)
 {
     _mapper = mapper;
     _applicantRepository = applicantRepository;
     _validator           = validator;
 }
예제 #10
0
        public IActionResult Post([FromBody] Applicant a)
        {
            ApplicantValidator v      = new ApplicantValidator();
            ValidationResult   result = v.Validate(a);

            if (result.IsValid)
            {
                var qu   = _applicantContext.Applicants.Add(a);
                var user = _applicantContext.SaveChanges();
                return(Created("/" + a.ID, user));
            }
            else
            {
                return(BadRequest());
            }
        }
예제 #11
0
        public ActionResult <IEnumerable <Applicant> > Post(Applicant applicant)
        {
            ApplicantValidator validator = new ApplicantValidator();
            var validateResult           = validator.Validate(applicant);

            if (validateResult.IsValid)
            {
                dbContext.Applicants.Add(applicant);
                dbContext.SaveChanges();
                return(CreatedAtAction(nameof(Get), new { id = applicant.ID }, applicant));
            }
            else
            {
                string allMessages = validateResult.ToString("~");
                return(BadRequest(new { Message = allMessages }));
            }
        }
예제 #12
0
        public async Task <int> Update(int id, Applicant applicant)
        {
            var validator           = new ApplicantValidator();
            ValidationResult result = validator.Validate(applicant);

            if (result.IsValid)
            {
                return(await _repository.Update(id, applicant));
            }

            var exceptionMessage = String.Join(",",
                                               result.Errors.Select(x => $"{x.ErrorMessage}").ToArray());

            _logger.LogError(exceptionMessage);

            throw new Exception(exceptionMessage);
        }
예제 #13
0
        public async Task <ApplicantObjResponse> AddApplicant(ApplicantObj applicant)
        {
            try
            {
                ApplicantValidator validator = new ApplicantValidator();

                ValidationResult results = validator.Validate(applicant);
                if (!results.IsValid)
                {
                    IList <ValidationFailure> failures = results.Errors;
                    return(new ApplicantObjResponse()
                    {
                        ValidationResults = failures
                    });
                }
                var app = new Applicant
                {
                    Address         = applicant.Address,
                    Age             = applicant.Age,
                    EMailAdress     = applicant.EMailAdress,
                    FamilyName      = applicant.FamilyName,
                    Hired           = applicant.Hired,
                    Name            = applicant.Name,
                    CountryOfOrigin = applicant.CountryOfOrigin
                };
                _logger.LogInformation($"request from applicant--- {JsonConvert.SerializeObject(app)}");
                var res = await _context.Applicants.AddAsync(app);

                await _context.SaveChangesAsync();

                return(new ApplicantObjResponse()
                {
                    Success = true
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.Message + " " + ex.StackTrace);
                return(new ApplicantObjResponse()
                {
                    Success = false
                });
            }
        }
예제 #14
0
        public ActionResult Put(int id, Applicant newApplicant)
        {
            ApplicantValidator validator = new ApplicantValidator();
            var validateResult           = validator.Validate(newApplicant);

            if (validateResult.IsValid)
            {
                newApplicant.ID = id;
                dbContext.Attach(newApplicant);
                dbContext.Entry(newApplicant).State = EntityState.Modified;
                dbContext.SaveChanges();
                return(Ok());
            }
            else
            {
                string allMessages = validateResult.ToString("~");
                return(BadRequest(new { Message = allMessages }));
            }
        }
예제 #15
0
        public ActionResult <ApplicantModel> CreateApplicant([FromBody] ApplicantModel applicantModel)
        {
            try
            {
                ApplicantValidator validator = new ApplicantValidator();

                ValidationResult result = validator.Validate(applicantModel);
                return(Ok());
            }
            catch (Exception ex)
            {
                return(BadRequest());
            }
            //pet.Id = _petsInMemoryStore.Any() ?
            //         _petsInMemoryStore.Max(p => p.Id) + 1 : 1;
            //_petsInMemoryStore.Add(pet);

            //return CreatedAtAction(nameof(GetById), new { id = pet.Id }, pet);
        }
예제 #16
0
 public ApplicantRepository(DataContext context, ApplicantValidator applicantValidator)
 {
     _context   = context;
     _validator = applicantValidator;
 }