Esempio n. 1
0
        public async Task <IActionResult> PutCompany(long id, [FromBody] CompanyForUpdateDto company)
        {
            try
            {
                if (company == null)
                {
                    return(BadRequest("Company object is null"));
                }
                else if (!ModelState.IsValid)
                {
                    return(BadRequest("Invalid model object"));
                }

                var companyEntity = await _repository.Company.GetCompanyByIdAsync(id);

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

                _mapper.Map(company, companyEntity);
                _repository.Company.UpdateCompany(companyEntity);
                await _repository.SaveAsync();

                return(StatusCode(StatusCodes.Status200OK, "Company updated"));
            }
            catch (Exception)
            {
                return(StatusCode(StatusCodes.Status500InternalServerError));
            }
        }
        public async Task <IActionResult> UpdateCompany(int Id, CompanyForUpdateDto company)
        {
            var companyFromRepo = await _companyRepo.GetCompanyAsync(Id);

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

            var validationResults = new CompanyForUpdateDtoValidator().Validate(company);

            validationResults.AddToModelState(ModelState, null);

            if (!ModelState.IsValid)
            {
                return(BadRequest(new ValidationProblemDetails(ModelState)));
                //return ValidationProblem();
            }

            _mapper.Map(company, companyFromRepo);
            _companyRepo.UpdateCompany(companyFromRepo);

            await _companyRepo.SaveAsync();

            return(NoContent());
        }
Esempio n. 3
0
        public IActionResult UpdateCompany(Guid id, [FromBody] CompanyForUpdateDto company)
        {
            if (company == null)
            {
                _logger.LogError("CompanyForUpdateDto object sent from client is null.");
                return(BadRequest("CompanyForUpdateDto object is null"));
            }

            if (!ModelState.IsValid)
            {
                _logger.LogError("Invalid model state for the CompanyForUpdateDto object");
                return(UnprocessableEntity(ModelState));
            }

            var companyEntity = _repository.Company.GetCompany(id, trackChanges: true);

            if (companyEntity == null)
            {
                _logger.LogInfo($"Company with id: {id} doesn't exist in the database.");
                return(NotFound());
            }

            _mapper.Map(company, companyEntity);
            _repository.Save();

            return(NoContent());
        }
Esempio n. 4
0
        public async Task <IActionResult> UpdateCompany(Guid id, [FromBody] CompanyForUpdateDto company)
        {
            //if (company == null)
            //{
            //    _logger.LogError("CompanyForUpdateDto object sent from client is null.");
            //    return BadRequest("CompanyForUpdateDto object is null");
            //}

            //if (!ModelState.IsValid)
            //{
            //    _logger.LogError("Invalid model state for the CompanyForUpdateDto object");
            //    return UnprocessableEntity(ModelState);
            //}

            //var companyEntity = await _repository.Company.GetCompanyAsync(id, trackChanges: true);

            //if (companyEntity == null)
            //{
            //    _logger.LogInfo($"Company with id: {id} doesn't exist in the database.");
            //    return NotFound();
            //}
            var companyEntity = HttpContext.Items["company"] as Company;

            _mapper.Map(company, companyEntity);
            await _repository.SaveAsync();

            return(NoContent());
        }
Esempio n. 5
0
        public async Task <IActionResult> UpdateCompany(Guid id,
                                                        [FromBody] CompanyForUpdateDto company)
        {
            //if (company == null)
            //{
            //    _logger.LogError("CompanyForUpdateDto object sent from client is null.");
            //    return BadRequest("CompanyForUpdateDto object is null");
            //}
            //var companyEntity = await _repository.Company.GetCompanyAsync(id, trackChanges: true);//отслеживать изменения для апдейта
            //if (companyEntity == null)
            //{
            //    _logger.LogInfo($"Company with id: {id} doesn't exist in the database.");
            //    return NotFound();
            //}

            //_mapper.Map(company, companyEntity);

            //await _repository.SaveAsync();
            //return NoContent();

            var companyEntity = HttpContext.Items["company"] as Company;

            _mapper.Map(company, companyEntity);
            await _repository.SaveAsync();

            return(NoContent());
        }
Esempio n. 6
0
        public async Task <IActionResult> EditCompany(Guid id, CompanyForUpdateDto companyForUpdateDto)
        {
            Company company = await _repo.GetCompany(id);

            Guid jwtId = Guid.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value);

            if (id != company.Id)
            {
                return(BadRequest("Id's do not match"));
            }
            if (company == null)
            {
                return(BadRequest());
            }

            if (!await _repo.CanEditCompany(company.Id, jwtId))
            {
                return(Unauthorized());
            }
            company = _mapper.Map(companyForUpdateDto, company);
            Company updatedCompany = await _repo.UpdateCompany(company.Id, company);

            if (updatedCompany != null)
            {
                return(Ok(_mapper.Map <CompanyForReturnDto>(company)));
            }
            return(BadRequest("SOmething went wrong updating the company"));
        }
        public async Task <IActionResult> UpdateCompany(Guid id, [FromBody] CompanyForUpdateDto company)
        {
            var companyEntity = HttpContext.Items["company"] as Company;

            _mapper.Map(company, companyEntity);
            await _repository.SaveAsync();

            return(NoContent());
        }
        public ActionResult PatchCompany(Guid companyId, [FromBody] JsonPatchDocument <CompanyForUpdateDto> patchDocument)
        {
            if (patchDocument == null)
            {
                return(BadRequest());
            }

            if (!_companyRepository.CompanyExists(companyId))
            {
                return(NotFound());
            }

            var companyFromRepo = _companyRepository.GetCompany(companyId);

            if (companyFromRepo == null)
            {
                var companyDto = new CompanyForUpdateDto();
                patchDocument.ApplyTo(companyDto, ModelState);

                if (!TryValidateModel(companyDto))
                {
                    return(ValidationProblem(ModelState));
                }

                var companyToAdd = _mapper.Map <Entities.Company>(companyDto);
                companyToAdd.Id = companyId;

                _companyRepository.AddCompany(companyId, companyToAdd);

                _companyRepository.Save();

                var companyToReturn = _mapper.Map <CompanyDto>(companyToAdd);

                return(CreatedAtRoute("GetCompany",
                                      new { companyId }, companyToReturn));
            }

            var companyToPatch = _mapper.Map <CompanyForUpdateDto>(companyFromRepo);

            patchDocument.ApplyTo(companyToPatch, ModelState);
            //patchDocument.ApplyTo(companyToPatch);

            if (!TryValidateModel(companyToPatch))
            {
                return(ValidationProblem(ModelState));
            }

            _mapper.Map(companyToPatch, companyFromRepo);

            _companyRepository.UpdateCompany(companyFromRepo);

            _companyRepository.Save();

            return(NoContent());
        }
Esempio n. 9
0
 private void ApplyUpdateToEntity(Company company, CompanyForUpdateDto companyUpdate)
 {
     company.Name                 = companyUpdate.Name;
     company.HqCity               = companyUpdate.HqCity;
     company.HqCountry            = companyUpdate.HqCountry;
     company.PostCode             = companyUpdate.PostCode;
     company.CompanyDescription   = companyUpdate.CompanyDescription;
     company.Category             = companyUpdate.Category.ToCompanyCategory();
     company.LogoFileName         = companyUpdate.LogoFileName;
     company.Website              = companyUpdate.Website;
     company.EmployerBrandWebsite = companyUpdate.EmployerBrandWebsite;
 }
Esempio n. 10
0
        public async Task <IActionResult> UpdateCompany(Guid id, [FromBody] CompanyForUpdateDto company)
        {
            //------------- The commented code below is replaced by the ActionFilter called as an attribute above ----------

            //if (company == null)
            //{
            //    _logger.LogError("CompanyForUpdateDto object sent from client is null.");
            //    return BadRequest("CompanyForUpdateDto object is null");
            //}

            //if (!ModelState.IsValid)
            //{
            //    _logger.LogError("Invalid model state for the EmployeeForUpdateDto object");
            //    return UnprocessableEntity(ModelState);
            //}


            var companyEntity = HttpContext.Items["company"] as Company;
            //------------- The commented code below is replaced by the IAsyncActionFilter called as an attribute above ----------

            //var companyEntity = await _repository.Company.GetCompanyAsync(id, trackChanges: true);
            //if (companyEntity == null)
            //{
            //    _logger.LogInfo($"Company with id: {id} doesn't exist in the database.");
            //    return NotFound();
            //}

            //extracting the added employee(s)
            List <EmployeeForCreationDto> employeeForCreationDtoList = company.Employees.ToList();
            List <Employee> employees = new List <Employee>();

            foreach (EmployeeForCreationDto employeeForCreationDto in employeeForCreationDtoList)
            {
                employees.Add(new Employee {
                    Name     = employeeForCreationDto.Name,
                    Age      = employeeForCreationDto.Age,
                    Position = employeeForCreationDto.Position
                });
            }

            //_mapper.Map(company, companyEntity);
            companyEntity.Name      = company.Name;
            companyEntity.Address   = company.Address;
            companyEntity.Country   = company.Country;
            companyEntity.Employees = (ICollection <Employee>)employees;

            await _repository.SaveAsync();

            return(NoContent());
        }
Esempio n. 11
0
 public static Company ToEntity(this CompanyForUpdateDto source)
 {
     return(new Company()
     {
         Name = source.Name,
         HqCity = source.HqCity,
         HqCountry = source.HqCountry,
         PostCode = source.PostCode,
         CompanyDescription = source.CompanyDescription,
         Category = source.Category.ToCompanyCategory(),
         LogoFileName = source.LogoFileName,
         Website = source.Website,
         EmployerBrandWebsite = source.EmployerBrandWebsite
     });
 }
Esempio n. 12
0
        public async Task <IActionResult> UpdateCompany(Guid id, [FromBody] CompanyForUpdateDto
                                                        company)
        {
            // Action service filter validates the incoming model

            //Action service filter confirms if company exists

            var companyEntity = HttpContext.Items["company"] as Company;

            //map company to entity and save
            _mapper.Map(company, companyEntity);
            await _repository.SaveAsync();

            return(NoContent());
        }
        //public IActionResult UpdateCompany(Guid id, [FromBody] CompanyForUpdateDto company)
        public async Task <IActionResult> UpdateCompany(Guid id, [FromBody] CompanyForUpdateDto company)
        {
            var companyEntity = HttpContext.Items["company"] as Company; //Version 2

            if (companyEntity == null)
            {
                _logger.LogInfo($"Company with id: {id} doesn't exist in the database.");
                return(NotFound());
            } //Version 1, removed in Version 2
            _mapper.Map(company, companyEntity);
            //_repository.Save();
            await _repository.SaveAsync();

            return(NoContent());
        }
Esempio n. 14
0
        public void UpdateCompany_UnExistingCompanyId_ReturnsNotFoundResult()
        {
            // Arrange
            Company companyToUpdate = SeedTestData.GetTestCompany();

            CompanyForUpdateDto companyForUpdateDto = null;

            var controller = new CompaniesController(mockRepo.Object, _mapper);
            // Act
            var result = controller.UpdateCompany(companyToUpdate.Id, companyForUpdateDto);

            // Assert
            Assert.IsInstanceOf <BadRequestObjectResult>(result);

            mockRepo.Verify(repo => repo.Company.GetCompany(companyToUpdate.Id, true), Times.Never);
            mockRepo.Verify(repo => repo.Save(), Times.Never);
        }
        public async Task <IActionResult> UpdateCompany(int id, CompanyForUpdateDto companyForUpdateDto)
        {
            var companyFromRepo = await _repo.GetCompany(id);

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

            _mapper.Map(companyForUpdateDto, companyFromRepo);

            if (await _repo.SaveAll())
            {
                return(NoContent());
            }

            throw new Exception($"Updating Company {id} failed on save");
        }
Esempio n. 16
0
        public async Task <IActionResult> UpdateCompanyAsync(Guid id, [FromBody] CompanyForUpdateDto
                                                             company)
        {
            var companyEntity = await _repository.Company.GetCompanyAsync(id, trackChanges :
                                                                          true);

            if (companyEntity == null)
            {
                _logger.LogInfo($"Company with id: {id} doesn't exist in the database.");

                return(NotFound());
            }

            _mapper.Map(company, companyEntity);
            await _repository.SaveAsync();

            return(NoContent());
        }
        public IActionResult UpdateCompany(Guid id, [FromBody] CompanyForUpdateDto company)
        {
            //if (company == null)
            //{
            //    logger.LogError("CompanyForUpdateDto object sent from client is null.");
            //    return BadRequest("CompanyForUpdateDto object is null");
            //}
            var companyEntity = HttpContext.Items["company"] as Company; //await repository.Company.GetCompany(id, trackChanges: true);

            //if (companyEntity == null)
            //{
            //    logger.LogInfo($"Company with id: {id} doesn't exist in the database.");
            //    return NotFound();
            //}
            mapper.Map(company, companyEntity);
            repository.Save();
            return(NoContent());
        }
        public async Task <ActionResult <CompanyDto> > Update(int id, CompanyForUpdateDto companyForUpdate)
        {
            if (!await _companyService.Exists(id))
            {
                return(NotFound());
            }

            if (!await _companyService.CanIsinByUsed(companyForUpdate.Isin, id))
            {
                ModelState.AddModelError(nameof(companyForUpdate.Isin), "This ISIN is already used!");
                return(ValidationProblem());
            }

            Company company = _mapper.Map <Company>(companyForUpdate);

            await _companyService.UpdateAsync(id, company);

            return(Ok(_mapper.Map <CompanyDto>(company)));
        }
Esempio n. 19
0
        public async Task <IActionResult> UpdateCompany(Guid companyId, CompanyForUpdateDto companyUpdate)
        {
            var companyFromRepo = await _repository.GetCompanyAsync(companyId);

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

            // Need to keep repoInstance for Entity Framework
            ApplyUpdateToEntity(companyFromRepo, companyUpdate);

            // Action without any effect
            _repository.UpdateCompany(companyFromRepo);

            await _repository.SaveChangesAsync();

            return(NoContent());
        }
Esempio n. 20
0
        public async Task <IActionResult> UpdateCompany(Guid id, [FromBody] CompanyForUpdateDto company)
        {
            if (company == null)
            {
                _logger.LogError("CompanyForUpdateDto object sent from client is  null");
                return(BadRequest("CompanyForUpdateDto object is  null"));
            }
            var companyEntity = await _repositrory.Company.GetCompanyAsync(id, trackChanges : true);

            if (companyEntity == null)
            {
                _logger.LogInfo($"Company Wiht Id : {id} doesn't exist in the database");
                return(NotFound());
            }
            _mapper.Map(company, companyEntity);
            await _repositrory.SaveAsync();

            return(NoContent());
        }
Esempio n. 21
0
        public IActionResult UpdateCompany(Guid companyId, [FromBody] CompanyForUpdateDto companyDto)
        {
            if (companyDto == null)
            {
                return(BadRequest("CompanyForUpdateDto object is null"));
            }
            var companyEntity = _repositoryManager.Company.GetCompany(companyId,
                                                                      trackChanges: true);

            if (companyEntity == null)
            {
                return(NotFound());
            }
            companyEntity.Name    = companyDto.Name;
            companyEntity.Address = companyDto.Address;
            companyEntity.Country = companyDto.Country;
            //of via mapper:_mapper.Map(companyDto, companyEntity);
            _repositoryManager.Save();
            return(Ok(companyEntity));
        }
Esempio n. 22
0
        public IActionResult UpdateCompany(Guid companyId, [FromBody] CompanyForUpdateDto companyDto)
        {
            if (companyDto == null)
            {
                BadRequest("EmployeeForUpdateDto is empty");
            }
            var companyEntity = _repositoryManager.Company.GetCompany(companyId, trackChanges: true);  //moet true zijn

            if (companyEntity == null)
            {
                NotFound(); //404
            }
            //ovwel manueel
            //companyEntity.Name = companyDto.Name;
            //companyEntity.Address = companyDto.Address;
            //companyEntity.Country = companyDto.Country;

            //ofwel zelf ofwel met automapper
            _mapper.Map(companyDto, companyEntity);
            _repositoryManager.Save();
            return(Ok(companyEntity));
        }
Esempio n. 23
0
        public IActionResult UpdateCompany(Guid id, [FromBody] CompanyForUpdateDto company)
        {
            #region использование валидации

            /*Чтобы вернуть 422 вместо 400, первое, что нам нужно сделать, это подавить
             * BadRequest ошибка, когда ModelState является недействительным.
             * Мы собираемся сделать это, добавив этот код в Startup класс в ConfigureServices метод:
             * services.Configure<ApiBehaviorOptions>(options =>
             * {
             * options.SuppressModelStateInvalidFilter = true;
             * });
             */

            #endregion
            if (!ModelState.IsValid)
            {
                _logger.LogError("Invalid model state for the EmployeeForCreationDto object");
                return(UnprocessableEntity(ModelState));
            }
            if (company == null)
            {
                _logger.LogError("CompanyForUpdateDto object sent from client is null.");
                return(BadRequest("CompanyForUpdateDto object is null"));
            }

            var companyEntity = _wrapper.Company.GetCompanyAsync(id, trackChanges: true);
            if (companyEntity == null)
            {
                _logger.LogInfo($"Company with id: {id} doesn't exist in the database.");
                return(NotFound());
            }

            _mapper.Map(company, companyEntity);
            _wrapper.SaveAsync();

            return(NoContent());
        }
Esempio n. 24
0
        public void UpdateCompany_ValidInput_ReturnsOkObjectResult_WithUpdatedCompany()
        {
            // Arrange
            Company companyToUpdate = SeedTestData.GetTestCompany();

            companyToUpdate.Name    = "gewijzigde naam";
            companyToUpdate.Address = "gewijzigd adres";
            companyToUpdate.Country = "gewijzigd land";
            CompanyForUpdateDto companyForUpdateDto = new CompanyForUpdateDto
            {
                Name    = companyToUpdate.Name,
                Address = companyToUpdate.Address,
                Country = companyToUpdate.Country
            };

            mockRepo.Setup(repo => repo.Company.GetCompany(companyToUpdate.Id, true))
            .Returns(companyToUpdate).Verifiable();
            mockRepo.Setup(repo => repo.Save()).Verifiable();

            var controller = new CompaniesController(mockRepo.Object, _mapper);

            //Act
            var result = controller.UpdateCompany(companyToUpdate.Id, companyForUpdateDto);

            // Assert
            Assert.IsInstanceOf <OkObjectResult>(result);
            OkObjectResult okResult = result as OkObjectResult;

            Assert.IsInstanceOf <Company>(okResult.Value);
            var updatedCompany = okResult.Value as Company;

            Assert.AreEqual(companyToUpdate.Name, updatedCompany.Name);
            Assert.AreEqual(companyToUpdate.Address, updatedCompany.Address);
            Assert.AreEqual(companyToUpdate.Country, updatedCompany.Country);
            mockRepo.Verify(repo => repo.Company.GetCompany(companyToUpdate.Id, true), Times.Once);
            mockRepo.Verify(repo => repo.Save(), Times.Once);
        }
Esempio n. 25
0
        public IActionResult UpdateCompany(
            Guid id,
            [FromBody] CompanyForUpdateDto companyUpdates)
        {
            // Update using PUT for demonstration purposes. No upserting and no patching.

            if (companyUpdates == null)
            {
                return(BadRequest());
            }

            Company savedCompany = _repository.GetCompany(id);

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

            AutoMapper.Mapper.Map(companyUpdates, savedCompany);

            _repository.UpdateCompany(savedCompany);             // needs try / catch

            return(NoContent());
        }