public ActionResult <ReadArticleDto> CreateArticle(CreateArticleDto createArticleDto) { List <Hashtag> hashtagList = new List <Hashtag>(); Article articleModel = new Article { Title = createArticleDto.Title, Body = createArticleDto.Body, CreatedAt = DateTime.Now, UpdatedAt = DateTime.Now, AuthorId = createArticleDto.AuthorId, AuthorUsername = createArticleDto.AuthorUsername, }; _repository.CreateArticle(articleModel); _repository.SaveChanges(); foreach (var item in createArticleDto.Hashtags) { hashtagList.Add(new Hashtag { Description = item, ArticleId = articleModel.Id }); } _repository.AddHashtagsForNewArticle(hashtagList); _repository.SaveChanges(); var readArticleDto = _mapper.Map <ReadArticleDto>(articleModel); return(CreatedAtRoute(nameof(GetArticleById), new { Id = readArticleDto.Id }, readArticleDto)); }
public void Execute(CreateArticleDto request) { _validator.ValidateAndThrow(request); var article = new Articles { Subject = request.Subject, Description = request.Description, Text = request.Text, UserId = _actor.Id }; //ArticlesCategories foreach (var item in request.ArticleCategories) { article.ArticleCategories.Add(new ArticleCategories { ArticleId = article.Id, CategoryId = item.CategoryId }); } _context.Articles.Add(article); _context.SaveChanges(); }
public async Task <IActionResult> CreateArticle(CreateArticleDto request) { var command = new CreateArticleCommand(request.Subject, request.Body, Guid.NewGuid()); var isSuccess = await _mediator.Send(command); if (isSuccess) { return(Created(string.Empty, isSuccess)); } return(BadRequest()); }
//public SystemArticleLogic(IRepository<SystemArticle, Guid> repository, // ISystemArticleRepository systemArticleRepository) : base(repository) //{ // this._systemArticleRepository = systemArticleRepository; //} #endregion #region 方法 /// <summary> /// 保存文章 /// </summary> /// <param name="article"></param> /// <returns></returns> public Task <OperateStatus> SaveArticle(CreateArticleDto article) { return(null); //if (article.ArticleId.IsEmptyGuid()) //{ // article.ArticleId = CombUtil.NewComb(); // return InsertAsync(article); //} //else { // return UpdateAsync(article); //} }
public async Task <IActionResult> Write(ArticleWriteInputModel input) { var dto = new CreateArticleDto { Title = input.Title, Text = input.Text, FirstName = input.FirstName, LastName = input.LastName, Resume = input.Resume, UserId = await this.usersService.GetIdAsync(this.User.Identity.Name), }; await this.articlesService.CreateArticleAsync(dto, input.Files, Path.Combine(this.webHostEnvironment.WebRootPath, "images", "authors")); return(this.Redirect("/")); }
public IActionResult Post([FromForm] CreateArticleDto dto, [FromServices] ICreateArticleCommand command) { 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; executor.ExecuteCommand(command, dto); return(StatusCode(StatusCodes.Status201Created)); }
public async Task <IActionResult> SubmitArticle([FromBody] CreateArticleDto createArticleDto) { var articleEntity = //Map create article dto to new article entity. Mapper.Map <Article>(createArticleDto); articleEntity.ArticlePath = //save file to disk and add path to entity. await _fileRepository .SaveArticle(createArticleDto.ArticleFile, createArticleDto.UserName); articleEntity.Status = Status.Pending; //Set status to pending _dbContext.Articles.Add(articleEntity); //Add article to database if (_dbContext.SaveChanges() >= 0) //save and redirect to index if successful { return(RedirectToAction(nameof(Index))); } throw new Exception("Failed to save article"); //throw new exception on failure. }
public async Task CreateArticle_GivenValidData_ShouldReturnOK() { var subject = "Article Subject"; var body = "Article Body"; _mediator.Send(Arg.Any <CreateArticleCommand>()).Returns(true); var controller = new ArticlesController(_mediator); var request = new CreateArticleDto { Subject = subject, Body = body }; IActionResult result = await controller.CreateArticle(request); Assert.IsAssignableFrom <IActionResult>(result); Assert.IsType <OkResult>(result); }
public async Task <ActionResult> CreateArticle([FromBody] CreateArticleDto dto) { var newArticle = new Article() { Title = dto.Title, Description = dto.Description, HeroImage = _mapper.Map <Image>(dto.HeroImage) }; for (int partCount = 0; partCount < dto.Parts.Count; partCount++) { var newPart = new ArticlePart() { PartNumber = partCount + 1, Title = dto.Parts[partCount].Title, Description = dto.Parts[partCount].Description }; for (int stepCount = 0; stepCount < dto.Parts[partCount].Steps.Count; stepCount++) { var newStep = new ArticleStep() { StepNumber = stepCount + 1, Title = dto.Parts[partCount].Steps[stepCount].Title, Description = dto.Parts[partCount].Steps[stepCount].Description }; newPart.Steps.Add(newStep); } newArticle.Parts.Add(newPart); } var currentUser = await GetCurrentUser(); newArticle.Users.Add(currentUser); await _appDbContext.Articles.AddAsync(newArticle); await _appDbContext.SaveChangesAsync(); return(Ok()); }
public async Task <IActionResult> OnPostAsync([FromForm] CreateArticleDto articleDto) { if (!ModelState.IsValid) { return(Page()); } var username = _userManager.GetUserName(User); var path = await _articleFileRepository.SaveArticle(articleDto.Article, username); var articleEntity = Mapper.Map <Article>(articleDto); articleEntity.AuthorId = _userManager.GetUserId(User); articleEntity.ArticleFile = path; _articleRepository.Create(articleEntity); if (!_articleRepository.Save()) { throw new Exception("Failed to create article database entry."); } return(RedirectToPage("/Articles/Article", new { id = articleEntity.Id })); }
public async Task CreateArticleAsync(CreateArticleDto dto, IFormFile avatar, string imageFolder) { if (!this.articlesRepository.All().Any(x => x.Title == dto.Title)) { var author = this.authorsRepository.All().Where(x => x.FirstName == dto.FirstName && x.LastName == dto.LastName).FirstOrDefault(); if (author is null) { author = new Author { FirstName = dto.FirstName, LastName = dto.LastName, Resume = dto.Resume, }; author.Images.Add(new Image { AddedByEmployeeId = dto.UserId, Name = avatar.FileName, Extension = this.ChangeToContentType(Path.GetExtension(avatar.FileName).Replace(".", string.Empty).Trim()), }); await this.UploadImagesToDirectory(imageFolder, avatar); await this.authorsRepository.AddAsync(author); await this.authorsRepository.SaveChangesAsync(); } var article = new Article { Title = dto.Title, Text = dto.Text, AuthorId = author.Id, }; await this.articlesRepository.AddAsync(article); await this.articlesRepository.SaveChangesAsync(); } }
public async Task <IActionResult> CreateArticle([FromBody] CreateArticleDto createArticleDto) { //Check ModelState if (!ModelState.IsValid) { return(BadRequest(ModelState)); } //Check if model bind failed. if (createArticleDto == null) { return(BadRequest()); } //Map to entity var articleEntity = Mapper.Map <Article>(createArticleDto); //Save file and add path to articleEntity articleEntity.ArticlePath = await _fileRepository .SaveArticle(createArticleDto.ArticleFile, createArticleDto.UserName); //Confirm file was saved. if (articleEntity.ArticlePath == null) { return(BadRequest()); } //Add articleEntity to database and save database. _dbContext.Articles.Add(articleEntity); if (!(await _dbContext.SaveChangesAsync() >= 0)) { throw new Exception("Failed to save Article DB Entry."); } //Convert entity to GetArticleDto var articleToReturn = Mapper.Map <GetArticleDto>(articleEntity); //Redirect to GetArticle action return(CreatedAtRoute("GetArticle", new { articleId = articleEntity.Id }, articleToReturn)); }
public async Task <ActionResult> UpdateArticle([FromRoute] string articleId, [FromBody] CreateArticleDto dto) { var article = await _appDbContext.Articles.FirstOrDefaultAsync(i => i.Id == Guid.Parse(articleId)); var currentUser = await GetCurrentUser(); if (!article.Users.Contains(currentUser)) { article.Users.Add(currentUser); } var newHistory = new ArticleHistory() { Version = article.Histories.Count + 1, TimeStamp = DateTime.Now, Title = article.Title, Description = article.Description, HeroImage = article.HeroImage, Parts = article.Parts, Issues = article.Issues, Ratings = article.Ratings, Contributors = article.Users }; article.Histories.Add(newHistory); article.Title = dto.Title; article.Description = dto.Description; article.HeroImage = _mapper.Map <Image>(dto.HeroImage); article.Parts = _mapper.Map <List <ArticlePart> >(dto.Parts); await _appDbContext.SaveChangesAsync(); return(Ok()); }
public void Post([FromBody] CreateArticleDto dto, [FromServices] ICreateArticleCommand command) { executor.ExecuteCommand(command, dto); }
public CreateArticleRequest(CreateArticleDto articleDto) =>
public async Task <JsonResult> SaveArticle(CreateArticleDto article) { return(Json(await _systemArticleLogic.SaveArticle(article))); }
public ActionResult <ArticleDto> CreateArticle(Guid personId, Guid projectId, Guid topicId, [FromBody] CreateArticleDto 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 = _mapper.Map <Article>(dto); article.TopicId = topicId; _db.Article.Create(article); _db.Save(); var insertedArticle = _db.Article .FindByCondition(x => x.Id == article.Id) .Select(x => new Article { Id = x.Id, TopicId = x.TopicId, Title = x.Title, Content = x.Content.Substring(0, 200), CreatedTime = x.CreatedTime, LastUpdatedTime = x.LastUpdatedTime, }) .SingleOrDefault(); return(Ok(_mapper.Map <ArticleDto>(insertedArticle))); } catch (Exception e) { _logger.LogError($"ERROR in CreateArticle: {e.Message}"); return(StatusCode(500, "Internal server error")); } }