public async Task Update_ValidObject_CorrectCallsPerformed()
        {
            //Arrange
            var articleForUpdate = new ArticleForUpdateDto()
            {
                Id                = 1,
                Name1             = "1st article Updated",
                SupplierId        = "sup id",
                SupplierReference = "sup ref",
                PurchasePrice     = 99.99M
            };
            var updateArticleCommand = new UpdateArticleCommand(_unitOfWorkMock.Object, _writeMapper);

            _articleRepositoryMock.Setup(r => r.GetArticleByIdAsync(articleForUpdate.Id)).Returns(Task.FromResult(_testArticles.First()));
            _unitOfWorkMock.Setup(uow => uow.Commit()).Returns(Task.FromResult(true));

            //Act
            var result = await updateArticleCommand.Execute(articleForUpdate);

            //Assert
            _articleRepositoryMock.Verify(r => r.GetArticleByIdAsync(It.IsAny <int>()), Times.Once);
            _articleRepositoryMock.Verify(r => r.Update(It.IsAny <Article>()), Times.Once);
            Assert.That(result, Is.EqualTo(true));
            Assert.That(_testArticles.First().Name1, Is.EqualTo(articleForUpdate.Name1));
        }
Example #2
0
        public IActionResult UpdateArticleForUser(Guid userId,
                                                  Guid articleId,
                                                  ArticleForUpdateDto article, Guid tagId)
        {
            if (!_articleLibraryRepository.UserExists(userId))
            {
                return(NotFound());
            }

            var articleForUserFromRepo = _articleLibraryRepository.GetArticle(userId, articleId);

            if (articleForUserFromRepo == null)
            {
                var articleToAdd = _mapper.Map <Article>(article);
                articleToAdd.Id = articleId;

                _articleLibraryRepository.AddArticle(userId, articleToAdd, tagId);
                _articleLibraryRepository.Save();

                var articleToReturn = _mapper.Map <ArticleDto>(articleToAdd);

                return(CreatedAtRoute("GetArticleForUser",
                                      new { userId, articleId = articleToReturn.Id },
                                      articleToReturn));
            }

            //map the entity to a CourseForUpdateDto
            // apply the upadted filed values to that dto
            // map the CourseForUpdateDto back to an entity
            _mapper.Map(article, articleForUserFromRepo);

            _articleLibraryRepository.UpdateArticle(articleForUserFromRepo);
            _articleLibraryRepository.Save();
            return(NoContent());
        }
Example #3
0
        public async Task UpdateArticle(ArticleForUpdateDto article)
        {
            var articleFromDb = GetArticlesWithIncludes().FirstOrDefault(art => art.Id == article.Id);
            await _images.SaveAsync();

            _mapper.Map(article, articleFromDb);
            _articleRepository.Update(articleFromDb);
            await _articleRepository.SaveAsync();
        }
        public IActionResult UpdateArticleForAuthor(Guid authorId, Guid id,
                                                    [FromBody] ArticleForUpdateDto article)
        {
            if (article == null)
            {
                return(BadRequest());
            }

            if (article.Description == article.Title)
            {
                ModelState.AddModelError(nameof(ArticleForUpdateDto),
                                         "The provided description should be different from the title.");
            }

            if (!ModelState.IsValid)
            {
                return(new UnprocessableEntityObjectResult(ModelState));
            }


            if (!_libraryRepository.AuthorExists(authorId))
            {
                return(NotFound());
            }

            var articleForAuthorFromRepo = _libraryRepository.GetArticleForAuthor(authorId, id);

            if (articleForAuthorFromRepo == null)
            {
                var articleToAdd = Mapper.Map <Article>(article);
                articleToAdd.Id = id;

                _libraryRepository.AddArticleForAuthor(authorId, articleToAdd);

                if (!_libraryRepository.Save())
                {
                    throw new Exception($"Upserting article {id} for author {authorId} failed on save.");
                }

                var articleToReturn = Mapper.Map <ArticleDto>(articleToAdd);

                return(CreatedAtRoute("GetArticleForAuthor",
                                      new { authorId = authorId, id = articleToReturn.Id },
                                      articleToReturn));
            }

            Mapper.Map(article, articleForAuthorFromRepo);

            _libraryRepository.UpdateArticleForAuthor(articleForAuthorFromRepo);

            if (!_libraryRepository.Save())
            {
                throw new Exception($"Updating article {id} for author {authorId} failed on save.");
            }

            return(NoContent());
        }
        // strictly a command should not return anything, except when not long running
        // https://stackoverflow.com/questions/43433318/cqrs-command-return-values
        // https://lostechies.com/jimmybogard/2013/12/19/put-your-controllers-on-a-diet-posts-and-commands/
        public async Task <ActionResult> UpdateArticle(ArticleForUpdateDto articleUpdateDto)
        {
            var updated = await _updateCommand.Execute(articleUpdateDto);

            if (updated)
            {
                return(NoContent());
            }

            return(BadRequest("Failed to update article"));
        }
        // TODO: restful: also specify id in parm list?
        public async Task <ActionResult> UpdateArticle(ArticleForUpdateDto articleUpdateDto)
        {
            await _updateCommand.Execute(articleUpdateDto);

            return(NoContent());

            // TODO: handle errors

            //if (await _unitOfWork.Commit()) return NoContent();

            //return BadRequest("Failed to update article");
        }
Example #7
0
 public async Task <ActionResult> Update(ArticleForUpdateDto article)
 {
     try
     {
         await _articleService.UpdateArticle(article);
     }
     catch (Exception ex)
     {
         return(BadRequest(ex.Message));
     }
     return(NoContent());
 }
Example #8
0
        public IActionResult PartiallyUpdateArticleForUser(Guid userId,
                                                           Guid articleId,
                                                           Guid tagId,
                                                           JsonPatchDocument <ArticleForUpdateDto> patchDocument)
        {
            if (!_articleLibraryRepository.UserExists((userId)))
            {
                return(NotFound());
            }

            var articleForUserFromRepo = _articleLibraryRepository.GetArticle(userId, articleId);

            if (articleForUserFromRepo == null)
            {
                var articleDto = new ArticleForUpdateDto();
                patchDocument.ApplyTo(articleDto, ModelState);

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

                var articleToAdd = _mapper.Map <Article>(articleDto);
                articleToAdd.Id = articleId;

                _articleLibraryRepository.AddArticle(userId, articleToAdd, tagId);
                _articleLibraryRepository.Save();

                var articleToReturn = _mapper.Map <ArticleDto>(articleToAdd);

                return(CreatedAtRoute("GetArticleForUser",
                                      new { userId, articleId = articleToReturn.Id },
                                      articleToReturn));
            }

            var articleToPatch = _mapper.Map <ArticleForUpdateDto>(articleForUserFromRepo);

            // add validation
            patchDocument.ApplyTo(articleToPatch, ModelState);

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

            _mapper.Map(articleToPatch, articleForUserFromRepo);

            _articleLibraryRepository.UpdateArticle(articleForUserFromRepo);

            _articleLibraryRepository.Save();

            return(NoContent());
        }
        public IResult UpdateArticle(ArticleForUpdateDto articleForUpdateDto)
        {
            //TO DO: Implement transaction

            Article article = _articleRepository.GetIncluding(x => x.Id == articleForUpdateDto.Id,
                                                              x => x.Pictures);
            var picturesDict = article.Pictures.ToDictionary(x => x.PublicId);

            var toBeDeletedPictures = _mapper.Map <List <PictureForDeleteDto> >(picturesDict.Where(x => !articleForUpdateDto.Pictures
                                                                                                   .Select(y => y.PublicId)
                                                                                                   .Contains(x.Key))
                                                                                .Select(x => x.Value));

            foreach (var toBeDeletedPicture in toBeDeletedPictures)
            {
                _pictureService.DeletePicture(toBeDeletedPicture);
            }

            var picturesToBeCreated = articleForUpdateDto.Pictures.Where(x => x.PublicId == null).Select(x => new PictureForCreationDto
            {
                ArticleId = article.Id,
                IsMain    = x.IsMain,
                File      = x.File
            }).ToList();

            var articleWithTranslationToBeUpdated = _mapper.Map <ArticleTranslation>(articleForUpdateDto);

            if (picturesToBeCreated.Count > 0)
            {
                bool skipMainPicture = picturesToBeCreated.Any(x => x.IsMain) ? false : true;
                var  result          = _pictureService.InsertPicturesForArticle(picturesToBeCreated, skipMainPicture);

                if (result.Success)
                {
                    var imgRegex = new Regex("<img src=\"(?<url>(data:(?<type>.+?);base64),(?<data>[^\"]+))\"");
                    foreach (var picture in result.Data.Where(x => !x.IsMain))
                    {
                        articleWithTranslationToBeUpdated.ContentMain = imgRegex.Replace(articleWithTranslationToBeUpdated.ContentMain,
                                                                                         m => $"<img src=\"{picture.Url}\"", 1);
                    }

                    _articleTranslationRepository.Update(articleWithTranslationToBeUpdated);
                    return(new SuccessResult(string.Format(Messages.SuccessfulUpdate, nameof(Article))));
                }
                else
                {
                    return(new ErrorResult($"Picture couldn't be inserted Error Message {result.Message}"));
                }
            }
            _articleTranslationRepository.Update(articleWithTranslationToBeUpdated);
            return(new SuccessResult(string.Format(Messages.SuccessfulUpdate, nameof(Article))));
        }
Example #10
0
        public async Task <bool> Execute(ArticleForUpdateDto articleForUpdate)
        {
            Article article = await _unitOfWork.ArticleRepository.GetArticleByIdAsync(articleForUpdate.Id);

            _mapper.Map(articleForUpdate, article);

            _unitOfWork.ArticleRepository.Update(article);

            if (await _unitOfWork.Commit())
            {
                return(true);
            }

            return(false);
        }
Example #11
0
        public async Task GetArticle_WithNonExistingId_ReturnsTheCorrectArticleDto()
        {
            // arrange
            var articleForUpdateDto = new ArticleForUpdateDto()
            {
                Id = 5, Name1 = "Article01 Updated"
            };

            // act
            var result = await _articlesController.UpdateArticle(articleForUpdateDto);

            // assert
            _articleRepositoryMock.Verify(m => m.Update(It.IsAny <Article>()), Times.Once);
            Assert.That(result, Is.Not.Null);
            Assert.That(result.GetType(), Is.EqualTo(typeof(BadRequestObjectResult)));
            Assert.That(((BadRequestObjectResult)result).StatusCode, Is.EqualTo(400));
            Assert.That(((BadRequestObjectResult)result).Value, Is.EqualTo("Failed to update article"));
        }
Example #12
0
        public IActionResult UpdateArticleForProduct(Guid productId, Guid id,
                                                     [FromBody] ArticleForUpdateDto article)
        {
            if (article == null)
            {
                return(BadRequest());
            }

            if (!_libraryRepository.ProductExists(productId))
            {
                return(NotFound());
            }

            var articleForProductRepo = _libraryRepository.GetArticleForProduct(productId, id);

            if (articleForProductRepo == null)
            {
                var articleToAdd = Mapper.Map <Article>(article);
                articleToAdd.Id = id;
                _libraryRepository.AddArticleForProduct(productId, articleToAdd);

                if (!_libraryRepository.Save())
                {
                    throw new Exception("Upserting failed on save");
                }

                var articleToReturn = Mapper.Map <ArticleDto>(articleToAdd);

                return(CreatedAtRoute("GetArticleForProduct",
                                      new { productId = productId, id = articleToReturn.Id },
                                      articleToReturn));
            }

            Mapper.Map(article, articleForProductRepo);

            _libraryRepository.UpdateArticleForProduct(articleForProductRepo);

            if (!_libraryRepository.Save())
            {
                throw new Exception("$Updating failed on save");
            }

            return(NoContent());
        }
        public async Task UpdateArticle_WithFailingCommit_ReturnsStatusBadRequest()
        {
            // arrange
            _articleRepository.Setup(ar => ar.GetArticleByIdAsync(1)).Returns(Task.FromResult(_testArticles.First()));
            _updateCommandMock.Setup(m => m.Execute(It.IsAny <ArticleForUpdateDto>())).Returns(Task.FromResult(false));
            var articleForUpdateDto = new ArticleForUpdateDto()
            {
                Id = 5, Name1 = "1st article Updated"
            };

            // act
            var result = await _articlesController.UpdateArticle(articleForUpdateDto);

            // assert
            _updateCommandMock.Verify(m => m.Execute(It.IsAny <ArticleForUpdateDto>()), Times.Once);
            Assert.That(result, Is.Not.Null);
            Assert.That(result.GetType(), Is.EqualTo(typeof(BadRequestObjectResult)));
            Assert.That(((BadRequestObjectResult)result).StatusCode, Is.EqualTo(400));
            Assert.That(((BadRequestObjectResult)result).Value, Is.EqualTo("Failed to update article"));
        }
        public async Task UpdateArticle_WithSucceedingCommit_ReturnsStatusCodeNoContent()
        {
            // arrange
            _articleRepository.Setup(ar => ar.GetArticleByIdAsync(1)).Returns(Task.FromResult(_testArticles.First()));
            _unitOfWork.Setup(uow => uow.Commit()).Returns(Task.FromResult(true));
            _updateCommandMock.Setup(m => m.Execute(It.IsAny <ArticleForUpdateDto>())).Returns(Task.FromResult(true));
            var articleForUpdateDto = new ArticleForUpdateDto()
            {
                Id = 1, Name1 = "1st article Updated"
            };

            // act
            var result = await _articlesController.UpdateArticle(articleForUpdateDto);

            // assert
            _updateCommandMock.Verify(m => m.Execute(It.IsAny <ArticleForUpdateDto>()), Times.Once);
            Assert.That(result, Is.Not.Null);
            Assert.That(result.GetType(), Is.EqualTo(typeof(NoContentResult)));
            Assert.That(((NoContentResult)result).StatusCode, Is.EqualTo(204));
        }
        public async Task Update_ValidObject_ObjectIsUpdated()
        {
            //Arrange
            var articleForUpdate = new ArticleForUpdateDto()
            {
                Id                = 1,
                Name1             = "1st article Updated",
                SupplierId        = "sup id",
                SupplierReference = "sup ref",
                PurchasePrice     = 99.99M
            };
            var updateArticleCommand = new UpdateArticleCommand(_unitOfWork, _writeMapper);

            //Act
            var result = await updateArticleCommand.Execute(articleForUpdate);

            //Assert
            Assert.That(result, Is.EqualTo(true));
            Assert.That(TestContext.Articles.First().Name1, Is.EqualTo(articleForUpdate.Name1));
        }
Example #16
0
        public async Task UpdateArticle_Success()
        {
            var articleImages = new HashSet <ArticleImage>()
            {
                new ArticleImage()
                {
                    Id      = 1,
                    Article = new Article()
                    {
                        Id = 1
                    },
                    ArticleId = 1
                },
                new ArticleImage()
                {
                    Id      = 2,
                    Article = new Article()
                    {
                        Id = 2
                    },
                    ArticleId = 2
                }
            };
            var articleDto = new ArticleForUpdateDto()
            {
                Id = 1, Content = "test"
            };
            var article = GetTestArticles().AsQueryable().FirstOrDefault(art => art.Id == articleDto.Id);

            _articleRepositoryMock.Setup(x => x.Update(article));
            _articleRepositoryMock.Setup(x => x.SaveAsync());

            await _service.UpdateArticle(articleDto);

            _articleRepositoryMock.Verify(x => x.Update(It.IsAny <Article>()), Times.Once());
            _articleRepositoryMock.Verify(x => x.SaveAsync(), Times.Once());
        }
        public async Task Execute(ArticleForUpdateDto articleForUpdate)
        {
            Domain.Model.Entities.Articles.Article article =
                await _unitOfWork.ArticleRepository.GetArticleByIdAsync(articleForUpdate.Id);

            // TODO mapping via DI !!
            //mapper.Map(articleForUpdate, article);

            article.SupplierId        = articleForUpdate.SupplierId;
            article.SupplierReference = articleForUpdate.SupplierReference;
            article.Name1             = articleForUpdate.Name1;
            article.PurchasePrice     = articleForUpdate.PurchasePrice;

            _unitOfWork.ArticleRepository.Update(article);

            await _unitOfWork.Commit();

            // evt. notifications

            // TODO: handle errors ?
            // if (await _unitOfWork.Commit()) return NoContent();

            // return BadRequest("Failed to update article");
        }