public void ProcessRequest(HttpContext context) { context.Response.ContentType = "application/json"; string action = context.Request.QueryString["action"]; if (string.Compare(action, "adminLogin", false) == 0) { int varifyCode = 0; if (int.TryParse(context.Request["captcha"], out varifyCode)) { string json = string.Empty; Debug.Write(varifyCode); int sCode = -1; var o = context.Session["varifyCode"]; if (o == null) { json = JsonConvert.SerializeObject(new { IsOk = "NoOk", Msg = "请刷新验证码再试" }); context.Response.Write(json); return; } sCode = int.Parse(o.ToString()); if (sCode == varifyCode) { //验证用户名密码 FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, "admin", DateTime.Now, DateTime.Now.AddDays(1), false, "password", "/"); string authticket = FormsAuthentication.Encrypt(ticket); HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, authticket); cookie.Secure = false; cookie.Expires = ticket.Expiration; cookie.Path = FormsAuthentication.FormsCookiePath; context.Response.Cookies.Add(cookie); json = JsonConvert.SerializeObject(new { IsOk = "Ok" }); context.Response.Write(json); } else { json = JsonConvert.SerializeObject(new { IsOk = "NoOk", Msg = "验证码输入有误,请刷新验证码" }); context.Response.Write(json); return; } } else { string json = JsonConvert.SerializeObject(new { IsOk = "NoOk", Msg = "" }); context.Response.Write(json); return; } } else if (string.Compare(action, "yzm", false) == 0) { ValidateCode c = new ValidateCode(); string code = c.CreateValidateCode(4); context.Session["varifyCode"] = code; c.CreateValidateGraphic(code, context); } else if (string.Compare(action, "loginInfo", false) == 0) { context.Response.ContentType = "application/json"; LoginInfoData data = new LoginInfoData(); int page = int.Parse(context.Request["page"]); int limit = int.Parse(context.Request["limit"]); data.code = 0; data.msg = "ok"; data.count = 6; List <LoginInfo> listInfo = new List <LoginInfo>(); listInfo.Add(new LoginInfo() { City = "重庆", Id = 0, Ip = "192.168.1.1", UserName = "******", LoginDate = "2020-6-10 19:00:00", UserOS = "win10" }); listInfo.Add(new LoginInfo() { City = "重庆", Id = 1, Ip = "192.168.1.1", UserName = "******", LoginDate = "2020-6-10 19:00:00", UserOS = "win10" }); listInfo.Add(new LoginInfo() { City = "重庆", Id = 2, Ip = "192.168.1.1", UserName = "******", LoginDate = "2020-6-10 19:00:00", UserOS = "win10" }); listInfo.Add(new LoginInfo() { City = "重庆", Id = 3, Ip = "192.168.1.1", UserName = "******", LoginDate = "2020-6-10 19:00:00", UserOS = "win10" }); listInfo.Add(new LoginInfo() { City = "重庆", Id = 4, Ip = "192.168.1.1", UserName = "******", LoginDate = "2020-6-10 19:00:00", UserOS = "win10" }); listInfo.Add(new LoginInfo() { City = "重庆", Id = 5, Ip = "192.168.1.1", UserName = "******", LoginDate = "2020-6-10 19:00:00", UserOS = "win10" }); data.data = listInfo.Skip((page - 1) * limit).Take(limit).ToList(); context.Response.Write(JsonConvert.SerializeObject(data)); } else if (string.Compare(action, "notice", false) == 0) { context.Response.ContentType = "application/json"; string p = context.Request["page"]; string l = context.Request["limit"]; int page = -1; if (!string.IsNullOrEmpty(p)) { page = int.Parse(p); } int limit = -1; if (!string.IsNullOrEmpty(l)) { limit = int.Parse(l); } NoticeData data = new NoticeData(); data.code = 0; data.msg = "ok"; var list = TestData.getNotice(); if (page < 0 || limit < 0) { data.data = list; } else { data.data = list.Skip((page - 1) * limit).Take(limit).ToList(); } data.count = list.Count(); context.Response.Write(JsonConvert.SerializeObject(data)); } else if (string.Compare(action, "article", false) == 0) { context.Response.ContentType = "application/json"; string p = context.Request["page"]; string l = context.Request["limit"]; int page = -1; if (!string.IsNullOrEmpty(p)) { page = int.Parse(p); } int limit = -1; if (!string.IsNullOrEmpty(l)) { limit = int.Parse(l); } ArticleData data = new ArticleData(); data.code = 0; data.msg = "ok"; var list = TestData.GetArticle(); if (page < 0 || limit < 0) { data.data = list; } else { data.data = list.Skip((page - 1) * limit).Take(limit).ToList(); } data.count = list.Count(); context.Response.Write(JsonConvert.SerializeObject(data)); } else if (string.Compare(action, "uploadImg", false) == 0) { ImgJson iJson = new ImgJson(); iJson.data = new List <string>(); string dir = "\\UpImgs\\" + DateTime.Now.ToString("yyyyMMdd"); string physicsPath = HttpContext.Current.Server.MapPath("~" + dir); if (!System.IO.Directory.Exists(physicsPath)) { System.IO.Directory.CreateDirectory(physicsPath); } for (int i = 0; i < context.Request.Files.Count; i++) { string phPath = string.Empty; //获取上传的文件的对象 HttpPostedFile img = context.Request.Files[i]; //获取上传文件的名称 string s = img.FileName; var strFileExtension = s.Substring(s.LastIndexOf('.') + 1, s.Length - s.LastIndexOf('.') - 1); string allowextension = System.Configuration.ConfigurationManager.AppSettings["ImageType"]; if (allowextension.ToLower().IndexOf(strFileExtension.ToLower()) >= 0) { int len = s.LastIndexOf(".") - s.LastIndexOf("\\") - 1; string fileName = DateTime.Now.ToString("yyyyMMdd") + DateTime.Now.Millisecond.ToString(); string fullName = fileName + "." + strFileExtension; //fileName = fileName.Replace(",", ""); //fullName = fullName.Replace(",", ""); //fullName = fullName.Replace(":", ""); //截取获得上传文件的名称(ie上传会把绝对路径也连带上,这里只得到文件的名称) //string str = System.Guid.NewGuid().ToString("N")+ s.Substring(s.LastIndexOf(".") - 1); // s.Substring(s.LastIndexOf("\\") + 1); string path = dir + "\\" + fullName; phPath = physicsPath + "//" + fullName; //保存文件 img.SaveAs(phPath); iJson.data.Add(path); } } if (iJson.data.Count > 0 && iJson.data.Count == context.Request.Files.Count) { iJson.code = 1; } else { iJson.code = 0; iJson.msg = "上传图片出现错误"; } context.Response.ContentType = "application/json"; context.Response.AddHeader("Content-Type", "text/html; charset=UTF-8"); context.Response.Write(JsonConvert.SerializeObject(iJson)); } else if (string.Compare(action, "uploadImg1", false) == 0) { context.Response.AddHeader("Content-Type", "text/html; charset=UTF-8"); string fileType = context.Request["dir"]; string dir = string.Empty; string allowextension = string.Empty; if (fileType == "file") { dir = "\\UpFiles\\" + DateTime.Now.ToString("yyyyMMdd"); allowextension = System.Configuration.ConfigurationManager.AppSettings["FileType"]; } else { dir = "\\UpImgs\\" + DateTime.Now.ToString("yyyyMMdd"); allowextension = System.Configuration.ConfigurationManager.AppSettings["ImageType"]; } try { string physicsPath = HttpContext.Current.Server.MapPath("~" + dir); if (!System.IO.Directory.Exists(physicsPath)) { System.IO.Directory.CreateDirectory(physicsPath); } if (context.Request.Files.Count > 0) { string phPath = string.Empty; //获取上传的文件的对象 HttpPostedFile img = context.Request.Files[0]; //获取上传文件的名称 string s = img.FileName; var strFileExtension = s.Substring(s.LastIndexOf('.') + 1, s.Length - s.LastIndexOf('.') - 1); if (allowextension.ToLower().IndexOf(strFileExtension.ToLower()) >= 0) { int len = s.LastIndexOf(".") - s.LastIndexOf("\\") - 1; string fileName = DateTime.Now.ToString("yyyyMMdd") + DateTime.Now.Millisecond.ToString(); string fullName = fileName + "." + strFileExtension; string path = dir + "\\" + fullName; phPath = physicsPath + "//" + fullName; string pp = path.Replace("\\", "/"); //保存文件 img.SaveAs(phPath); context.Response.Write(JsonConvert.SerializeObject(new { error = 0, url = pp })); } else { context.Response.Write(JsonConvert.SerializeObject(new { error = 1, message = "文件格式不支持" })); } } else { context.Response.Write(JsonConvert.SerializeObject(new { error = 1, message = "网络错误,后台没接收到文件" })); } } catch (Exception) { context.Response.Write(JsonConvert.SerializeObject(new { error = 1, message = "上传图片出错" })); throw; } } else if (string.Compare(action, "noticeAE", false) == 0) { var id = context.Request["noticeId"]; var title = context.Request["noticeTitle"]; var content = context.Request["noticeContent"]; var time = context.Request["DataStart"]; DateTime time1 = DateTime.Now; if (!string.IsNullOrEmpty(time)) { time1 = Convert.ToDateTime(time); } //编辑 if (!string.IsNullOrEmpty(id)) { } else {//新增 } context.Response.Write(JsonConvert.SerializeObject(new { IsOk = "Ok", msg = "操作完成" })); } else if (string.Compare(action, "ArticleAE", false) == 0) { FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(context.Request.Cookies[FormsAuthentication.FormsCookieName].Value); if (ticket == null) { context.Response.Write(JsonConvert.SerializeObject(new { IsOk = "NoOk", msg = "请刷新页面再试" })); context.Response.End(); } LLArticle article = new LLArticle(); int artId = String.IsNullOrEmpty(context.Request["ArtId"]) ? -1 : int.Parse(context.Request["ArtId"]); string listStr = context.Request["ArtType"]; if ("" != listStr && null != listStr) { article.ArtType = listStr.Split(new char[] { ',' }).Select(str => int.Parse(str)).ToList(); } article.Content = context.Request["Content"]; article.Title = context.Request["ArtTitle"]; article.Digest = context.Request["Digest"]; article.ReadPwd = context.Request["ArtPwd"]; article.Editor = ticket.Name; if (artId > 0) { article.LastUpdatetime = DateTime.Now; } else { article.ArtTime = DateTime.Now; } context.Response.Write(JsonConvert.SerializeObject(new { IsOk = "Ok", msg = "操作成功" })); } else if (string.Compare(action, "articleType", false) == 0) { context.Response.ContentType = "application/json"; string p = context.Request["page"]; string l = context.Request["limit"]; int page = -1; if (!string.IsNullOrEmpty(p)) { page = int.Parse(p); } int limit = -1; if (!string.IsNullOrEmpty(l)) { limit = int.Parse(l); } ArtTypeData data = new ArtTypeData(); data.code = 0; data.msg = "ok"; var list = TestData.GetLLType(); if (page < 0 || limit < 0) { data.data = list; } else { data.data = list.Skip((page - 1) * limit).Take(limit).ToList(); } data.count = list.Count(); context.Response.Write(JsonConvert.SerializeObject(data)); } else if (string.Compare(action, "artTypeAE", false) == 0) { var id = context.Request["TypeId"]; var title = context.Request["TypeTitle"]; var detail = context.Request["TypeDetail"]; var time = context.Request["TypeCTime"]; var isHidden = context.Request["TypeIsHidden"]; DateTime time1 = DateTime.Now; if (!string.IsNullOrEmpty(time)) { time1 = Convert.ToDateTime(time); } //编辑 if (!string.IsNullOrEmpty(id)) { } else {//新增 } context.Response.Write(JsonConvert.SerializeObject(new { IsOk = "Ok", msg = "操作完成" })); } }
private static string TextEvaluator(TextBlock text, ArticleData data) => TextEvaluator(text, data, new Dictionary <string, object>());
public void Put([FromBody] ArticleData article) { var articlePL = _mapper.Map <ArticleModel>(article); _service.Update(articlePL); }
private void buttonSearch_Click(object sender, RoutedEventArgs e) { bool tagsFound = false; bool articleFound = false; bool textParsable; int parsedNumber = 0; // Check for db conntection if (!_tagDb.IsConnected()) { return; } // Clear previous search entries SearchEntries.Clear(); // Check if field is set if (textBoxSearch.Text == "") { return; } // Try parse given number textParsable = int.TryParse(textBoxSearch.Text, out parsedNumber); // Search by chip number ArticleData articleFromDb = _tagDb.GetArticleDataByTagData(textBoxSearch.Text); // Check return value if (articleFromDb != null) { articleFound = true; SearchEntries.Add(new SearchEntry(articleFromDb.Id.ToString(), articleFromDb.Name, articleFromDb.Note, articleFromDb.Cost, "", DateTime.Now, "")); Logger.GetInstance().Log($"CW: Article received: {articleFromDb.Id}, {articleFromDb.Name}, {articleFromDb.Cost}, {articleFromDb.Note}"); } if (textParsable) { // Search by article number List <TagData> tagsFromDb = _tagDb.GetTagDataByArticleData(parsedNumber); // Check return value if (tagsFromDb.Count >= 1) { tagsFound = true; foreach (var td in tagsFromDb) { SearchEntries.Add(new SearchEntry("", "", "", 0.00M, td.Id, td.TimeStamp, td.Data)); Logger.GetInstance().Log($"CW: Tag received: {td.Id}, {td.TimeStamp}, {td.Data}"); } } } //Update data grid dataGridSearch.Items.Refresh(); // Set status label if (articleFound) { if (tagsFound) { labelStatus.Content = "Status: Artikel und Tags gefunden."; } else { labelStatus.Content = "Status: Artikel gefunden."; } } else { if (tagsFound) { labelStatus.Content = "Status: Tags gefunden."; } else { labelStatus.Content = "Status: Suche ergab keine Ergebnisse."; } } }
public static string Assemble(ArticleData data, TemplateBlock[] elements) => Assemble(data, elements, new Dictionary <string, object>());
public static ArticleData Parse(string article, ArticleHeadInfo articleHeadInfo, bool debug = false) { string content = File.ReadAllText(article); ArticleData ad = new ArticleData(articleHeadInfo); MarkdownDocument document = new MarkdownDocument(); document.Parse(content); List <MarkdownBlock> elements = new List <MarkdownBlock>(); List <ChapterData> chapters = new List <ChapterData>(); ChapterData chapter = new ChapterData(); List <MarkdownBlock> chapterElements = new List <MarkdownBlock>(); void AddChapter() { if (chapterElements.Count > 0) { chapter.Elements = chapterElements.ToArray(); chapters.Add(chapter); } } void NewChapter(HeaderBlock header) { // Add old AddChapter(); // New chapter chapter = new ChapterData { Title = header.ToString().Trim() }; chapterElements = new List <MarkdownBlock>(); } for (int i = 0; i < document.Blocks.Count; i++) { MarkdownBlock block = document.Blocks[i]; if (debug) { Console.Write($"{block.Type}: ", ConsoleColor.Cyan); } if (!IsCommentParagraph(block)) { elements.Add(block); } if (block is HeaderBlock header) { if (header.HeaderLevel <= 2) { if (header.HeaderLevel == 1 && ad.TITLE == null) { ad.TITLE = header.ToString().Trim(); } NewChapter(header); continue; } } if (!IsCommentParagraph(block)) { chapterElements.Add(block); } if (block is ParagraphBlock paragraph) { if (debug) { Console.WriteLine(); } for (int j = 0; j < paragraph.Inlines.Count; j++) { MarkdownInline inline = paragraph.Inlines[j]; if (debug) { Console.Write($" {inline.Type}: ", ConsoleColor.DarkCyan); } if (debug) { Console.WriteLine(inline.ToString()); } if (inline.Type != MarkdownInlineType.Comment) { } } if (debug) { Console.WriteLine("\n" + block.ToHtml()); } } else { if (debug) { Console.WriteLine(block + "\n" + block.ToHtml()); } } } AddChapter(); ad.CHAPTERS = chapters.ToArray(); ad.ELEMENTS = elements.ToArray(); return(ad); }
void createLocalCache(ArticleData[] articles) { string json = LitJson.JsonMapper.ToJson(articles); PlayerPrefs.SetString("ONEWS_ARTICLES", json); }
public static CommentFetchContext Initial(ArticleData articleinfo) { return(new CommentFetchContext(articleinfo)); }
public async Task <JsonResult> FetchArticles(string ids) { string authorizationToken = ""; string apiURL = ConfigurationManager.AppSettings["apiUrl"]; string articleServiceUrl = ""; string strStores = ConfigurationManager.AppSettings["Stores"]; int[] stores; stores = strStores.Split(',').Select(int.Parse).ToArray(); List <ArticleViewModel> articleList = new List <ArticleViewModel>(); ArticleData responseItem = null; try { foreach (int store in stores) { articleServiceUrl = string.Concat(apiURL, string.Format("?store={0}&chain={1}&ids={2}", store.ToString(), "0", ids)); authorizationToken = this.generateJWTToken( Convert.ToString(ConfigurationManager.AppSettings["Secret"]), Convert.ToString(ConfigurationManager.AppSettings["Issuer"]), articleServiceUrl); using (HttpClient client = new HttpClient(ClientHandler, false)) { client.MaxResponseContentBufferSize = 1000000; client.DefaultRequestHeaders.Add("Authorization", string.Format("JWT {0}", authorizationToken)); client.DefaultRequestHeaders.Add("Accept", "application/json;charset=UTF-8"); string args = string.Format("store={0}&chain={1}&ids={2}", store.ToString(), "0", ids); HttpResponseMessage response = await client.GetAsync(articleServiceUrl); if (response.IsSuccessStatusCode) { responseItem = JsonConvert.DeserializeObject <ArticleData>( response.Content.ReadAsStringAsync().Result); if (responseItem != null) { string resultInfo = string.Format("Successfully call API with args: {0}", args); if (responseItem.articles.Count > 0) { responseItem.articles.ForEach(article => articleList.Add(article)); break; } } else { string resultInfo = string.Format("Failed to call API. args: {0}", args); } } else { string resultInfo = string.Format("Failed to call API. args: {0}", args); } } } } catch (Exception e) { Console.WriteLine(e); throw; } return(Json(articleList, JsonRequestBehavior.AllowGet)); }
public static List <string> ExtractWordsFromBody(ArticleData data) { return(data.Text.GetWordsFromBody()); }
/// <summary> /// 更新到数据库(从缓存同步到数据库用) /// </summary> /// <param name="o"></param> /// <returns></returns> public Task UpdateToDbAsync(ArticleData o) { _context.ArticleData.Update(o); return(Task.CompletedTask); }
/// <summary> /// Generates the file structure from config file /// </summary> /// <param name="projectDirectory">Project directory</param> /// <param name="config">Configuration</param> public static void Compile(string projectDirectory, Config config, bool debug = false) { string articlesPath = Path.Combine(projectDirectory, config.ArticlesPath); string templatesPath = Path.Combine(projectDirectory, config.TemplatesPath); string stylesPath = Path.Combine(projectDirectory, config.StylesPath); string outputPath = Path.Combine(projectDirectory, config.OutputPath); if (!Directory.Exists(articlesPath)) { Console.WriteLine("Articles directory could not be found!", ConsoleColor.Red); } else if (!Directory.Exists(templatesPath)) { Console.WriteLine("Templates directory could not be found!", ConsoleColor.Red); } else if (!Directory.Exists(stylesPath)) { Console.WriteLine("Styles directory could not be found!", ConsoleColor.Red); } else { if (!Directory.Exists(outputPath)) { Directory.CreateDirectory(outputPath); } #region Compile Articles void CompileArticleDirectory(string directoryPath, string relativePath) { // Compile all articles using the templates. string[] articles = Directory.GetFiles(directoryPath); foreach (var article in articles) { ArticleHeadInfo ahi = ArticleHeadInfoParser.Parse(article, config.DefaultArticleInfo); string fileOutput = Path.Combine(outputPath, Path.Combine(relativePath, Path.GetFileNameWithoutExtension(article))) + ".html"; Console.WriteLine($"Compiling '{article}' to '{fileOutput}' using template '{ahi.TemplateFileName()}'...", ConsoleColor.Yellow); string template = String.Empty; if (File.Exists(Path.Combine(templatesPath, ahi.Template))) { template = Path.Combine(templatesPath, ahi.Template); } else if (File.Exists(Path.Combine(templatesPath, ahi.TemplateFileName()))) { template = Path.Combine(templatesPath, ahi.TemplateFileName()); } else { Console.WriteLine($"Template '{ahi.TemplateFileName()}' not found in '{templatesPath}'! Please enter a valid filepath.", ConsoleColor.Red); continue; } ArticleData ad = ArticleParser.Parse(article, ahi, debug); TemplateAssembler.InitializeInterpreter(ad); string result = TemplateAssembler.AssembleFile(ad, template); File.WriteAllText(fileOutput, result); } string[] parts = Directory.GetDirectories(directoryPath); foreach (string part in parts) { CompileArticleDirectory(Path.Combine(directoryPath, part), part); } } CompileArticleDirectory(articlesPath, string.Empty); #endregion #region Move Styles #endregion } }
/// <summary> /// サーバーから記事データをダウンロードする /// </summary> /// <param name="hatakeType">対象のハタケ種別</param> /// <returns></returns> public ObservableCollection <ArticleData> DownloadData(HatakeType hatakeType) { // TODO:サーバーから記事データをダウンロードする。 ObservableCollection <ArticleData> articleDatas = new ObservableCollection <ArticleData>(); ArticleData articleData1 = new ArticleData(); ArticleData articleData2 = new ArticleData(); ArticleData articleData3 = new ArticleData(); ArticleData articleData4 = new ArticleData(); ArticleData articleData5 = new ArticleData(); // TODO:サーバー側で取得する記事を振り分けるのでここの分岐は仮物。 if (hatakeType == HatakeType.JapanGreenTea) { articleData1.ArticleImage = ImageSource.FromResource("ChasMine.Assets.News1.jpeg"); articleData1.ArticleTitle = "日常からほんの少し離れた場所『鎌倉』で日本各地のお茶を本格的に味わいながら心を整える時間を過ごしませんか"; articleData1.EditorName = "NIHONCHAFAN.COM"; articleData1.PostDate = DateTime.Now; articleData1.URL = "https://nihonchafan.com/kamakura-club-saryo/"; articleData2.ArticleImage = ImageSource.FromResource("ChasMine.Assets.News2.jpg"); articleData2.ArticleTitle = "話題沸騰中!日本茶ミルクティー専門店「OCHABA」に行ってきた【新宿】"; articleData2.EditorName = "じゃらんニュース"; articleData2.PostDate = DateTime.Now; articleData2.URL = "https://www.excite.co.jp/news/article/JalanNews_356319/"; articleData3.ArticleImage = ImageSource.FromResource("ChasMine.Assets.News3.jpg"); articleData3.ArticleTitle = "お茶のおいしさ、「消費者が決める」 渋谷で品評会"; articleData3.EditorName = "NIKKEI STYLE"; articleData3.PostDate = DateTime.Now; articleData3.URL = "https://style.nikkei.com/article/DGXMZO93825140Q5A111C1000000?channel=DF130120166105&style=1"; articleData4.ArticleImage = ImageSource.FromResource("ChasMine.Assets.News4.jpg"); articleData4.ArticleTitle = "センチュリーロイヤルホテル日本茶で訪日外国人観光客をおもてなし雪まつり期間、ホテルロビーで呈茶サービス2月1日より「お茶を食すレストランフェア」も開催"; articleData4.EditorName = "valuepress"; articleData4.PostDate = DateTime.Now; articleData4.URL = "https://www.value-press.com/pressrelease/155167"; articleData5.ArticleImage = ImageSource.FromResource("ChasMine.Assets.News5.jpg"); articleData5.ArticleTitle = "日本茶ティーサロン「カネジュウ農園」が表参道に、一番茶チーズホイップティーや桜煎茶で楽しむ茶の魅力"; articleData5.EditorName = "fashionpress[ファッションプレス]"; articleData5.PostDate = DateTime.Now; articleData5.URL = "https://www.fashion-press.net/news/46819"; } else if (hatakeType == HatakeType.BlackTea) { articleData1.ArticleImage = ImageSource.FromResource("ChasMine.Assets.News6.jpg"); articleData1.ArticleTitle = "【国内初】ガブリエル シャネル アフタヌーンティー アット フォーシーズンズ"; articleData1.EditorName = "PR TIMES"; articleData1.PostDate = DateTime.Now; articleData1.URL = "https://prtimes.jp/main/html/rd/p/000000024.000031396.html"; articleData2.ArticleImage = ImageSource.FromResource("ChasMine.Assets.News7.jpg"); articleData2.ArticleTitle = "リプトン ティー スタンド「茨城メロン」の限定フルーツインティー、名古屋&博多で発売"; articleData2.EditorName = "fashionpress[ファッションプレス]"; articleData2.PostDate = DateTime.Now; articleData2.URL = "https://www.fashion-press.net/news/53084"; articleData3.ArticleImage = ImageSource.FromResource("ChasMine.Assets.News8.jpg"); articleData3.ArticleTitle = "「三越英国展」日本橋三越で、日本初登場の限定アフタヌーンティー&英国NO.1フィッシュ&チップス"; articleData3.EditorName = "fashionpress[ファッションプレス]"; articleData3.PostDate = DateTime.Now; articleData3.URL = "https://www.fashion-press.net/news/53115"; articleData4.ArticleImage = ImageSource.FromResource("ChasMine.Assets.News9.png"); articleData4.ArticleTitle = "新CMキャラクター伊藤健太郎さんが「ミルクティー男子」に!?「紅茶花伝 ロイヤルミルクティー」25年目のフルリニューアルで9月2日(月)から全国発売「心が通い合った」牛と共演する新CM撮影現場に潜入!"; articleData4.EditorName = "cocacola.co.jp"; articleData4.PostDate = DateTime.Now; articleData4.URL = "https://www.cocacola.co.jp/press-center/news-20190822-11"; articleData5.ArticleImage = ImageSource.FromResource("ChasMine.Assets.News10.jpg"); articleData5.ArticleTitle = "アップルが芳醇すぎる「キリン 午後の紅茶 Fruit×Fruit TEA アップル&グリーンアップル」はもはや紅茶フレーバーのアップルジュース"; articleData5.EditorName = "Gigazine"; articleData5.PostDate = DateTime.Now; articleData5.URL = "https://gigazine.net/news/20190910-gogo-tea-fruit-green-apple/"; } articleDatas.Add(articleData1); articleDatas.Add(articleData2); articleDatas.Add(articleData3); articleDatas.Add(articleData4); articleDatas.Add(articleData5); return(articleDatas); }
/// <exception cref="ArgumentNullException" /> /// <exception cref="InvalidOperationException" /> private void ProcessArticlesTree(Article newArticle, Article existingArticle, Content definition) { if (newArticle == null || !_filter.Matches(newArticle)) { return; } if (!_filter.Matches(existingArticle)) { existingArticle = null; } if (definition == null) { throw new ArgumentNullException(nameof(definition)); } ValidateDates(newArticle, existingArticle); ArticleData newArticleUpdateData = new ArticleData { ContentId = definition.ContentId, Id = newArticle.Id }; List <int> plainFieldIds = definition.Fields .Where(x => x is PlainField) .Select(x => x.FieldId) .ToList(); if (definition.LoadAllPlainFields) { plainFieldIds.AddRange( _fieldService.List(definition.ContentId) .Where(x => x.RelationType == RelationType.None && definition.Fields.All(y => y.FieldId != x.Id)) .Select(x => x.Id)); } // TODO: исключаем Readonly поля var updatedFields = newArticle.Fields.Values .OfType <PlainArticleField>() .Where(x => plainFieldIds.Contains(x.FieldId.Value) && (existingArticle == null || existingArticle.Fields.Values .OfType <PlainArticleField>() .All(y => y.FieldId != x.FieldId || !HasEqualNativeValues(x, y)))) .Select(x => new FieldData { Id = x.FieldId.Value, Value = x.Value }); newArticleUpdateData.Fields.AddRange(updatedFields); var associationFieldsInfo = ( from fieldDef in definition.Fields.OfType <Association>() join field in newArticle.Fields.Values on fieldDef.FieldId equals field.FieldId select new { field, oldField = existingArticle?.Fields.Values.SingleOrDefault(x => x.FieldId == field.FieldId), fieldDef }).ToArray(); foreach (var fieldToSyncInfo in associationFieldsInfo) { if (fieldToSyncInfo.fieldDef is BackwardRelationField backwardRelationFieldDef) { BackwardArticleField oldField = (BackwardArticleField)fieldToSyncInfo.oldField; BackwardArticleField field = (BackwardArticleField)fieldToSyncInfo.field; int[] idsToAdd = field.GetArticles(_filter) .Where(x => oldField == null || oldField.GetArticles(_filter).All(y => y.Id != x.Id)) .Select(x => x.Id) .ToArray(); int[] idsToRemove = oldField?.GetArticles(_filter) .Select(x => x.Id) .Where(x => field.GetArticles(_filter).All(y => y.Id != x)) .ToArray() ?? new int[0]; if (idsToAdd.Any()) { _updateData.AddRange(idsToAdd.Select(x => new ArticleData { Id = x, ContentId = backwardRelationFieldDef.Content.ContentId, Fields = new List <FieldData> { new FieldData { Id = field.FieldId.Value, ArticleIds = new[] { newArticle.Id } } } })); } if (idsToRemove.Any()) { if (backwardRelationFieldDef.DeletingMode == DeletingMode.Delete) { foreach (int idToRemove in idsToRemove) { _articlesToDelete[idToRemove] = backwardRelationFieldDef.Content; } } else { _updateData.AddRange(idsToRemove.Select(x => new ArticleData { Id = x, ContentId = backwardRelationFieldDef.Content.ContentId })); } } } else if (fieldToSyncInfo.fieldDef is ExtensionField extensionFieldDef) { ExtensionArticleField oldField = (ExtensionArticleField)fieldToSyncInfo.oldField; ExtensionArticleField field = (ExtensionArticleField)fieldToSyncInfo.field; if (oldField == null || field.Value != oldField.Value) { newArticleUpdateData.Fields.Add(new FieldData { Id = extensionFieldDef.FieldId, Value = field.Value, ArticleIds = field.Item == null ? null : new[] { field.Item.Id } }); if (oldField?.Item != null) { _articlesToDelete[oldField.Item.Id] = extensionFieldDef .ContentMapping[oldField.Item.ContentId]; } } } else if (fieldToSyncInfo.field is SingleArticleField) { SingleArticleField oldField = (SingleArticleField)fieldToSyncInfo.oldField; SingleArticleField field = (SingleArticleField)fieldToSyncInfo.field; EntityField entityFieldDef = (EntityField)fieldToSyncInfo.fieldDef; Article item = field.GetItem(_filter); Article oldItem = oldField?.GetItem(_filter); if (item?.Id != oldItem?.Id) { newArticleUpdateData.Fields.Add(new FieldData { Id = field.FieldId.Value, ArticleIds = item == null ? null : new[] { item.Id } }); if (oldItem != null && entityFieldDef.DeletingMode == DeletingMode.Delete) { _articlesToDelete[oldItem.Id] = entityFieldDef.Content; } } } else if (fieldToSyncInfo.field is MultiArticleField) { MultiArticleField oldField = (MultiArticleField)fieldToSyncInfo.oldField; MultiArticleField field = (MultiArticleField)fieldToSyncInfo.field; EntityField entityFieldDef = (EntityField)fieldToSyncInfo.fieldDef; var items = field.GetArticles(_filter).ToArray(); var oldItems = oldField?.GetArticles(_filter).ToArray(); if (items.Length != (oldItems?.Length ?? 0) || items.Any(x => oldItems.All(y => y.Id != x.Id))) { newArticleUpdateData.Fields.Add(new FieldData { Id = field.FieldId.Value, ArticleIds = items.Select(x => x.Id).ToArray() }); if (entityFieldDef.DeletingMode == DeletingMode.Delete) { int[] idsToRemove = oldItems? .Where(x => items.All(y => y.Id != x.Id)) .Select(x => x.Id) .ToArray() ?? new int[0]; foreach (int idToRemove in idsToRemove) { _articlesToDelete[idToRemove] = entityFieldDef.Content; } } } } } if (newArticleUpdateData.Fields.Any()) { _updateData.Add(newArticleUpdateData); } foreach (var fieldInfo in associationFieldsInfo .Where(x => x.fieldDef.UpdatingMode == UpdatingMode.Update || x.fieldDef is ExtensionField)) { Article[] oldFieldsArticles = fieldInfo.oldField == null ? new Article[0] : GetChildArticles(fieldInfo.oldField, _filter).ToArray(); foreach (Article childArticle in GetChildArticles(fieldInfo.field, _filter)) { Content childArticleDef = fieldInfo.fieldDef.GetContents() .SingleOrDefault(x => x.ContentId == childArticle.ContentId); if (childArticleDef == null) { throw new InvalidOperationException($@"There is an conflict in product definition field {fieldInfo.field.FieldId} between ContentId={childArticle.ContentId} and Articleid={childArticle.Id}"); } Article oldChildArticle = oldFieldsArticles.SingleOrDefault(x => x.Id == childArticle.Id); ProcessArticlesTree(childArticle, oldChildArticle, childArticleDef); } } }
public PreprocessedArticle(ArticleData data, string tag, List <string> stopList) { Label = tag; PreProcessText(data, stopList); }
private static string ActionEvaluator(ActionBlock action, ArticleData data) => ActionEvaluator(action, data, new Dictionary <string, object>());
public WebBrowserPage(ArticleData selectedData) { InitializeComponent(); this.BindingContext = new WebBrowserPageViewModel(this.Navigation, selectedData); }
/// <summary> /// Assemble an article with the given template /// </summary> /// <param name="data">The article data</param> /// <param name="templateFile">The filepath to the template</param> /// <returns>True if successful</returns> public static string AssembleFile(ArticleData data, string templateFile) => Assemble(data, TemplateDocument.ParseFile(templateFile));
/// <summary> /// 处理图文消息 /// </summary> /// <param name="originContent">id|id|id</param> /// <param name="data">素材资源库</param> /// <returns></returns> public static List <Article> FillNewsMessage(string originContent, MaterialData data) { if (originContent.IsNullOrWhiteSpace()) { return(null); } //var firstMaterialId = originContent.Split('|')?[0]; List <Article> articleList = new List <Article>(); //materialIds 如:9DAAC45C|6309EAD9,记录了设置当时的News的文章顺序,第一个参数为主图文的Id, //主图文的material内已经自带了所有关联的多图文Id,因此这里只需要取第一个 var materialIds = originContent.Split('|'); var material = data.FirstOrDefault(z => z.Id == materialIds[0]); if (material == null) { return(null); } var articleData = SerializerHelper.GetObject <ArticleData>(material.Content);//获取主文章(第一篇图文)内容 if (articleData != null && articleData.ArticleIds != null) { for (int i = 0; i < articleData.ArticleIds.Count; i++) { ArticleData articleItem = null; string materialId = null; if (i == 0) { articleItem = articleData;//第一项就是自己 materialId = material.Id; } else { var materialItem = data.FirstOrDefault(z => z.Id == articleData.ArticleIds[i]);//后续选项从素材中查找 if (materialItem != null) { articleItem = SerializerHelper.GetObject <ArticleData>(materialItem.Content); if (articleItem == null) { continue; } materialId = materialItem.Id; } else { continue; } } var article = new Article() { Title = articleItem?.Title, PicUrl = articleItem?.ThumbCoverUrl, Description = articleItem?.Digest, // Url = $"http://neuchar.senparc.com/Material/Details?uniqueId={articleItem.ArticleIds[0]}" }; if (articleItem.ContentSourceUrl.IsNullOrWhiteSpace()) { article.Url = $"http://neuchar.senparc.com/WX/Material/Details?uniqueId={materialId}"; } else { article.Url = articleItem.ContentSourceUrl; } articleList.Add(article); } } return(articleList.Count > 0 ? articleList : null);//TODO:可以返回一条默认有好消息 //var list = SerializerHelper.GetObject<List<Article>>(originContent); //foreach (var item in list) //{ // item.Title = FillTextMessage(item.Title); // item.Description = FillTextMessage(item.Description); //} //return list; }
public static string Assemble(ArticleData data, TemplateDocument document) => Assemble(data, document.Elements);
public void Dispose() { context.Dispose(); context = null; article = null; }
public IActionResult ViewArticle() { var model = new ArticleData(); return(View(model)); }