public ActionResult Create() { BindTagItem(); var model = new NewsDto(); return(View(model)); }
public NewsDto Execute(int request) { var news = Context.News.AsQueryable(); var newsDb = news.Include(u => u.User) .Include(p => p.Pictures) .Include(nc => nc.NewsCategories) .ThenInclude(c => c.Categories).Where(x => x.Id == request).FirstOrDefault(); if (newsDb == null) { throw new EntityNotFoundException("News"); } var dto = new NewsDto { Id = newsDb.Id, Heading = newsDb.Heading, Content = newsDb.Content, Username = newsDb.User.Username, Path = !newsDb.Pictures.Any() ? "" : newsDb.Pictures.Where(x => x.NewsId == request).FirstOrDefault().Path, CreatedAt = newsDb.CreatedAt, NewsDetail = newsDb.NewsCategories.Select(nd => new NewsDetailsDto { CategoryName = nd.Categories.Name, CategoryId = nd.CategoryId }).ToList() }; return(dto); }
public bool PutNews(NewsDto news) { var mapped = AutoMapper.Mapper.Map <NewsDto, News>(news); using (var ctx = new Entities()) { var ns = ctx.News.Include(x => x.Images).FirstOrDefault(x => x.Id == news.Id); if (ns == null) { throw new KeyNotFoundException($"Non trovata entità con id {news.Id}"); } AutoMapper.Mapper.Map(mapped, ns); if (news.DeleteImage) { ns.Images = null; ns.ImageId = null; } if (news.Image != null) { ctx.Images.Remove(ns.Images); ctx.Images.Add(mapped.Images); ns.ImageId = mapped.Images.Id; } ns.LastUpdateDate = DateTime.Now; ctx.Entry(ns).State = EntityState.Modified; return(ctx.SaveChanges() > 0); } }
public async Task <int> Delete(NewsDto newsToDelete, Guid userId) { if (newsToDelete is null) { throw new ArgumentNullException(nameof(newsToDelete)); } // Check if the news to delete was published by the user if (newsToDelete.UserId != userId) { throw new UserIdMismatchException("Cannot delete news you didn't publish."); } _unitOfWork.NewsRepo.Remove(newsToDelete.Id); try { var result = await _unitOfWork.SaveAsync(); return(result); } catch (DbUpdateException) { throw new NewsServiceException($"Could not delete news (Id: {newsToDelete.Id})."); } }
public NewsDto CreateNews(NewsDto newsDto, int userId, int tenantId, MemoryStream file, string path) { if (GetNews(newsDto.NewsId, tenantId) != null) { return(EditNews(newsDto, userId, tenantId, file, path)); } ValidateNews(newsDto, tenantId); var newsObj = Mapper.Map <News>(newsDto); foreach (var newsName in newsDto.TitleDictionary) { newsObj.NewsTranslations.Add(new NewsTranslation { Title = newsName.Value, Description = newsDto.DescriptionDictionary[newsName.Key], Language = newsName.Key, }); } newsObj.CreationTime = Strings.CurrentDateTime; newsObj.CreatorUserId = userId; newsObj.TenantId = tenantId; _typeTranslationService.InsertRange(newsObj.NewsTranslations); _newsService.Insert(newsObj); SaveChanges(); _manageStorage.UploadImage(path + "\\" + "News-" + newsObj.NewsId, file, newsObj.NewsId.ToString()); return(newsDto); }
public async Task <IActionResult> Edit(Guid id, [Bind("Id,Title,Content,Url,Rating,NewsDate,DateCollect,RssSourceId")] NewsDto news) { if (id != news.Id) { return(NotFound()); } if (ModelState.IsValid) { try { await _newsService.Update(news); } catch (DbUpdateConcurrencyException) { if (!NewsExists(news.Id)) { return(NotFound()); } else { throw; } } return(RedirectToAction(nameof(Index))); } //ViewData["RssSourceId"] = new SelectList(_newsService.RssSource, "Id", "Id", news.RssSourceId); return(View(news)); }
public ActionResult Create(NewsDto model) { if (ModelState.IsValid) { var file = Request.Files["ImageInput"]; if (file != null && file.ContentLength > 0) { var upload = new UploadUtility(StoreAreaForUpload.ForNews); var result = upload.SharedCoverSaveAs(file); if (!result.Success) { ModelState.AddModelError("UploadError", result.Message); return(View(model)); } model.ThumbPath = result.Message; } else { const string noImage = @"/assets/img/bg/nonews_photo_400x300.jpg"; model.ThumbPath = Utilities.GetImgUrl(model.NewsContent); if (String.IsNullOrEmpty(model.ThumbPath)) { model.ThumbPath = noImage; } } _newsService.AddNews(model); return(RedirectToAction("Index")); } return(View(model)); }
internal IFacadeUpdateResult <NewsData> SaveNews(NewsDto dto) { ArgumentValidator.IsNotNull("dto", dto); FacadeUpdateResult <NewsData> result = new FacadeUpdateResult <NewsData>(); INewsService service = UnitOfWork.GetService <INewsService>(); News instance = RetrieveOrNew <NewsData, News, INewsService>(result.ValidationResult, dto.Id); if (result.IsSuccessful) { instance.Title = dto.Title; instance.Content = dto.Content; instance.IssuedById = dto.IssuedById; instance.IssuedTime = dto.IssuedTime; instance.NewsGroupId = dto.NewsGroupId; instance.CategoryId = dto.CategoryId; var saveQuery = service.Save(instance); result.AttachResult(instance.RetrieveData <NewsData>()); result.Merge(saveQuery); } return(result); }
public NewsDetailsPage(NewsDto article) { InitializeComponent(); BindingContext = model = new NewsDetailsViewModel { Article = article }; }
public News UpdateFromDto(NewsDto newsDto) { if (newsDto == null) { return(this); } NewsId = newsDto.newsId; AuthorId = newsDto.authorId; Title = newsDto.title; Body = newsDto.body; Date = newsDto.date.UnixTimestampToDateTime(); Type = newsDto.type; // Not recreating list in case of situation if somoene is holding list's reference during update Likes.Clear(); Likes.AddRange(newsDto.likes); // Same thing here Comments.Clear(); if (newsDto.comments != null) { Comments.AddRange(newsDto.comments.Select(commentDto => commentDto.commentId)); } // For fluent interface purposes return(this); }
public void update(NewsDto newsDto) { try { using (TransactionScope tx = new TransactionScope(TransactionScopeOption.Required)) { News news = _newsRepository.getById(newsDto.news_id); if (news == null) { throw new ItemNotFoundException($"News with ID {newsDto.news_id} doesnot Exit."); } string oldImages = news.image; _newsMaker.copy(news, newsDto); _newsRepository.update(news); if (!string.IsNullOrWhiteSpace(oldImages)) { deleteImage(oldImages); } tx.Complete(); } } catch (Exception) { throw; } }
public NewsDto Insert(NewsDto dto) { NewsEntity model = new NewsEntity(dto); try { _Db.CreateTransaction(); _Db.Insert(model); _Db.Commit(); SolrNewsEntity document = new SolrNewsEntity(dto); bool SolrUpdated = _Solr.AddUpdate(document); if (!SolrUpdated) { _Db.Rollback(); } else { _Db.Save(); _Solr.Save(); } return(new NewsDto(model)); } catch (Exception err) { _Solr.RollBack(); _Db.Rollback(); throw err; } }
/// <summary> /// 获取新闻 /// </summary> /// <param name="count"></param> /// <param name="orderString"></param> /// <returns></returns> public async Task <List <NewsDto> > GetTopNewsByCount(int count, string orderString) { DataResultDto <List <NewsDto> > dataResultDto = new DataResultDto <List <NewsDto> >(); List <NewsDto> list = new List <NewsDto>(); string where = "where IsDelete=0 "; string order = string.Format("order by {0}", orderString); string sql = string.Format(" select NewsId,Title,Body,KeyWord,Description,VisitCount,CommentCount,CreateDate,OriginalUrl,Sort,IsDelete from news {0} {1} limit 0,{2}", where, order, count); IEnumerable <News> nlist = null; using (var connection = CreateConnection()) { nlist = await connection.QueryAsync <News>(sql); } NewsDto newsDto = null; foreach (var ib in nlist) { newsDto = Mapper.Map <News, NewsDto>(ib); newsDto.User = new UserDto(); newsDto.User.UserId = 1; newsDto.User.UserName = "******"; newsDto.User.LoginName = "管理员"; newsDto.User.UserHeadImaUrl = "/upload/user-head/default.png"; list.Add(newsDto); } return(list); }
public string GetNavigateUrl(object obj) { NewsDto item = (NewsDto)obj; string url = string.Format("{0}?{1}={2}", NewsPage.PageUrl, NewsPage.QryInstanceId, item.Id); return(GetUrl(url)); }
public async Task <IEnumerable <NewsItem> > GetRemoteNews(string url) { using (var response = await Client.Create().GetAsync(url, new CancellationToken()).ConfigureAwait(false)) { response.EnsureSuccessStatusCode(); var xml = await response.Content.ReadAsStringAsync().ConfigureAwait(false); try { var doc = new XmlDocument(); doc.LoadXml(xml); var jsonString = JsonConvert.SerializeXmlNode(doc); return(NewsDto.FromJson(jsonString).Rss.Channel.NewsItem); } catch (Exception ex) { Debug.WriteLine(ex); } return(new List <NewsItem>()); } }
public async Task <IHttpActionResult> PutNews(int id, NewsDto newsDto) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (id != newsDto.ID) { return(BadRequest()); } var news = DtoToEntityIMapper.Map <NewsDto, News>(newsDto); //// UoW.GetRepository <News>().ModifyEntityState(news); try { await UoW.SaveAsync(); } catch (DbUpdateConcurrencyException) { if (!NewsExists(id)) { return(NotFound()); } else { throw; } } return(StatusCode(HttpStatusCode.NoContent)); }
private static void Localize(NewsDto source, NewsMvcViewModel destination) { var language = LanguageHelper.GetThreadLanguage(); var ruLocalization = source.NewsLocalizations.FirstOrDefault(n => n.LanguageId == 2); var enLocalization = source.NewsLocalizations.FirstOrDefault(n => n.LanguageId == 1); switch (language) { case CultureLanguage.EN: destination.LocalizedTitle = enLocalization?.Header; destination.LocalizedShortDescription = enLocalization?.ShortDescription; destination.LocalizedContent = enLocalization?.Content; break; case CultureLanguage.Undefined: case CultureLanguage.RU: case null: default: destination.LocalizedTitle = ruLocalization?.Header; destination.LocalizedShortDescription = ruLocalization?.ShortDescription; destination.LocalizedContent = ruLocalization?.Content; break; } }
public async Task <IActionResult> PostPublishNews(NewsDto newsDto) { newsDto.UserId = _fakeUser; var news = await _newsDomainService.PublishNewsAsync(newsDto); return(Ok(news)); }
public async Task <News> AddNews(NewsDto news) { var newNews = _newsRepository.Add(news); await _context.SaveChangesAsync(); return(newNews); }
public async Task <ActionResult <NewsDto> > PutNews([FromRoute] int id, [FromBody] NewsDto newsDto) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (id != newsDto.ID) { return(BadRequest()); } News news = DtoToEntityIMapper.Map <NewsDto, News>(newsDto); repository.ModifyEntryState(news, EntityState.Modified); try { await uoW.SaveAsync(); } catch (DbUpdateConcurrencyException) { if (!NewsExists(id)) { return(NotFound()); } else { throw; } } return(NoContent()); }
private async Task LoadNewsDetails() { IncludesSearchRequest searchRequest = GetIncludes(); _news = await _newsApi.GetById <NewsDto>(_id, searchRequest); LoadPropertyValues(_news); }
public SearchItemModel(NewsDto newsDto) { Title = newsDto.NewsTitle; Context = Utilities.DropHtml(newsDto.NewsContent, Length); IntLink = newsDto.NewsId; CreateTime = newsDto.CreateTime; Type = ResultItemType.News; }
public MessageDTO addUpdateNews(NewsDto news) { News nws = Mapper.Map <NewsDto, News>(news); Message msg = _eventsAndNews.addUpdateNews(nws); var result = Mapper.Map <Message, MessageDTO>(msg); return(result); }
private void RetrieveData() { using (IUnitOfWork uow = UnitOfWorkFactory.Instance.Start(DataStoreResolver.CRMDataStoreKey)) { NewsFacade facade = new NewsFacade(uow); CurrentInstance = facade.RetrieveOrNewNews(InstanceId, new NewsConverter()); } }
/// <summary> /// 修改新闻 /// </summary> /// <param name="blogDto"></param> /// <returns></returns> public async Task <bool> UpdateNews(NewsDto newsDto) { string sql = "update `news` set Title=@Title,Body=@Body,KeyWord=@KeyWord,Description=@Description,OriginalUrl=@OriginalUrl,Sort=@Sort where NewsId=@NewsId"; using (var connect = CreateConnection()) { return(await connect.ExecuteAsync(sql, new { Title = newsDto.Title, Body = newsDto.Body, KeyWord = newsDto.KeyWord, Description = newsDto.Description, OriginalUrl = newsDto.OriginalUrl, Sort = newsDto.Sort, NewsId = newsDto.NewsId }) > 0); } }
public async Task Update([FromBody] NewsDto newsDto) { var news = _mapper.Map <News>(newsDto); _context.Update <News>(news); await _context.SaveChangesAsync(); _eventBus.Publish(new NewsUpdateEvent(news)); }
/// <summary> /// 添加新闻 /// </summary> /// <param name="newsDto"></param> /// <returns></returns> public async Task <bool> AddNews(NewsDto newsDto) { string sql = "insert into `news`(Title,Body,KeyWord,Description,OriginalUrl,Sort) VALUES(@Title,@Body,@KeyWord,@Description,@OriginalUrl,@Sort)"; using (var connect = CreateConnection()) { return(await connect.ExecuteAsync(sql, new { Title = newsDto.Title, Body = newsDto.Body, KeyWord = newsDto.KeyWord, Description = newsDto.Description, OriginalUrl = newsDto.OriginalUrl, Sort = newsDto.Sort }) > 0); } }
public async Task SendNews(NewsDto entity) { bool addNews = await newsService.Add(mapper.Map <News>(entity)); if (addNews) { await Clients.All.SendAsync(HubConstants.SendNews, mapper.Map <NewsDto>(entity)); } }
public ActionResult Edit([FromBody] NewsDto news) { //登記操作者 news.UpdateUser = _currentUser.UserName; var myJson = _service.Update(news); return(Json(myJson)); }
public void UpdateNews(NewsDto dto) { var entity = newsRepository.Find(x => x.Id == dto.Id).FirstOrDefault(); entity.Content = dto.Content; entity.Title = dto.Title; entity.TitleImageUrl = dto.TitleImageUrl; newsRepository.Save(entity); }