public ActionResult Edit(int id, CreateNewsDto dto) { if (!ModelState.IsValid) { TempData["greska"] = "Doslo je do greske pri unosu"; RedirectToAction("Edit"); } try { dto.NewsId = id; var pathSave = ""; if (dto.Image != null) { var newFileName = Guid.NewGuid().ToString() + "_" + dto.Image.FileName; var webPath = _hostingEnvironment.WebRootPath; var uploads = Path.Combine("", webPath + @"\uploads\" + newFileName); pathSave = @"/uploads/" + newFileName; dto.Image.CopyTo(new FileStream(uploads, FileMode.Create)); } dto.Path = pathSave; _editNewsCommand.Execute(dto); return(RedirectToAction(nameof(Index))); } catch (EntityNotFoundException ex) { TempData["error"] = ex.Message; ViewBag.Categories = _getCategoriesCommand.Execute(new CategorySearch { }); return(View()); } }
public async Task <IActionResult> PostNews([FromBody] CreateNewsDto createNewsDto) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var addedTagsDto = tagService.AddTags(createNewsDto.Tags).Result; createNewsDto.Tags = addedTagsDto; var news = mapper.Map <CreateNewsDto, News>(createNewsDto); var newsTags = new List <NewsTag>(); foreach (var tagDto in addedTagsDto) { newsTags.Add(new NewsTag() { TagId = tagDto.Id }); } news.NewsTags = newsTags; news.VisitorCount = 0; news.CreatedAt = DateTime.Now; news.ModifiedAt = news.CreatedAt; news.ModifiedBy = news.UserId; context.News.Add(news); await context.SaveChangesAsync(); await elasticClient.IndexDocumentAsync(news); //return Ok(); return(CreatedAtAction("GetFullNews", new { id = news.Id })); }
public ActionResult Post([FromForm] CreateNewsDto createDto) { var ext = Path.GetExtension(createDto.Image.FileName); //.gif if (!FileUpload.AllowedExtensions.Contains(ext)) { return(UnprocessableEntity("Image extension is not allowed.")); } try { var newFileName = Guid.NewGuid().ToString() + "_" + createDto.Image.FileName; var filePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "uploads", newFileName); var pathSave = @"/uploads/" + newFileName; createDto.Image.CopyTo(new FileStream(filePath, FileMode.Create)); createDto.Path = pathSave; _addNewsCommand.Execute(createDto); return(Ok()); } catch (Exception) { return(StatusCode(500)); } }
public async Task <News> UpdateNews(int id, CreateNewsDto newsDto) { var news = await _dataContext.News.FindAsync(id); if (news == null) { throw new Exception("News not Found"); } news.Text = newsDto.Text; if (newsDto.Title != null) { news.Title = newsDto.Title; } if (newsDto.NewsType != 0) { news.NewsType = newsDto.NewsType; } if (newsDto.Text != null) { news.Text = newsDto.Text; } news.UpdatedBy = UserRoles.Admin; _dataContext.News.Update(news); await _dataContext.SaveChangesAsync(); return(news); }
private void RemoveExistsRelastionship(CreateNewsDto request) { var foundNewsCategories = Context.NewsCategories.Where(x => x.NewsId == request.NewsId); Context.NewsCategories.RemoveRange(foundNewsCategories); Context.SaveChanges(); }
public async Task <GetNewsDto> CreateNewsAsync(CreateNewsDto createNewsDto, CancellationToken token = default) { var news = _mapper.Map <News>(createNewsDto); await _newsRepository.InsertAsync(news, token); _cacheClient?.RemoveKey("news"); return(_mapper.Map <GetNewsDto>(news)); }
public async Task <ActionResult <MainResponse <News> > > CreateNews(CreateNewsDto newsDto) { var createdNews = await _newsService.CreateNews(newsDto); return(new MainResponse <News> { Path = HttpContext.Request.Path, Message = "Successfully Created News", Data = createdNews }); }
public void Execute(CreateNewsDto request) { if (request.CategoryIds.Any(x => !Context.Categories.Any(y => y.Id == x))) { throw new EntityNotFoundException("Categories"); } var createNewNew = CreateNewNews(request); CreateNewNewsCategory(request, createNewNew); SavePicture(request, createNewNew); }
private void SavePicture(CreateNewsDto request, int newsId) { var pictureId = 0; var picture = new Picture { Path = request.Path, CreatedAt = DateTime.Now, NewsId = newsId }; Context.Pictures.Add(picture); Context.SaveChanges(); }
public int CreateNews(CreateNewsDto createUserDto) { var createdNews = new NewsEntity() { Title = createUserDto.Title, Description = createUserDto.Description, PathToImages = null, UserId = createUserDto.UserId }; _db.News.Add(createdNews); _db.SaveChanges(); return(createdNews.Id); }
public async Task <News> CreateNews(CreateNewsDto newsDto) { var news = new News { Text = newsDto.Text, Title = newsDto.Title, NewsType = newsDto.NewsType, CreatedBy = UserRoles.Admin }; _dataContext.News.Add(news); await _dataContext.SaveChangesAsync(); return(news); }
public void Execute(CreateNewsDto request) { var news = Context.News.Find(request.NewsId); if (news == null) { throw new EntityNotFoundException("News"); } if (request.CategoryIds.Any(x => !Context.Categories.Any(y => y.Id == x))) { throw new EntityNotFoundException("Categories"); } //if (!Context.Users.Any(x => x.Id == HttpContext.UserId)) //{ // throw new EntityNotFoundException("User"); //} var picture = new Picture { Path = request.Path, CreatedAt = DateTime.Now, NewsId = request.NewsId }; news.Heading = request.Heading; news.Content = request.Content; news.ModifiedAt = DateTime.Now; news.UserId = /*request.UserId*/ 1; Context.SaveChanges(); Context.Pictures.Add(picture); var foundNewsCategories = Context.NewsCategories.Where(x => x.NewsId == request.NewsId); Context.NewsCategories.RemoveRange(foundNewsCategories); Context.SaveChanges(); foreach (var cat in request.CategoryIds) { var newsCategories = new NewsCategories() { CategoryId = cat, NewsId = request.NewsId }; Context.NewsCategories.Add(newsCategories); Context.SaveChanges(); } }
private void CreateNewNewsCategory(CreateNewsDto request, int id) { request.NewsId = id; RemoveExistsRelastionship(request); foreach (var cat in request.CategoryIds) { var newsCategories = new NewsCategories() { CategoryId = cat, NewsId = request.NewsId }; Context.NewsCategories.Add(newsCategories); Context.SaveChanges(); } }
private int CreateNewNews(CreateNewsDto request) { int newsId; var news = new News { Heading = request.Heading, Content = request.Content, CreatedAt = DateTime.Now, UserId = /*request.UserId*/ 1 }; Context.News.Add(news); Context.SaveChanges(); newsId = news.Id; return(newsId); }
public IActionResult Put(int id, [FromBody] CreateNewsDto newsDto) { try { newsDto.NewsId = id; _editNewsCommand.Execute(newsDto); return(NoContent()); } catch (EntityNotFoundException) { return(Conflict("News with that name doesn't exist.")); } catch (Exception) { return(StatusCode(500, "An error has occured.")); } }
public ActionResult Create(CreateNewsDto dto) { if (!ModelState.IsValid) { TempData["greska"] = "Doslo je do greske pri unosu"; RedirectToAction("create"); } try { _addNewsCommand.Execute(dto); return(RedirectToAction(nameof(Index))); } catch { TempData["error"] = "Whoops! Something went wrong!"; ViewBag.Categories = _getCategoriesCommand.Execute(null); return(View()); } }
public async Task <ActionResult <MainResponse <News> > > UpdateNews(int id, CreateNewsDto newsDto) { News updatedNews; try { updatedNews = await _newsService.UpdateNews(id, newsDto); } catch (Exception e) { return(NotFound(new ApiException((int)HttpStatusCode.NotFound, e.Message))); } return(new MainResponse <News> { Path = HttpContext.Request.Path, Message = "Successfully Updated News", Data = updatedNews }); }
public async Task <ActionResult <NewsDto> > CreateNews(CreateNewsDto createNewsDto) { if (createNewsDto is null) { throw new ArgumentNullException(nameof(createNewsDto)); } var currentUserId = Guid.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value); try { var newsToReturn = await _newsService.Create(createNewsDto, currentUserId); return(CreatedAtAction(nameof(GetById), new { newsId = newsToReturn.Id }, newsToReturn)); } catch (UserIdMismatchException ex) { return(new JsonResult(new { ex.Message }) { StatusCode = StatusCodes.Status403Forbidden }); } }
public async Task <NewsDto> Create(CreateNewsDto createNewsDto, Guid userId) { if (createNewsDto is null) { throw new ArgumentNullException(nameof(createNewsDto)); } // Check if the establishment for which the news is going to be published is owned by the user var targetEstablishment = await _establishmentService.GetById(createNewsDto.EstablishmentId); if (targetEstablishment.UserId != userId) { throw new UserIdMismatchException("Cannot publish news for an establishment you don't own."); } var newsEntity = _mapper.Map <News>(createNewsDto); newsEntity.UserId = userId; _unitOfWork.NewsRepo.Add(newsEntity); await _unitOfWork.SaveAsync(); return(_mapper.Map <NewsDto>(newsEntity)); }
public ActionResult <IdDto> CreateNews([FromBody] CreateNewsDto createUserDto) { return(new OkObjectResult(new { Id = _newsService.CreateNews(createUserDto) })); }
public void Create(CreateNewsDto news) { var lastId = News.Any() ? News.OrderByDescending(n => n.Id).FirstOrDefault().Id : 0; News.Add(new News(lastId + 1, news.Title, news.Content)); }