public async Task GivenValidRequest_WhenTheUserDidNotCreateTheArticle_ThrowsConduitApiExceptionForBadRequest()
        {
            // Arrange
            var stubArticleDto = new UpdateArticleDto
            {
                Body        = "This isn't my article!",
                Description = "Or is it?",
                Title       = "I'm a hacker trying to hack hacky articles about hacking."
            };

            var updateArticleCommand = new UpdateArticleCommand
            {
                Slug    = "how-to-train-your-dragon",
                Article = stubArticleDto
            };

            // Act
            var request = new UpdateArticleCommandHandler(_logger, Context, CurrentUserContext, Mapper, MachineDateTime);

            // Assert
            await Should.ThrowAsync <ConduitApiException>(async() =>
            {
                await request.Handle(updateArticleCommand, CancellationToken.None);
            });
        }
        public async Task GivenValidRequest_WhenASubsetOfPropertiesIsSent_ReturnsUpdatedArticleResponseWithOriginalPropertiesUnchanged()
        {
            // Arrange, retrieve the original article information
            var stubArticleDto = new UpdateArticleDto
            {
                Title = "I'm a hacker trying to hack hacky articles about hacking."
            };

            var updateArticleCommand = new UpdateArticleCommand
            {
                Slug    = "why-beer-is-gods-gift-to-the-world",
                Article = stubArticleDto
            };

            // Act
            var request = new UpdateArticleCommandHandler(_logger, Context, CurrentUserContext, Mapper, MachineDateTime);
            var result  = await request.Handle(updateArticleCommand, CancellationToken.None);

            // Assert
            var updatedArticle = Context.Articles.FirstOrDefault(a =>
                                                                 string.Equals(a.Slug, stubArticleDto.Title.ToSlug(), StringComparison.OrdinalIgnoreCase));

            updatedArticle.ShouldNotBeNull();
            result.ShouldNotBeNull();
            result.ShouldBeOfType <ArticleViewModel>();
            result.Article.Body.ShouldBe(updatedArticle.Body);
            result.Article.Description.ShouldBe(updatedArticle.Description);
            result.Article.Title.ShouldBe(stubArticleDto.Title);
            result.Article.TagList.ShouldContain("beer");

            // Validate the article in the DB context
            updatedArticle.Body.ShouldBe(updatedArticle.Body);
            updatedArticle.Description.ShouldBe(updatedArticle.Description);
            updatedArticle.Title.ShouldBe(stubArticleDto.Title);
        }
        public async Task GivenValidRequest_WhenTheArticleSlugIsNotFound_ThrowsConduitApiExceptionForNotFound()
        {
            // Arrange
            var stubArticleDto = new UpdateArticleDto
            {
                Body        = "I don't exist",
                Description = "Or do I?",
                Title       = "What is Life? 42."
            };

            var updateArticleCommand = new UpdateArticleCommand
            {
                Slug    = "this-article-does-not-exist",
                Article = stubArticleDto
            };

            // Act
            var request = new UpdateArticleCommandHandler(_logger, Context, CurrentUserContext, Mapper, MachineDateTime);

            // Assert
            await Should.ThrowAsync <ConduitApiException>(async() =>
            {
                await request.Handle(updateArticleCommand, CancellationToken.None);
            });
        }
Example #4
0
        public IResult UpdateArticle(UpdateArticleDto updateArticleDto)
        {
            var user    = _authService.GetAuthenticatedUser().Result.Data;
            var article = _uow.Articles.Get(x => x.Id == updateArticleDto.ArticleId);

            //LOGIN KULLANICI VAR MI
            //MAKALE MEVCUT MU
            //MAKALE KATEGORİSİ MEVCUT MU
            //MAKALE MEVCUT KULLANICIYA MI AİT
            var errorResult = BusinessRules.Run(CheckAuthenticatedUserExist(), IsArticleExist(updateArticleDto.ArticleId),
                                                CheckArticleCategoryExist(updateArticleDto.ArticleCategoryId),
                                                IsArticleBelongToUser(user.Id, article.Id)  //(PATLAR)
                                                );

            if (errorResult != null)
            {
                return(errorResult);
            }

            /*BURAYA KADAR OLAN KISIM İŞ KURALLARI. BİR İŞ MOTORU YAZILABİLİR
             * -------------------------------------------------------------------- */
            article.Title             = updateArticleDto.Title;
            article.Content           = updateArticleDto.Content;
            article.ArticleCategoryId = updateArticleDto.ArticleCategoryId;

            this._uow.Articles.Update(article);
            this._uow.Commit();

            return(new SuccessResult(Message.ArticleUpdated));
        }
Example #5
0
        public async Task <IActionResult> Update(int id, [FromBody] UpdateArticleDto dto)
        {
            var model = this.mapper.Map <UpdateArticleModel>(dto);

            model.Id = id;

            var created = await this.articleService.UpdateAsync <ArticleDto>(model);

            return(this.Ok(created));
        }
Example #6
0
        public async Task <bool> UpdateArticle(UpdateArticleDto updateArticleDto)
        {
            int articleId = updateArticleDto.ArticleId;

            //从数据库查询该Id的文章
            var article = await _articleRepository.FirstOrDefaultAsync(a => a.Id == articleId);

            if (article == null)
            {
                //文章不存在
                _logger.LogError("文章不存在,更新失败");
                return(false);
            }

            //获取文章原本的完整的路径
            string completePath = article.ArticleUrl;
            //获取文章新的内容
            string newArticleContent = updateArticleDto.ArticleContent;
            //切割文章内容,去掉首字符串
            string articleContentNormal = SplitString.SplitStringWithStart(newArticleContent);

            //将新的内容更新至文件
            var result = await FileOperate.UpdateArticleContentAsync(completePath, articleContentNormal, _logger);

            if (result == false)
            {
                //更新硬盘文档失败
                _logger.LogError("从硬盘更新文章失败,更新失败");
                return(false);
            }

            //硬盘上的文件更新成功,更新数据库
            article.ArticleName          = updateArticleDto.ArticleName;
            article.ArticleTags          = updateArticleDto.ArticleTags;
            article.TypeId               = updateArticleDto.TypeId;
            article.LastModificationTime = updateArticleDto.LastModificationTime;
            article.Introduce            = updateArticleDto.Introduce;
            article.IsRecommend          = updateArticleDto.IsRecommend;

            //更新数据库
            Article updateMysqlResult = await _articleRepository.UpdateAsync(article);

            if (updateMysqlResult == null)
            {
                //更新数据库失败,可以尝试重试机制
                _logger.LogError("数据库更新失败,更新失败");
                return(false);
            }
            //更新成功,更新缓存
            //将该文章Id和RedisArticle组合,作为Redis键名
            string redisArticleKey = PostConsts.ArticleBaseKey + articleId;
            await _cacheManager.GetCache(PostConsts.RedisForArticleStore).SetAsync(redisArticleKey, updateMysqlResult);

            return(true);
        }
Example #7
0
        public IActionResult UpdateArticle(UpdateArticleDto updateArticleDto)
        {
            var result = _articleService.UpdateArticle(updateArticleDto);

            if (result.ResultType == ResultType.UnAuthorized)
            {
                return(Unauthorized());
            }

            if (result.ResultType == ResultType.Success)
            {
                return(Ok(result.Message));
            }

            return(BadRequest(result.Message));
        }
Example #8
0
        public async Task <IActionResult> UpdateArticle(UpdateArticleDto update)
        {
            if (!await _authService.IsPermitted(User, update.ArticleUserSettings.EnvironmentId))
            {
                return(Unauthorized());
            }

            Article article = await _repo.GetArticle(update.Article.Id);

            ArticleUserSetting articleUserSettings = await _repo.GetArticleUserSettings(update.Article.Id, update.ArticleUserSettings.EnvironmentId);

            _mapper.Map(update.Article, article);
            _mapper.Map(update.ArticleUserSettings, articleUserSettings);

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

            throw new Exception("Failed to update article");
        }
        /// <summary>
        /// 更改文章信息
        /// </summary>
        /// <param name="updateArticleDto">更改文章模型</param>
        /// <returns></returns>
        public async Task <ShowArticleDto> UpdateArticleAsync(UpdateArticleDto updateArticleDto)
        {
            ArticleType articleType = await _articleTypeRepository.GetByIdAsync(updateArticleDto.ArticleTypeId);

            Guard.Against.NullArticleType(updateArticleDto.ArticleTypeId, articleType);

            Article article = await _articleRepository.GetByIdAsync(updateArticleDto.Id);

            Guard.Against.NullArticle(updateArticleDto.Id, article);

            article.Update(updateArticleDto.Title, updateArticleDto.SummaryInfo, updateArticleDto.Icon, updateArticleDto.Content, updateArticleDto.Status, articleType);

            if (await _articleRepository.ReplaceAsync(article))
            {
                //返回展示模型
                var showArticle = _mapper.Map <ShowArticleDto>(article);
                return(showArticle);
            }
            _logger.LogError($"文章更新失败。失败数据:{JsonConvert.SerializeObject(article)}");
            return(null);
        }
Example #10
0
        public IActionResult Put(int id, [FromForm] UpdateArticleDto dto, [FromServices] IUpdateArticleCommand command)
        {
            if (dto.ImageObj != null)
            {
                var guid      = Guid.NewGuid();
                var extension = Path.GetExtension(dto.ImageObj.FileName);

                var newFileName = guid + extension;

                var path = Path.Combine("wwwroot", "images", newFileName);

                using (var fileStream = new FileStream(path, FileMode.Create))
                {
                    dto.ImageObj.CopyTo(fileStream);
                }

                dto.Picture = newFileName;
            }

            dto.Id = id;
            executor.ExecuteCommand(command, dto);
            return(NoContent());
        }
 public UpdateArticleAction(UpdateArticleDto updatedArticle) =>
        public async Task <ActionResult <ResponseResult <ShowArticleDto> > > UpdateArticleAsync([FromBody] UpdateArticleDto updateArticleDto)
        {
            try
            {
                var deleteArtcle = await _articleService.UpdateArticleAsync(updateArticleDto);

                return(new ResponseResult <ShowArticleDto>(1, "更改成功", deleteArtcle));
            }
            catch (Exception ex)
            {
                _logger.LogCritical(ex, ex.Message);
                return(new ResponseResult <ShowArticleDto>(0, ex.Message, null));
            }
        }
Example #13
0
        public ActionResult <ArticleDto> UpdateArticle(Guid personId, Guid projectId, Guid topicId, Guid articleId, [FromBody] UpdateArticleDto dto)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return(BadRequest());
                }
                if (!_db.Person.BelongsToUser(personId, HttpContext))
                {
                    return(Forbid());
                }
                if (_db.Participation.GetRole(personId, projectId)?.KnowledgeBaseWrite != true)
                {
                    return(Forbid());
                }

                var topic = _db.Topic.FindByCondition(x => x.Id == topicId && x.ProjectId == projectId).SingleOrDefault();
                if (topic == null)
                {
                    return(BadRequest());
                }

                var article = _db.Article.FindByCondition(x => x.Id == articleId && x.TopicId == topicId).SingleOrDefault();
                if (article == null)
                {
                    return(BadRequest());
                }

                article.Title   = dto.Title;
                article.Content = dto.Content;

                _db.Article.Update(article);
                _db.Save();

                return(Ok(_mapper.Map <ArticleDto>(article)));
            }
            catch (Exception e)
            {
                _logger.LogError($"ERROR in UpdateArticle: {e.Message}");
                return(StatusCode(500, "Internal server error"));
            }
        }
 public UpdateArticleRequest(UpdateArticleDto request) =>