public NewsModel GetNews(NewsModel news) { //html string htm = Html.GetHtml(news.SourceUrl, "http://uy.ts.cn"); if (string.IsNullOrEmpty(htm)) return null; HtmlDocument doc = new HtmlDocument(); doc.LoadHtml(htm); HtmlNode node = doc.GetElementbyId("content_value"); if (node == null) return null; //图片 //获取基URl //http://uy.ts.cn/news/node_900.htm //string url = string.Format("http://uy.ts.cn/{0}/node_{1}.htm", GetUrlBefore(Convert.ToInt32(news.Types.CatID)), news.Types.CatID); Html.EachImages(node, news.SourceUrl); //删除 注释 IEnumerable<HtmlNode> commons = node.Elements("#comment"); Remove: if (commons != null && commons.Count() > 0) { node.RemoveChild(commons.First()); goto Remove; } news.Content = node.InnerHtml.Trim(' ','\r','\n'); news.Time = DateTime.Now; news.Pic = _GetFirstImg(node); string innerText = node.InnerText; news.KeyWords = innerText.Length > 240 ? innerText.Substring(0, 240) : innerText; return news; }
public static int Insert(NewsModel model) { try { using (DataContentDataContext dc = new DataContentDataContext()) { New newItem = new New(); newItem.Id = model.ID; newItem.Title = model.Title; newItem.Header = model.Header; newItem.Contents = model.Contents; newItem.Author = model.Author; newItem.Link_Image = model.Link_Image; newItem.Link_Image_Small = model.Link_Image_Small; newItem.Type_News = model.Type_News; newItem.Poster = model.Poster; newItem.PosterID = model.PosterID; newItem.Creater = model.Creater; newItem.CreateDate = model.CreateDate; newItem.Modifier = model.Modifier; newItem.ModifyDate = model.ModifyDate; dc.News.InsertOnSubmit(newItem); dc.SubmitChanges(); } return 1; } catch (Exception) { return 0; } }
public void UploadTemporaryNewsTest() { var accessToken = AccessTokenContainer.GetAccessToken(_appId); var file = @"E:\1.jpg"; var mediaId = MediaApi.UploadTemporaryMedia(accessToken, UploadMediaFileType.thumb, file).thumb_media_id; Assert.IsNotNull(mediaId); var new1 = new NewsModel() { author = "test", content = "test", content_source_url = "http://qy.weiweihi.com/Content/Images/app/qyhelper.png", digest = "test", show_cover_pic = "1", thumb_media_id = mediaId, title = "test" }; var new2 = new NewsModel() { author = "test", content = "test111", content_source_url = "http://qy.weiweihi.com/Content/Images/app/qyhelper.png", digest = "test", show_cover_pic = "1", thumb_media_id = mediaId, title = "test" }; var result = MediaApi.UploadTemporaryNews(accessToken, 10000, new1, new2); Assert.IsNotNull(result.media_id); }
public void GetAllNewsShouldReturnTheNewsCorrectly() { var news = new NewsModel { Title = "Fire in the motel", Content = "The fire fighters are doing their best.", PublishDate = DateTime.Now }; var news1 = new NewsModel { Title = "Untitled", Content = "No content", PublishDate = new DateTime(1995, 10, 5) }; List<NewsModel> testList = new List<NewsModel>() { news, news1 }; this.repo.Add(news); this.repo.Add(news1); this.repo.SaveChanges(); var newsInDb = this.repo.All().ToList(); CollectionAssert.AreEqual(testList, newsInDb); }
public void BindData() { string Id = Request.QueryString["id"]; NewsModel model = new NewsModel(); model.ID = Id; objNews = NewsViewModel.SelectOne(model); }
private NewsTypeCollectionModel GetNewsTypeCollectionModel(string libraryName, string name, string folderPath, string sortField, string sortDir, string type) { //Fetch all news contents var newsModel = new NewsModel() { LibraryName = libraryName, Name = name, FolderPath = folderPath, SortDir = sortDir, SortField = sortField }; var news = new News() { LibraryName = newsModel.LibraryName, Name = newsModel.Name, FolderPath = newsModel.FolderPath, SortDir = newsModel.SortDir, SortField = newsModel.SortField }; var documents = NewsService.GetAllContents(news); var output = new List<NewsModel>(); ViewBag.UploadPath = folderPath; ViewBag.LibraryName = libraryName; foreach (var model in documents) { output.Add(new NewsModel() { Name = model.Name, Body = model.Body, CreatedDate = model.CreatedDate, CreatedBy = model.CreatedBy, LastUpdated = model.LastUpdated, LibraryName = libraryName, FolderPath = folderPath }); } //Fetch all Business Updates contents string businessUpdate = ApplicationConfiguration.BusinessUpdates; string events = ApplicationConfiguration.Events; newsModel = new NewsModel() { LibraryName = businessUpdate, Name = businessUpdate, FolderPath = businessUpdate.StartWithSlash(), SortDir = sortDir, SortField = sortField }; news = new News() { LibraryName = newsModel.LibraryName, Name = newsModel.Name, FolderPath = newsModel.FolderPath, SortDir = newsModel.SortDir, SortField = newsModel.SortField }; documents = NewsService.GetAllContents(news); var businessUpdateModel = new List<NewsModel>(); foreach (var model in documents) { businessUpdateModel.Add(new NewsModel() { Name = model.Name, Body = model.Body, CreatedDate = model.CreatedDate, CreatedBy = model.CreatedBy, LastUpdated = model.LastUpdated, LibraryName = businessUpdate, FolderPath = businessUpdate.StartWithSlash() }); } //Fetch all ECS Events contents newsModel = new NewsModel() { LibraryName = events, Name = events, FolderPath = events.StartWithSlash(), SortDir = sortDir, SortField = sortField }; news = new News() { LibraryName = newsModel.LibraryName, Name = newsModel.Name, FolderPath = newsModel.FolderPath, SortDir = newsModel.SortDir, SortField = newsModel.SortField }; documents = NewsService.GetAllContents(news); var ecsEventsModel = new List<NewsModel>(); foreach (var model in documents) { ecsEventsModel.Add(new NewsModel() { Name = model.Name, Body = model.Body, CreatedDate = model.CreatedDate, CreatedBy = model.CreatedBy, LastUpdated = model.LastUpdated, LibraryName = events, FolderPath = events.StartWithSlash() }); } return new NewsTypeCollectionModel() { BusinessUpdatesModel = businessUpdateModel, EcsEventsModel = ecsEventsModel, NewsModel = output }; }
public void UpdateProduct() { NewsModel model = new NewsModel(); model.ID = txtId.Text; model.Author = txtName.Text; model.Title = txtTitle.Text; model.Type_News = (cmdProType.SelectedValue != "") ? cmdProType.SelectedValue.ToCharArray()[0] : '0'; model.Header = FTBHeader.Text; model.Contents = FTBContents.Text; model.Link_Image_Small = (imgSmall.FileName != null) ? UploadImage(imgSmall, "small") : showImgSmall.ImageUrl; model.Link_Image = (imgBig.FileName != "") ? UploadImage(imgBig, "big") : showImageBig.ImageUrl; model.Modifier = Session["user"].ToString(); model.ModifyDate = DateTime.Now.ToString("yyyyMMdd"); NewsViewModel.Update(model); }
public void SaveProduct() { NewsModel model = new NewsModel(); model.ID = txtId.Text; model.Author = txtName.Text; model.Title = txtTitle.Text; model.Type_News = (cmdProType.SelectedValue != "")?cmdProType.SelectedValue.ToCharArray()[0]:'0'; model.Header = FTBHeader.Text; model.Contents = FTBContents.Text; model.Link_Image_Small = UploadImage(imgSmall, "small"); model.Link_Image = UploadImage(imgBig, "big"); model.Creater = Session["user"].ToString(); model.CreateDate = DateTime.Now.ToString("yyyyMMdd"); NewsViewModel.Insert(model); }
public void CreateNewsWithCorrectDataShouldCreateAndReturnNews() { var news = new NewsModel { Title = "Fire in the motel", Content = "The fire fighters are doing their best.", PublishDate = DateTime.Now }; var newsInDb = this.repo.Add(news); Assert.IsNotNull(newsInDb); Assert.AreEqual(news.Title, newsInDb.Title); Assert.AreEqual(news.Content, newsInDb.Content); Assert.AreEqual(news.PublishDate, newsInDb.PublishDate); }
public static int Delete(NewsModel model) { try { using (DataContentDataContext dc = new DataContentDataContext()) { New delItem = dc.News.Where(a => a.Id == model.ID).SingleOrDefault(); dc.News.DeleteOnSubmit(delItem); dc.SubmitChanges(); } return 1; } catch (Exception) { return 0; } }
public void getDateEdit() { NewsModel model = new NewsModel(); model.ID = Request.QueryString["id"]; if (model.ID != "") { model = NewsViewModel.SelectOne(model); txtId.Text = model.ID; txtName.Text = model.Author; txtTitle.Text = model.Title; cmdProType.SelectedValue = model.Type_News.ToString(); showImgSmall.ImageUrl = model.Link_Image_Small; showImageBig.ImageUrl = model.Link_Image; FTBHeader.Text = model.Header; FTBContents.Text = model.Contents; } }
public void Add_ShouldCreateNewNewsAndReturnItOnCorrectData() { var newNews = new NewsModel() { Title = "New news", Content = "The news is new", PublishDate = DateTime.Now }; var returnedNews = this.repository.Add(newNews); this.repository.SaveChanges(); Assert.IsNotNull(returnedNews); Assert.AreEqual(newNews.Title, returnedNews.Title); Assert.AreEqual(newNews.Content, returnedNews.Content); Assert.AreEqual(newNews.PublishDate, returnedNews.PublishDate); Assert.IsTrue(returnedNews.Id != 0); }
public ActionResult IndexCompleted(XDocument contents) { Contract.Assume(contents.Root != null); var channel = contents.Root.Element("channel"); var model = new NewsModel { FeedName = channel.Element("title").Value, Items = channel.Elements("item").Select( e => new NewsItemModel { Title = e.Element("title").Value, PublishDate = e.Element("pubDate").Value, URL = e.Element("link").Value } ).ToArray() }; return View(model); }
protected void btnAdd_Click(object sender, EventArgs e) { if (string.IsNullOrEmpty(this.txtTitle.Text)) { Page.ClientScript.RegisterStartupScript(this.GetType(), "msg", "alert('标题不能为空!')", true); return; } if (string.IsNullOrEmpty(this.txtLocation.Text)) { Page.ClientScript.RegisterStartupScript(this.GetType(), "msg", "alert('新闻来源不能为空!')", true); return; } if (string.IsNullOrEmpty(this.content.Value)) { Page.ClientScript.RegisterStartupScript(this.GetType(), "msg", "alert('新闻内容不能为空!')", true); return; } NewsModel a = new NewsModel(); a.F_Title = VerifyTool.DeleteHtml(this.txtTitle.Text.Trim().ToString()); a.F_Location = VerifyTool.DeleteHtml(this.txtLocation.Text.Trim().ToString()); a.F_Content = VerifyTool.DeleteScript(this.content.Value); a.F_ParentID = Convert.ToInt32(drpClass.SelectedValue); a.F_Keyword = txtKeyword.Text.Trim(); a.F_Lang = Convert.ToInt32(lang); int res = EispNewsBLL.AddNew(a); if (res > 0) { Page.ClientScript.RegisterStartupScript(this.GetType(), "msg", "alert('添加成功!');location.href='NewsADD.aspx?lang=" + lang + "'", true); } else { Page.ClientScript.RegisterStartupScript(this.GetType(), "msg", "alert('添加失败!')", true); } Response.Write(drpClass.SelectedValue); }
public void GetClientNewsSuccess(NewsModel model) { if (model != null) { news = model; toolbar.Title = model.Title; txtPostdate.Text = "发布于:" + DateTimeUtils.CommonTime(news.DateAdded); if (news.DiggCount > 0) { txtDigg.Text = news.DiggCount.ToString(); } if (news.ViewCount > 0) { txtRead.Text = news.ViewCount.ToString(); } if (news.CommentCount > 0) { txtComments.Text = news.CommentCount.ToString(); } (txtComments.Parent as FrameLayout).Click += delegate { NewsCommentsActivity.Start(this, news.Id); }; (txtBookmark.Parent as FrameLayout).Click += delegate { var linkurl = "https://news.cnblogs.com/n/" + news.Id + "/"; var title = news.Title + "_IT新闻_博客园"; BookmarkAddActivity.Start(this, linkurl, title, true); }; if (news.Body == null || news.Body == "") { OnRefresh(); } else { GetServiceNewsSuccess(model); } } }
public void AfterDeleteNewsTest() { var accessToken = AccessTokenContainer.GetToken(_appId); var file = @"E:\1.jpg"; var result = MediaApi.UploadForeverMedia(accessToken, file); Assert.IsNotNull(result.media_id); var new1 = new NewsModel() { author = "test", content = "test", content_source_url = "http://qy.weiweihi.com/Content/Images/app/qyhelper.png", digest = "test", show_cover_pic = "1", thumb_media_id = result.media_id, title = "test" }; var new2 = new NewsModel() { author = "test", content = "test111", content_source_url = "http://qy.weiweihi.com/Content/Images/app/qyhelper.png", digest = "test", show_cover_pic = "1", thumb_media_id = result.media_id, title = "test" }; var result1 = MediaApi.UploadNews(accessToken, 10000, new1, new2); Assert.IsNotNull(result1.media_id); GroupMessageApi.SendGroupMessageByOpenId(accessToken, GroupMessageType.mpnews, result1.media_id, 10000, "o3IHxjrPzMVZIJOgYMH1PyoTW_Tg", "o3IHxjrPzMVZIJOgYMH1PyoTW_Tg"); //var result2 = MediaApi.UpdateForeverNews(accessToken, result1.media_id, 0, 10000, new2); MediaApi.DeleteForeverMedia(accessToken, result1.media_id); //Assert.AreEqual(result2.errcode, ReturnCode.请求成功); }
// GET: api/T_News_Masters/5 //[ResponseType(typeof(T_News_Masters))] public async Task <IHttpActionResult> GetT_News_Masters(int id) { T_News_Masters t_News_Masters = await db.T_News_Masters.FindAsync(id); if (t_News_Masters == null) { return(NotFound()); } NewsModel ObjNewsDetails = new NewsModel() { NewsID = t_News_Masters.NewsID, Active = t_News_Masters.Active, CreatedBy = t_News_Masters.CreatedBy, CreatedDate = t_News_Masters.CreatedDate.ToString("dd-MMM-yyyy"), Img1 = t_News_Masters.Img1, Img2 = t_News_Masters.Img2, Img3 = t_News_Masters.Img3, Img4 = t_News_Masters.Img4, Img5 = t_News_Masters.Img5, Location = t_News_Masters.Location, ModifiedBy = t_News_Masters.ModifiedBy, ModifiedDate = t_News_Masters.ModifiedDate.ToString("dd-MMM-yyyy"), NewsHeading = t_News_Masters.NewsHeading, NewsSubCategoryID = t_News_Masters.NewsSubCategoryID, NewsTypeID = t_News_Masters.NewsType, NoOfNewsViews = t_News_Masters.NoOfNewsViews, Para1 = t_News_Masters.Para1, Para2 = t_News_Masters.Para2, Para3 = t_News_Masters.Para3, Para4 = t_News_Masters.Para4, Para5 = t_News_Masters.Para5, Remarks = t_News_Masters.Remarks, SubHeading = t_News_Masters.SubHeading, NewsCategoryID = t_News_Masters.M_NewsSubCategoryMasters.NewsCategory, NewsCategory = t_News_Masters.M_NewsSubCategoryMasters.M_NewsCategoryMaster.CategoryName, NewsSubCategory = t_News_Masters.M_NewsSubCategoryMasters.SubCategory, NewsType = t_News_Masters.M_RSAMasters.TableValue }; return(Ok(ObjNewsDetails)); }
/// <summary> /// 更新一条数据 /// </summary> public bool Update(NewsModel model) { StringBuilder strSql = new StringBuilder(); strSql.Append("update tb_News set "); strSql.Append("Title=@Title,"); strSql.Append("NTypes=@NTypes,"); strSql.Append("Content=@Content,"); strSql.Append("PhotoUrl=@PhotoUrl,"); strSql.Append("PushTime=@PushTime,"); strSql.Append("States=@States"); strSql.Append(" where NewsID=@NewsID"); SqlParameter[] parameters = { new SqlParameter("@Title", SqlDbType.NVarChar, 100), new SqlParameter("@NTypes", SqlDbType.NVarChar, 10), new SqlParameter("@Content", SqlDbType.NVarChar, -1), new SqlParameter("@PhotoUrl", SqlDbType.NVarChar, 200), new SqlParameter("@PushTime", SqlDbType.DateTime), new SqlParameter("@States", SqlDbType.Int, 4), new SqlParameter("@NewsID", SqlDbType.Int, 4) }; parameters[0].Value = model.Title; parameters[1].Value = model.NTypes; parameters[2].Value = model.Content; parameters[3].Value = model.PhotoUrl; parameters[4].Value = model.PushTime; parameters[5].Value = model.States; parameters[6].Value = model.NewsID; int rows = DbHelperSQL.ExecuteSql(strSql.ToString(), parameters); if (rows > 0) { return(true); } else { return(false); } }
//[TestMethod] private string UploadAndUpdateNewsTest(string accessToken) { //var file = @"E:\1.jpg"; //var result = MediaApi.UploadForeverMedia(accessToken, file, UploadForeverMediaType.image); //Assert.IsNotNull(result.media_id); var mediaId = UploadForeverMediaTest(); var new1 = new NewsModel() { author = "test", content = "test", content_source_url = "https://weixin.senparc.com/Content/Images/2019/logo-community-two-lines.png", digest = "test", show_cover_pic = "1", thumb_media_id = mediaId, title = "test" }; var new2 = new NewsModel() { author = "test", content = "test111", content_source_url = "https://weixin.senparc.com/Content/Images/2019/logo-community-two-lines.png", digest = "test", show_cover_pic = "1", thumb_media_id = mediaId, title = "test" }; var result = MediaApi.UploadNewsAsync(accessToken, 10000, new1, new2).GetAwaiter().GetResult(); Assert.IsNotNull(result.media_id); Console.WriteLine("上传图文素材成功,mediaId:" + result.media_id); //var result2 = MediaApi.UpdateForeverNews(accessToken, result1.media_id, 0, 10000, new2); //Assert.AreEqual(result2.errcode, ReturnCode.请求成功); return(result.media_id); }
public void ListAllNews_ShouldReturnNewsCorrectly() { var controller = new NewsController(this.context); this.SetupController(controller); var news = new NewsModel { Title = "Fire in the motel", Content = "The fire fighters are doing their best.", PublishDate = DateTime.Now }; var news1 = new NewsModel { Title = "Untitled", Content = "No content", PublishDate = new DateTime(1995, 10, 5) }; var news2 = new NewsModel { Title = "Today hits", Content = "No content", PublishDate = DateTime.Now }; this.context.Add(news); this.context.Add(news1); this.context.Add(news2); var response = controller.GetNews().ExecuteAsync(CancellationToken.None).Result; var newsResponce = response.Content .ReadAsAsync <IEnumerable <NewsModel> >() .Result .ToList(); Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); CollectionAssert.AreEqual(newsResponce, this.context.All().ToList()); }
public void AfterDeleteNewsTest() { var accessToken = AccessTokenContainer.GetAccessToken(_appId); var file = @"E:\1.jpg"; var result = MediaApi.UploadForeverMedia(accessToken, file); Assert.IsNotNull(result.media_id); var new1 = new NewsModel() { author = "test", content = "test", content_source_url = "http://qy.weiweihi.com/Content/Images/app/qyhelper.png", digest = "test", show_cover_pic = "1", thumb_media_id = result.media_id, title = "test" }; var new2 = new NewsModel() { author = "test", content = "test111", content_source_url = "http://qy.weiweihi.com/Content/Images/app/qyhelper.png", digest = "test", show_cover_pic = "1", thumb_media_id = result.media_id, title = "test" }; var result1 = MediaApi.UploadNews(accessToken, 10000, new1, new2); Assert.IsNotNull(result1.media_id); GroupMessageApi.SendGroupMessageByOpenId(accessToken, GroupMessageType.mpnews, result1.media_id, 10000, "o3IHxjrPzMVZIJOgYMH1PyoTW_Tg", "o3IHxjrPzMVZIJOgYMH1PyoTW_Tg"); //var result2 = MediaApi.UpdateForeverNews(accessToken, result1.media_id, 0, 10000, new2); MediaApi.DeleteForeverMedia(accessToken, result1.media_id); //Assert.AreEqual(result2.errcode, ReturnCode.请求成功); }
private async Task <NewsModel> GetNews(string newsId) { var model = new NewsModel(); try { var newsModel = _cacheManager.Get <List <NewsModel> >("NewsItems").FirstOrDefault(n => n.Id == newsId); // var responseBody = await _fileUploader.GetFileFromS3(@"News/NewsItems/" + newsId + ".json"); // var newsModel = JsonConvert.DeserializeObject<NewsModel>(responseBody); newsModel.MainImg = newsModel.Images.FirstOrDefault(); model = newsModel; // var update = await UpdateVisits(model); } catch (Exception ex) { //ignore } return(model); }
public ActionResult EditNotice() { NewsInfo newsInfo = AdminNews.AdminGetNewsById(1); if (newsInfo == null) { return(PromptView("没有系统公告不存在")); } ShopUtils.SetAdminRefererCookie(Url.Action("editnotice")); NewsModel model = new NewsModel(); model.NewsTypeId = newsInfo.NewsTypeId; model.IsShow = newsInfo.IsShow; model.IsTop = newsInfo.IsTop; model.IsHome = newsInfo.IsHome; model.DisplayOrder = newsInfo.DisplayOrder; model.Title = newsInfo.Title; model.Url = newsInfo.Url; model.Body = newsInfo.Body; return(View(model)); }
public ActionResult Write(NewsModel model) { if (ModelState.IsValid) { model.Author = User.Identity.Name; model.Raiting = 0; model.CreateDate = DateTime.Now; //ViewBag.Text = model.Text; string query = string.Format("insert into News (UserName, Title, Contect, Raiting, CreateDate) values('{0}', '{1}', '{2}', 0, '{3}')", model.Author, model.Title, WebUtility.HtmlEncode(model.Text), model.CreateDate); SqlCommand command = new SqlCommand(query, DataBase.Sql); command.ExecuteNonQuery(); return(RedirectToAction("Index", "Home")); } else { return(View(model)); } }
/// <summary> /// 更新新闻信息 /// </summary> /// <param name="oRModel"></param> /// <returns></returns> public string SetNewsInfo(NewsModel oNModel) { string ret = Config.Fail; try { ret = nb.SetNewsInfo(oNModel); int Id = 0; bool flag = Int32.TryParse(ret, out Id); if (flag && Id > 0) { return(Config.Success); } } catch (Exception ex) { WriteLog.WriteExceptionLog("NewsBLL.SetNewsInfo()", ex); return(Config.ExceptionMsg); } return(ret); }
// GET: News public ActionResult Index() { LinkedList <rrNews> llNews = rrNewsDB.GetNewsList(); NewsModel[] ModelArray = new NewsModel[llNews.Count]; int i = 0; foreach (rrNews News in llNews) { ModelArray[i] = new NewsModel(News); i++; } if (User.IsInRole("admin")) { return(View("EditIndex", ModelArray)); } return(View("Index", ModelArray)); }
public ActionResult AddRe1(FormCollection form) { string author = Request.Form["author"]; string content = Request.Form["content"]; int id = int.Parse(Request.Form["nid"]); T1NewsRe data = new T1NewsRe() { NewsID = id, ahthor = author, content = content }; NewsModel db = new NewsModel(); if (ModelState.IsValid) { db.T1NewsRe.Add(data); db.SaveChanges(); return(Redirect(Url.Action("Details", "Index", new { id = id }))); } return(View(data)); }
private IList <NewsModel> PopulateNews(DataSet ds) { var models = new List <NewsModel>(); if (ds != null) { foreach (DataRow rowItem in ds.Tables[0].Rows) { var model = new NewsModel(); model.Content = rowItem["Content"].ToString(); model.Id = int.Parse(rowItem["Id"].ToString()); model.Title = rowItem["Title"].ToString(); model.Category = DataStorageService.FindCategoryById(int.Parse(rowItem["CategoryId"].ToString())); model.DateCreated = DateTime.Parse(rowItem["DateCreated"].ToString()); model.DateUpdated = DateTime.Parse(rowItem["DateUpdated"].ToString()); models.Add(model); } } return(models); }
public void GetServiceNewsSuccess(NewsModel model) { if (model != null) { handler.Post(() => { if (swipeRefreshLayout.Refreshing) { swipeRefreshLayout.Refreshing = false; } news = model; if (swipeRefreshLayout.Refreshing) { swipeRefreshLayout.Refreshing = false; } var content = HtmlUtils.ReadHtml(Assets); var body = HtmlUtils.ReplaceHtml(model.Body).Trim('"'); txtBody.LoadDataWithBaseURL("file:///android_asset/", content.Replace("#title#", model.Title).Replace("#body#", body), "text/html", "utf-8", null); }); } }
public static IList <NewsModel> BuildArchivedNews(DASEntities db, int ArchiveId) { int languageId = (int)HttpContext.Current.Session["lngId"]; Archive temp = db.Archives.Include("News").Where(j => j.ArchiveId == ArchiveId).FirstOrDefault(); IList <NewsModel> list = new List <NewsModel>(); foreach (News tempC in temp.News) { if (languageId == tempC.LanguageId) { NewsModel news = new NewsModel() { NewsId = tempC.NewsId, Name = tempC.Name, Text = tempC.Text, Year = tempC.Year, Ord = tempC.Ord, Archive = tempC.Archive, LanguageId = tempC.LanguageId }; list.Add(news); } } return(list); }
public List <NewsModel> GetNewsByCondition(string condition) { SqlParameter param = new SqlParameter("@Condition", SqlDbType.VarChar, 255); param.Value = condition; SqlDataReader dr = SqlHelp.ExecuteReader("prc_GetNewsByCondition", CommandType.StoredProcedure, param); List <NewsModel> list = new List <NewsModel>(); while (dr.Read()) { NewsModel news = new NewsModel(); news.ID = Convert.ToInt32(dr[0]); news.Title = dr[1].ToString(); news.NoticeDate = Convert.ToDateTime(dr[2]); news.NoticeContent = dr[3].ToString(); news.NoticePerson = dr[4].ToString(); list.Add(news); } dr.Close(); return(list); }
public ActionResult <IEnumerable <News> > AddNews([FromBody] NewsModel content) { using (var context = new eshopContext()) { if (!context.News.ToList().Any(newsses => newsses.NewsTittle == content.NewsTittle)) { News newNews = new News(); newNews.NewsTittle = content.NewsTittle; newNews.NewsDescription = content.NewsDescription; newNews.NewsBody = content.NewsBody; newNews.NewsDateTime = DateTime.Now; newNews.UserId = content.UserId; context.News.Add(newNews); context.SaveChanges(); } } return(new List <News>()); }
private SMT.Saas.Tools.PlatformWS.T_PF_NEWS ModelToEntity(NewsModel clientModel) { DateTime dt = new DateTime(clientModel.UPDATEDATE.Year, clientModel.UPDATEDATE.Month, clientModel.UPDATEDATE.Day, DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second); SMT.Saas.Tools.PlatformWS.T_PF_NEWS model = new SMT.Saas.Tools.PlatformWS.T_PF_NEWS() { CREATECOMPANYID = Common.CurrentLoginUserInfo.UserPosts[0].CompanyID, CREATEDATE = DateTime.Now, CREATEDEPARTMENTID = Common.CurrentLoginUserInfo.UserPosts[0].DepartmentID, CREATEPOSTID = Common.CurrentLoginUserInfo.UserPosts[0].PostID, CREATEUSERID = Common.CurrentLoginUserInfo.EmployeeID, CREATEUSERNAME = Common.CurrentLoginUserInfo.EmployeeName, OWNERCOMPANYID = Common.CurrentLoginUserInfo.UserPosts[0].CompanyID, OWNERDEPARTMENTID = Common.CurrentLoginUserInfo.UserPosts[0].DepartmentID, OWNERID = Common.CurrentLoginUserInfo.EmployeeID, OWNERNAME = Common.CurrentLoginUserInfo.UserPosts[0].DepartmentName, OWNERPOSTID = Common.CurrentLoginUserInfo.EmployeeID, UPDATEUSERID = Common.CurrentLoginUserInfo.EmployeeID, UPDATEUSERNAME = Common.CurrentLoginUserInfo.EmployeeName, UPDATEDATE = dt, NEWSID = clientModel.NEWSID, NEWSCONTENT = clientModel.NEWSCONTENT, NEWSSTATE = clientModel.NEWSSTATE, NEWSTITEL = clientModel.NEWSTITEL, COMMENTCOUNT = "0", READCOUNT = "0", ISIMAGE = clientModel.ISIMAGE ? "1" : "0", ISPOPUP = clientModel.ISPOPUP ? "1" : "0", ENDDATE = clientModel.ENDDATE, NEWSTYPEID = clientModel.NEWSTYPEID, PUTDEPTID = clientModel.PUTDEPTID, PUTDEPTNAME = clientModel.PUTDEPTNAME }; NewsId = model.NEWSID.ToString(); return(model); }
private async void ExecuteFavoriteCommand(NewsModel news) { if (IsFavorite) { return; } try { IsBusy = true; await Task.Delay(100).ConfigureAwait(true); if (!Settings.IsLoggedIn) { await PushAsync <SocialLoginViewModel>(); return; } await _client.Save(News); _favorite = new FavoriteModel { NewsId = News.Id, UserId = Settings.UserId, News = News, Id = Guid.NewGuid().ToString() }; await _client.Save(_favorite); IsFavorite = true; } catch (Exception ex) { await DisplayAlert("Erro", ex.Message, "OK"); } finally { IsBusy = false; } }
public async Task <IActionResult> EditNews(NewsModel model, IFormFile file) { var entity = _newsService.GetById(model.Id); if (entity == null) { return(NotFound()); } if (ModelState.IsValid) { entity.Title = model.Title; entity.Author = model.Author; entity.Description = model.Description; entity.DateTime = model.DateTime; if (file != null) { FileFunctions.DeletePreviousImage(Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot\img\news", entity.ImageUrl)); entity.ImageUrl = file.FileName; var path = Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot\img\news", file.FileName); using (var stream = new FileStream(path, FileMode.Create)) await file.CopyToAsync(stream); } _newsService.Update(entity); ToastrService.AddToUserQueue(new Toastr() { Message = Toastr.GetMessage("Haber", EntityStatus.Update), Title = Toastr.GetTitle("Haber", EntityStatus.Update), ToastrType = ToastrType.Info }); return(RedirectToAction("NewsList")); } ViewBag.ErrorMessage = _newsService.ErrorMessage; return(View(model)); }
protected void Button1_Click(object sender, EventArgs e) { NewsModel newsModel = new NewsModel(); //获取新闻标题 newsModel.NewsTitle = titleText.Text.Trim(); //获取新闻作者 newsModel.AddUserId = int.Parse(Session["admin"].ToString()); newsHandler = new NewsHandler(); if (RadioButton1.Checked) { newsModel.NewsType = 1; //获取新闻内容 newsModel.NewsContent = newsContentCKE1.Value; } if (RadioButton2.Checked) { newsModel.NewsType = 2; newsModel.NewsContent = UrlText.Text.Trim(); if (!newsModel.NewsContent.StartsWith("http://") && !newsModel.NewsContent.StartsWith("https://")) { newsModel.NewsContent = "http://" + newsModel.NewsContent; } } //if (RadioButton3.Checked) //{ // newsModel.NewsType = 3; //} //添加新闻 if (newsHandler.AddNews(newsModel) > 0) { Page.ClientScript.RegisterStartupScript(Page.GetType(), "message", "<script language='javascript' defer>alert('提交成功!');</script>"); Response.Redirect("NewsManager.aspx"); } else { Page.ClientScript.RegisterStartupScript(Page.GetType(), "message", "<script language='javascript' defer>alert('提交失败,请联系管理员!');</script>"); } }
public async Task <IActionResult> GetHtmlAsyncSaudi() { var url = "http://www.alriyadh.com/search/srch?sort=date&q=%D9%83%D9%88%D8%B1%D9%88%D9%86%D8%A7"; var httpClient = new HttpClient(); var html = await httpClient.GetStringAsync(url); var htmlDocument = new HtmlDocument(); htmlDocument.LoadHtml(html); var ProductsHtml = htmlDocument.DocumentNode.Descendants("div") .Where(node => node.GetAttributeValue("class", "") .Equals("col-lg-9")).ToList(); var ProductListItems = ProductsHtml[0].Descendants("div") .Where(node => node.GetAttributeValue("class", "") .Contains("tr-post bx")).ToList(); foreach (var item in ProductListItems) { NewsModel newsModel = new NewsModel(); var childs = ProductListItems[0].ChildNodes[1]; newsModel.Image = childs.InnerHtml.Split('"')[1]; var editTitle = item.InnerText.Trim(' ', '\n'); var edittt = editTitle.Trim('&'); string[] lines = Regex.Split(edittt, "\t\t"); newsModel.Title = lines[6].Trim('&', '\n').TrimStart(' ').TrimEnd(' '); newsModel.Text = lines[10].Trim('&', '\n').TrimStart(' ').TrimEnd(' '); newsModel.Date = DateTime.Now.ToString(); newsModel.NewsSourceModel = null; newsModel.Detail = null; newsModel.NewsSourceModelId = 4; newsModel.Image = "98763131.jpg"; _context.NewsModels.Add(newsModel); CreatedAtAction("GetNewsModel", new { id = newsModel.Id }, newsModel); } await _context.SaveChangesAsync(); return(NoContent()); }
public async Task <IActionResult> AddNews([FromBody] NewsModel newsModel) { var prevNews = db.News.FirstOrDefault(n => n.Author == newsModel.Author && n.Header == newsModel.Header); if (prevNews == null) { logger.LogDebug($"Adding news, author: {newsModel.Author}"); if (newsModel.Date == null) { newsModel.Date = DateTime.Now; } var state = db.News.Add(new News(newsModel))?.State; logger.LogDebug($"News addition result: {state}"); db.SaveChanges(); return(Ok()); } else { logger.LogWarning($"News already exists"); return(StatusCode(500, "Duplicate")); } }
//[TestMethod] private string UploadAndUpdateNewsTest(string accessToken) { var file = @"E:\1.jpg"; var result = MediaApi.UploadForeverMedia(accessToken, file); Assert.IsNotNull(result.media_id); var new1 = new NewsModel() { author = "test", content = "test", content_source_url = "http://qy.weiweihi.com/Content/Images/app/qyhelper.png", digest = "test", show_cover_pic = "1", thumb_media_id = result.media_id, title = "test" }; var new2 = new NewsModel() { author = "test", content = "test111", content_source_url = "http://qy.weiweihi.com/Content/Images/app/qyhelper.png", digest = "test", show_cover_pic = "1", thumb_media_id = result.media_id, title = "test" }; var result1 = MediaApi.UploadNews(accessToken, 10000, new1, new2); Assert.IsNotNull(result1.media_id); //var result2 = MediaApi.UpdateForeverNews(accessToken, result1.media_id, 0, 10000, new2); //Assert.AreEqual(result2.errcode, ReturnCode.请求成功); return(result1.media_id); }
public async Task <IActionResult> GetHtmlAsyncEmarat() { var url = "https://www.emaratalyoum.com/search-7.160?s=d&q=%D9%83%D9%88%D8%B1%D9%88%D9%86%D8%A7"; var httpClient = new HttpClient(); var html = await httpClient.GetStringAsync(url); var htmlDocument = new HtmlDocument(); htmlDocument.LoadHtml(html); var ProductsHtml = htmlDocument.DocumentNode.Descendants("div") .Where(node => node.GetAttributeValue("class", "") .Equals("grid_8 pull_right content")).ToList(); var ProductListItems = ProductsHtml[0].Descendants("li") .Where(node => node.GetAttributeValue("class", "") .Contains("el")).ToList(); foreach (var item in ProductListItems) { NewsModel newsModel = new NewsModel(); var editTitle = item.InnerText.Trim(' ', '\n', '&'); var edittt = editTitle.Trim('&'); string[] lines = Regex.Split(edittt, "\t\t"); var Title = lines[8].Trim('&', '\n', 'q', 'u', 'o', 't', ';').TrimStart(' ').TrimEnd(' '); newsModel.Title = Regex.Replace(Title, """, " ").Trim(' ');; var Text = lines[16].Trim('&', '\n', 'q', 'u', 'o', 't', ';').TrimStart(' ').TrimEnd(' '); newsModel.Text = Regex.Replace(Text, """, " ").Trim(' '); newsModel.NewsSourceModel = null; newsModel.Detail = null; newsModel.NewsSourceModelId = 3; newsModel.Date = DateTime.Now.ToString(); newsModel.Image = "89170909.png"; _context.NewsModels.Add(newsModel); CreatedAtAction("GetNewsModel", new { id = newsModel.Id }, newsModel); } await _context.SaveChangesAsync(); return(NoContent()); }
public bool Update(NewsModel model) { string msgError = ""; try { var result = _dbHelper.ExecuteScalarSProcedureWithTransaction(out msgError, "sp_news_update", "@tt_id", model.tt_id, "@tt_image", model.tt_image, "@tt_name", model.tt_name, "@tt_description", model.tt_description); if ((result != null && !string.IsNullOrEmpty(result.ToString())) || !string.IsNullOrEmpty(msgError)) { throw new Exception(Convert.ToString(result) + msgError); } return(true); } catch (Exception ex) { throw ex; } }
public IActionResult NewsEditAdmin(int?id) { var entity = _newsServices.GetByWithCategoriesAndAuthorId((int)id); var model = new NewsModel() { NewsId = entity.NewsId, Title = entity.Title, Content = entity.Content, Description = entity.Description, Date = entity.Date, Image = entity.Image, Url = entity.Url, IsApproved = entity.IsApproved, nCategories = entity.newsHCategories.Select(i => i.NCategories).ToList(), Authors = entity.newsAuthors.Select(i => i.Author).ToList() }; ViewBag.NCategories = _nCategoryServices.GetAll(); ViewBag.Authors = _authorServices.GetAll(); return(View(model)); }
public IEnumerable <NewsModel> GetList() { List <NewsModel> model = new List <NewsModel>(); var result = _ent.Core_News.OrderBy(x => x.CreatedDate); foreach (var item in result) { NewsModel obj = new NewsModel { PId = item.NewsId, Title = item.Title, Summary = item.Summary, Description = item.Description, CreatedDate = item.CreatedDate, CreatedBy = item.CreatedBy, IsPublish = item.IsPublish, }; model.Add(obj); } return(model.AsEnumerable()); }
public async Task <NewsModel> ShowNews() { HttpClient httpClient = new HttpClient(); string url = $"https://fortniteapi.io/news?lang=en&type=br"; httpClient.DefaultRequestHeaders.Add("Authorization", "0e235bf6-1954f433-5e4caaf7-f6deb034"); try { HttpResponseMessage response = await httpClient.GetAsync(url); response.EnsureSuccessStatusCode(); NewsModel news = await response.Content.ReadAsAsync <NewsModel>(); return(news); } catch (HttpRequestException) { return(new NewsModel()); } }
public int Insert(NewsModel news) { //DateTime test = new DateTime(2015, 5, 27, 22, 43, 31); //long lb = test.Ticks - 14327378110000000; //DateTime dt = new DateTime(lb); long times = news.Time.Ticks; DateTime timeold = new DateTime(1970, 1, 1, 8, 0, 0); long tic = times - timeold.Ticks; tic = tic / 10000000; string sql = "INSERT INTO `phpred_hawar` (`title` ,`tur` ,`tur2` ,`keywords`,`body` ,`litpic` ,`mid` ,`time` ,`menbe` ,`menbe_url` ,`ip`,`testiq` ,`tewis` ,`view` ,`last_view`) VALUES(@title,@tur,'0',@keywords,@content,@pic,'0',@time,@menbe,@menbeurl,'127.0.0.1','1','0','1','0');"; MySqlParameter[] param = { new MySqlParameter("@title",news.Title), new MySqlParameter("@tur",news.Types.LocalID), new MySqlParameter("@keywords",news.KeyWords), new MySqlParameter("@content",news.Content), new MySqlParameter("@pic",news.Pic), new MySqlParameter("@time", MySqlDbType.VarChar){Value = tic}, new MySqlParameter("@menbe",news.Source), new MySqlParameter("@menbeurl",news.SourceUrl) }; return Helper.Insert(sql, param); }
public ActionResult News() { var model = new NewsModel(); FillResourceNewsModel(model); return View(model); }
private void FillResourceNewsModel(NewsModel model) { model.NewsCategories = Execute(() => _newsService.GetNewsGategories()) ?? new List<NewsCategoryData>(); model.Platforms = Execute(() => _resourceService.GetPlatforms()) ?? new List<PlatformData>(); }
private void FillNewsModel(NewsModel model) { var pagerData = (Execute(() => _newsService.GetNews(model.NewsCategoryId, model.PlatformId, model.SortId, model.Pager.PageId, model.Pager.PageSize)) ?? new PageData<NewsData>()); model.CopyFrom(pagerData); }
public void ModifyItemWithCorrectDataShouldModifyCorrectly() { var news = new NewsModel { Title = "Fire in the motel", Content = "The fire fighters are doing their best.", PublishDate = DateTime.Now }; this.repo.Add(news); this.repo.SaveChanges(); var newNews = new NewsModel { Title = "Fire was extinguished", Content = "No more fire.", PublishDate = DateTime.Now }; var newsInDb = this.repo.Find(news.Id); newsInDb.Title = newNews.Title; newsInDb.Content = newNews.Content; newsInDb.PublishDate = newNews.PublishDate; this.repo.Update(newsInDb); this.repo.SaveChanges(); var updatedNewsInDb = this.repo.Find(newsInDb.Id); Assert.AreEqual(newNews.Title, updatedNewsInDb.Title); Assert.AreEqual(newNews.Content, updatedNewsInDb.Content); Assert.AreEqual(newNews.PublishDate, updatedNewsInDb.PublishDate); }
public static int Update(NewsModel model) { try { using (DataContentDataContext dc = new DataContentDataContext()) { New changeItem = dc.News.Where(a => a.Id == model.ID).SingleOrDefault(); changeItem.Header = model.Header; changeItem.Title = model.Title; changeItem.Contents = model.Contents; changeItem.Author = model.Author; changeItem.Type_News = model.Type_News; changeItem.Link_Image = model.Link_Image; changeItem.Link_Image_Small = model.Link_Image_Small; changeItem.ModifyDate = model.ModifyDate; changeItem.Modifier = model.Modifier; changeItem.PosterID = model.PosterID; changeItem.Poster = model.Poster; dc.SubmitChanges(); } return 1; } catch (Exception) { return 0; } }
public void DeleteExistingItemShouldDeleteItem() { var news = new NewsModel { Title = "Fire in the motel", Content = "The fire fighters are doing their best.", PublishDate = DateTime.Now }; var n = this.repo.Add(news); this.repo.SaveChanges(); this.repo.Delete(n); this.repo.SaveChanges(); int newsCount = this.repo.All().Count(); Assert.AreEqual(0, newsCount); }
public void DeleteNonExistingItemShouldThrowException() { var news = new NewsModel { Id = 1233, Title = "Fire in the motel", Content = "The fire fighters are doing their best.", PublishDate = DateTime.Now }; this.repo.Delete(news); this.repo.SaveChanges(); }
public ActionResult GetContent(string libraryName, string name, string folderPath, string type) { try { var newsModel = new NewsModel() { LibraryName = libraryName, Name = name, FolderPath = folderPath }; var news = new News() { LibraryName = newsModel.LibraryName, Name = newsModel.Name, FolderPath = newsModel.FolderPath }; var model = NewsService.GetAllContent(news); ViewBag.UploadPath = folderPath; ViewBag.LibraryName = libraryName; var output = new NewsModel() { Name = model.Name, Body = model.Body, CreatedDate = model.CreatedDate, CreatedBy = model.CreatedBy, LastUpdated = model.LastUpdated }; return View("ShowNews", output); } catch (Exception ex) { throw ex; } }
public ActionResult Content(string libraryName, string name, string folderPath, string sortField, string sortDir, string type) { try { var newsModel = new NewsModel() { LibraryName = libraryName, Name = name, FolderPath = folderPath, SortDir = sortDir, SortField = sortField }; var news = new News() { LibraryName = newsModel.LibraryName, Name = newsModel.Name, FolderPath = newsModel.FolderPath, SortDir = newsModel.SortDir, SortField = newsModel.SortField }; var documents = NewsService.GetAllContents(news); var output = new List<NewsModel>(); ViewBag.UploadPath = folderPath; ViewBag.LibraryName = libraryName; foreach (var model in documents) { output.Add(new NewsModel() { Name = model.Name, Body = model.Body, CreatedDate = model.CreatedDate, CreatedBy = model.CreatedBy, LastUpdated = model.LastUpdated }); } return View("NewsTopic", output); } catch (Exception ex) { throw ex; } }
public static NewsModel SelectOne(NewsModel model) { try { using (DataContentDataContext dc = new DataContentDataContext()) { New i = dc.News.Where(a => a.Id == model.ID).SingleOrDefault(); return new NewsModel(i.Id, i.Header, i.Contents, i.Author, i.Type_News, i.Link_Image_Small, i.Link_Image, i.Poster, i.PosterID, i.Creater, i.CreateDate, i.Modifier, i.ModifyDate, i.Title); } } catch (Exception) { return new NewsModel(); } }
public ActionResult NewsData(NewsModel model) { FillNewsModel(model); return View(model); }
public ActionResult NewsFilter(string id) { var model = new NewsModel(); FillResourceNewsModel(model); FillFilterParams(model, id); return View("News", model); }
private static void FillFilterParams(NewsModel model, string shortId) { if (string.IsNullOrWhiteSpace(shortId)) return; var equalsPlatforms = model.Platforms.Where(platform => String.Equals(platform.ShortName, shortId, StringComparison.OrdinalIgnoreCase)).ToList(); if (equalsPlatforms.Any()) { model.PlatformId = equalsPlatforms.First().Id; } else { var equalsCategories = model.NewsCategories.Where(category => String.Equals(category.ShortName, shortId, StringComparison.OrdinalIgnoreCase)).ToList(); if (equalsCategories.Any()) { model.NewsCategoryId = equalsCategories.First().Id; } } }
/// <summary> /// Get News base on CatID /// </summary> /// <param name="CatID"></param> /// <returns></returns> public static List<NewsModel> SelectAll(string CatID) { List<NewsModel> lst = new List<NewsModel>(); try { using (DataContentDataContext dc = new DataContentDataContext()) { var items = from temp in dc.News where temp.CatID == CatID select temp; foreach (var i in items) { NewsModel n = new NewsModel(i.Id, i.Header, i.Contents, i.Author, i.Type_News, i.Link_Image_Small, i.Link_Image, i.Poster, i.PosterID, i.Creater, i.CreateDate, i.Modifier, i.ModifyDate, i.Title); lst.Add(n); } } return lst; } catch (Exception) { return lst; } }
public void CreateNewsWithIncorrectDataShouldThrowException() { var news = new NewsModel { Title = "1", Content = "2", PublishDate = DateTime.Now }; this.repo.Add(news); this.repo.SaveChanges(); }