// search for the finishing website // inputs: strings for start and end, ArticleCollection to store webpages in, ForbiddenLinks object void searchForWebsite(string StartPageName, string FinishPageName, ArticleCollection Webpages, ForbiddenLinks Forbidden) { // get data for first webpage WikipediaWebRequest request = new WikipediaWebRequest("wiki/"+StartPageName, Webpages, Forbidden, null); // successful request, start program if (request.SuccessfulWebRequest()) { WikipediaSearcher s = null; // create article crawler ArticleCrawler c = new ArticleCrawler(Webpages, Forbidden); Thread crawler = new Thread(() => c.Start()); crawler.Start(); crawler.Priority = ThreadPriority.Normal; // create searcher Console.WriteLine("Creating Searcher...."); Thread searcher = new Thread(() => {s = new WikipediaSearcher(Webpages, StartPageName, FinishPageName, Forbidden, "BFS");}); searcher.Start(); searcher.Priority = ThreadPriority.AboveNormal; // wait for searcher to complete searcher.Join(); // try to stop crawler try { crawler.Abort(); } catch (PlatformNotSupportedException) { // TODO: investigate this further Console.WriteLine("System does not support abort of threads. Please terminate manually"); } } }
// constructor // note: must specify which search type to use public WikipediaSearcher(ArticleCollection Webpages, string Start, string Finish, ForbiddenLinks l, string searchType) { StartPage = Start; FinishPage = Finish; Articles = Webpages; ForbiddenLinksCollection = l; // depth first if (searchType == "DFS") { watch.Start(); SearchDFS(); watch.Stop(); Console.WriteLine(watch.ElapsedMilliseconds); } // breadth first else if (searchType == "BFS") { watch.Start(); SearchBFS(); watch.Stop(); Console.WriteLine(watch.ElapsedMilliseconds + "ms"); } else { Console.WriteLine("Please enter either DFS or BFS to indicate which search type you prefer."); } }
private void LoadControl() { SliderTopic result = new SliderTopic(); TabTopicDisplayCollection listTabTopicDisplay = TabTopicDisplayCollection.GetTabTopicDisplayCollection(); var sliderTopic = listTabTopicDisplay.Where(item => item.DataId == Portlet.PortletInstance.Id).FirstOrDefault(); string topicid1; string topicid2; if (sliderTopic != null) { result.TopicId1 = sliderTopic.TopicId; topicid1 = result.TopicId1.ToString(); Topic topic = TopicCollection.GetTopic(topicid1 != "" ? topicid1 : ""); result.TopicName1 = topic.Name; result.SliderArticleList = ArticleCollection.GetArticleCollection(sliderTopic.TopicId.ToString(), 0, sliderTopic.NumberDisplay); result.SliderArticleList.ForEach(d => d.Name = d.GetDescription().Replace("\"", "\\\"")); } var secondTopic = listTabTopicDisplay.Where(item => item.DataId == Portlet.PortletInstance.Id).Skip(1).Take(1).SingleOrDefault(); if (secondTopic != null) { result.TopicId2 = secondTopic.TopicId; topicid2 = result.TopicId2.ToString(); Topic topic = TopicCollection.GetTopic(topicid2 != "" ? topicid2 : ""); result.TopicName2 = topic.Name; result.SecondArticleList = ArticleCollection.GetArticleCollection(secondTopic.TopicId.ToString(), 0, secondTopic.NumberDisplay).Take(3).ToList(); } var js = new JavaScriptSerializer(); ListArticle = js.Serialize(result); }
public IActionResult ReadXml() { XmlDocument xmlDocOnline = new XmlDocument(); xmlDocOnline.Load("https://www.tungsten-network.com/rss-resource-library/"); XmlNodeList nodeList = xmlDocOnline .DocumentElement .SelectNodes("//item/category[contains(.,'Friction')]/.."); List <XmlNode> xmlNodesList = new List <XmlNode>(); ArticleCollection articleCollection = new ArticleCollection(); articleCollection.Collection = new List <Article>(); foreach (XmlNode node in nodeList) { var heading = node["title"].InnerText; var date = node["pubDate"].InnerText; var enclosure = node["enclosure"].Attributes["url"].Value; var category = node["category"].InnerText; var article = new Article() { Heading = heading, Date = date, ImageUrl = enclosure, Category = category }; articleCollection.Collection.Add(article); } return(View(articleCollection)); }
public IEnumerable<Article> FilterArticles(string category) { IQueryable<Article> query = ArticleCollection.AsQueryable(); if (!string.IsNullOrWhiteSpace(category)) query = query.Where(x => x.Category == category); return query; }
//Thống kê truy cập bài viết public static List <Article> ThongKeTruyCapBaiViet(string tungay, string denngay) { PSCPortal.CMS.ArticleCollection ArticleList = ArticleCollection.GetArticleViewTimeCollectionPublish(); List <Article> result = new List <Article>(); Guid subId = SessionHelper.GetSession(SessionKey.SubDomain) == string.Empty ? Guid.Empty : new Guid(SessionHelper.GetSession(SessionKey.SubDomain)); if (subId == Guid.Empty) { result = ArticleList.ToList(); } else { result = new List <Article>(); PSCPortal.Engine.SubDomain subDomain = new PSCPortal.Engine.SubDomain { Id = subId }; nameWorksheet = PSCPortal.Engine.SubDomain.GetSubById(subId.ToString()).Description; PageCollection listPage = subDomain.GetPagesBelongTo(); foreach (var item in listPage) { foreach (var article in ArticleList.Where(ar => ar.PageId == item.Id)) { result.Add(article); } } } if (tungay != string.Empty && denngay != string.Empty) { IFormatProvider provider = new System.Globalization.CultureInfo("en-CA", true); DateTime startDate = DateTime.Parse(tungay, provider, System.Globalization.DateTimeStyles.NoCurrentDateDefault); DateTime endDate = DateTime.Parse(denngay, provider, System.Globalization.DateTimeStyles.NoCurrentDateDefault); result = result.Where(ar => ar.CreatedDate >= startDate && ar.CreatedDate <= endDate).ToList <Article>(); } return(result); }
protected override void OnStart() { ArticleCollection article = new ArticleCollection(); bool isActivity = App.Database.GetItems().Any(x => x.IsActivity); if (isActivity) { Theme theme = (Theme)Enum.Parse(typeof(Theme), App.Database.GetItems().FirstOrDefault(x => x.IsActivity).Theme); Preferences.Set("theme", theme.ToString()); ICollection <ResourceDictionary> mergedDictionaries = Application.Current.Resources.MergedDictionaries; if (mergedDictionaries != null) { mergedDictionaries.Clear(); switch (theme) { case Theme.Dark: mergedDictionaries.Add(new DarkTheme()); break; case Theme.Light: default: mergedDictionaries.Add(new LightTheme()); break; } } } }
protected override void PopulateRss(string channelName, string userName) { string topicId = HttpContext.Current.Request.QueryString["TopicId"]; Rss.Version = "2.0"; Rss.Channel = new RssChannel(); //Rss.Channel.Generator = "Trường Đại Học Kinh Tế Luật - UEL"; Rss.Channel.Link = System.Configuration.ConfigurationManager.AppSettings["MainDomainName"]; Rss.Channel.Copyright = "Trường Đại Học Đà Lạt - DLU"; //Rss.Channel.Description = "Định dạng theo tiêu chuẩn XML"; Rss.Channel.Title = "Tin mới nhất - Trường Đại Học Đà Lạt"; Rss.Channel.PubDate = string.Format("{0:dddd, MMMM d, yyyy HH:mm:ss}", DateTime.Now); Rss.Channel.WebMaster = "*****@*****.**"; //Rss.Channel.LastBuildDate = string.Format("{0:dddd, MMMM d, yyyy HH:mm:ss}", DateTime.Now); var list = ArticleCollection.GetArticleCollection(new Topic { Id = new Guid(topicId) }); Rss.Channel.Items = new List <RssItem>(); foreach (var item in list) { var rss = new RssItem(); rss.Title = item.Title; rss.Description = item.GetDescription(); rss.PubDate = string.Format("{0:dddd, MMMM d, yyyy HH:mm:ss}", item.CreatedDate); rss.Link = System.Configuration.ConfigurationManager.AppSettings["MainDomainName"] + "/?ArticleId=" + item.Id; Rss.Channel.Items.Add(rss); } }
public static string GetArticleNoBelongTopicPrimary(int startIndex, int maximumRows, string sortExpressions) { ArticleCollection articles = ArticleCollection.GetArticlesNoBelongTopicPrimary(); System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer(); return(js.Serialize(articles.GetSegment(startIndex, maximumRows, sortExpressions))); }
public static string ArticleSearch(string ArticleTitle, int startIndex, int maximumRows, string sortExpressions) { ArticleCollection ArticleListSearch = new ArticleCollection(); Dictionary <string, object> dic = new Dictionary <string, object>(); ArticleList = ArticleCollection.GetArticleBySearch(ArticleTitle); Guid subId = SessionHelper.GetSession(SessionKey.SubDomain) == string.Empty ? Guid.Empty : new Guid(SessionHelper.GetSession(SessionKey.SubDomain)); if (subId == Guid.Empty) { ArticleListSearch = ArticleList; } else { PSCPortal.Engine.SubDomain subDomain = new PSCPortal.Engine.SubDomain { Id = subId }; PSCPortal.Engine.PageCollection listPage = subDomain.GetPagesBelongTo(); foreach (var item in listPage) { foreach (var article in ArticleList.Where(ar => ar.PageId == item.Id)) { ArticleListSearch.Add(article); } } } dic.Add("Data", ArticleListSearch.GetSegment(startIndex, maximumRows, sortExpressions)); dic.Add("Count", ArticleListSearch.Count); System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer(); return(js.Serialize(dic)); }
public string GetArticleCollection(string topicId, int startIndex, int size) { List <Article> resultList = ArticleCollection.GetArticleCollection(topicId, startIndex, size); JavaScriptSerializer js = new JavaScriptSerializer(); return(js.Serialize(resultList)); }
public ArticlesController(IArticleModel article, ITagCollection tagColl) { _artColl = new ArticleCollection(); _articles = new List <Models.ArticleModel>(); _tags = new List <TagDto>(); _article = article; _tagColl = tagColl; }
public string SearchAndPaging(string strQuery, string index) { string result = string.Empty; try { List <SearchArticle> searchArticleList = new List <SearchArticle>(); PSCPortal.CMS.ArticleCollection ArticleList = ArticleCollection.GetArticleCollectionPublish(); string nameSub = Libs.Ultility.GetSubDomain() == string.Empty ? "HomePage" : Libs.Ultility.GetSubDomain(); SubDomain subDomain = PSCPortal.Engine.SubDomain.GetSubByName(nameSub); PageCollection pagesBelongTo = subDomain.GetPagesBelongTo(); string strId = string.Empty; foreach (var page in pagesBelongTo) { foreach (var ar in ArticleList.Where(ar => ar.PageId == page.Id)) { strId += ar.Id + " OR "; } if (strId.Length > 0) { strId = strId.Remove(strId.Length - 3, 3); } } int pageIndex = Int32.Parse(index); string strSearch = " ArticleDetail:(" + strQuery + ") AND ArticleId:" + "( " + strId + " )"; Lucene.Net.Index.IndexReader reader = Lucene.Net.Index.IndexReader.Open(Server.MapPath(System.Configuration.ConfigurationManager.AppSettings["IndexingArticle"])); Lucene.Net.QueryParsers.QueryParser parser = new Lucene.Net.QueryParsers.QueryParser("ArticleDetail", new Lucene.Net.Analysis.Standard.StandardAnalyzer()); Lucene.Net.Search.Query query = parser.Parse(strSearch); Lucene.Net.Search.IndexSearcher searcher = new Lucene.Net.Search.IndexSearcher(reader); Lucene.Net.Search.Hits hits = searcher.Search(query); Lucene.Net.Highlight.QueryScorer score = new Lucene.Net.Highlight.QueryScorer(query); Lucene.Net.Highlight.SimpleHTMLFormatter formater = new Lucene.Net.Highlight.SimpleHTMLFormatter("<span class='Highlight'>", "</span>"); Lucene.Net.Highlight.Highlighter highlighter = new Lucene.Net.Highlight.Highlighter(formater, score); result += hits.Length() + "_" + "<div class='blog_news'><div class='topic_news_title1'><div class='topic_news_title'><a href='#'>Kết quả tìm thấy: " + hits.Length() + "</a></div></div>"; result += "<div class='ct_topic_l'><div class='ct_topic_r1'>"; for (int i = pageIndex * 20 - 20; i < pageIndex * 20 && i < hits.Length(); i++) { string detail = hits.Doc(i).Get("ArticleDetail"); Lucene.Net.Analysis.TokenStream ts = (new Lucene.Net.Analysis.Standard.StandardAnalyzer()).TokenStream("ArticleDetail", new System.IO.StringReader(detail)); SearchArticle searchArticle = new SearchArticle(); searchArticle.Id = hits.Doc(i).Get("ArticleId");; searchArticle.Title = hits.Doc(i).Get("ArticleTitle"); searchArticle.Highligth = highlighter.GetBestFragment(ts, detail); searchArticleList.Add(searchArticle); } reader.Close(); JavaScriptSerializer serializer = new JavaScriptSerializer(); Dictionary <string, object> resultDic = new Dictionary <string, object>(); resultDic["Count"] = hits.Length(); resultDic["Data"] = searchArticleList; result = serializer.Serialize(resultDic); } catch (Exception e) { } return(result); }
public static string GetArticleCommentNewList(string topicId, int startIndex, int maximumRows, string sortExpressions) { Guid idTopic = new Guid(topicId); Topic topic = (Topic)TopicList.Search(o => ((Topic)o).Id == idTopic); ArticleListCommentNew = ArticleCollection.GetArticleCollectionPublishCommentNew(topic); System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer(); return(js.Serialize(ArticleListCommentNew.GetSegment(startIndex, maximumRows, sortExpressions))); }
public HomeController(ILogger <HomeController> logger, IArticleCollection articleColl, ContactCollection _contactCollection) { _logger = logger; _coll = new ArticleCollection(); _articles = new List <Models.ArticleModel>(); _articlelogic = new techburst_BLL.ArticleModel(); _articleColl = articleColl; contactCollection = _contactCollection; }
public ArticleCollection GetArticlesBelongTo() { PSCPortal.Framework.Database database = new PSCPortal.Framework.Database("PSCPortalConnectionString"); ArticleCollection result = new ArticleCollection(); using (DbConnection connection = database.GetConnection()) { DbCommand command = database.GetCommand(connection); #region SubDomainId DbParameter prId = database.GetParameter(System.Data.DbType.Guid, "@SubDomainId", _id); command.Parameters.Add(prId); #endregion command.CommandText = @"SELECT a.[ArticleId], [ArticleName], [ArticleTitle], b.[IsCheck], s.[Name] as SubDomainFromName FROM dbo.[Article] a inner join SubDomainInArticle b on a.ArticleId = b.ArticleNewId inner join SubDomain s on b.SubDomainFromId = s.Id WHERE b.SubDomainToId = @SubDomainId AND b.IsCheck = 'false'" ; command.CommandType = System.Data.CommandType.Text; connection.Open(); DbDataReader reader = command.ExecuteReader(); while (reader.Read()) { Article item = new Article(); if (!reader.IsDBNull(reader.GetOrdinal("ArticleId"))) { item.Id = new Guid(reader["ArticleId"].ToString()); } if (!reader.IsDBNull(reader.GetOrdinal("ArticleName"))) { item.Name = (string)reader["ArticleName"].ToString(); } if (!reader.IsDBNull(reader.GetOrdinal("ArticleTitle"))) { item.Title = (string)reader["ArticleTitle"].ToString(); } if (!reader.IsDBNull(reader.GetOrdinal("SubDomainFromName"))) { item.SubDomainFromName = (string)reader["SubDomainFromName"]; } if (!reader.IsDBNull(reader.GetOrdinal("IsCheck"))) { item.IsCheck = (bool)reader["IsCheck"]; } result.Add(item); } } return(result); }
public CollectionControl(string name, ArticleCollection other) { InitializeComponent(); collection.Name = other.Name; foreach (Article article in other.Articles) { collection.Articles.Add(article); } lvCollection.ItemsSource = collection.Articles; }
public async Task <ArticleCollection> GetArticleAsync(string lang) { var col = new ArticleCollection() { TopRanked = await GetTopRanked(lang), Relevant = await GetRelevant(lang), Recent = await GetRecent(lang) }; return(col); }
public static void IndexingArticle() { ArticleCollection articleList = ArticleCollection.GetArticleCollection(); Lucene.Net.Index.IndexWriter lwriter = new Lucene.Net.Index.IndexWriter(System.Web.HttpContext.Current.Server.MapPath(System.Configuration.ConfigurationManager.AppSettings["IndexingArticle"]), new Lucene.Net.Analysis.Standard.StandardAnalyzer(), true); lwriter.Close(); foreach (Article item in articleList) { Libs.Ultility.IndexingArticle(item); } }
//ugly overload, fragile, too much duplicated code :( public static void UpdateGroupArticles(string server, Newsgroup newsGroup) { if (newsGroup.Articles == null) { NewsConnection connection = new NewsConnection(); connection.Connect(server); ArticleCollection articles = connection.GetArticleHeaders(newsGroup); connection.Disconnect(); newsGroup.Articles = articles; } }
// constructor public WikipediaWebRequest(string requested_page, ArticleCollection Webpages, ForbiddenLinks l, Webpage parent) { ParentPage = parent; RequestedPage = requested_page.Replace(' ', '_'); if (!RequestedPage.Contains("wiki/")) { RequestedPage.Insert(0, "wiki/"); } Articles = Webpages; ForbiddenLinkCollection = l; Controller(); }
public void InitializeCollections() { System.IO.Directory.CreateDirectory(@"C:\Articles\"); System.IO.Directory.CreateDirectory(@"C:\Articles\exports\"); System.IO.Directory.CreateDirectory(@"C:\Articles\collections\"); string[] filePaths = Directory.GetFiles(@"C:\Articles\collections\", "*.xml"); foreach (string fileName in filePaths) { ArticleCollection collection = DeSerializeCollection <ArticleCollection>(fileName); if (collection != null) { TabItem tab = new TabItem { Content = new CollectionControl(collection.Name, collection), Header = collection.Name }; tabControl.Items.Add(tab); tabControl.SelectedItem = tab; CollectionControl control = (CollectionControl)tabControl.SelectedContent; if (control != null) { control.lvCollection.Items.Refresh(); } } } ArticleCollection src = DeSerializeCollection <ArticleCollection>(@"C:\Articles\source.xml"); if (src != null) { foreach (Article article in src.Articles) { sourceCollection.Articles.Add(article); } lvSource.ItemsSource = sourceCollection.Articles; lvSource.Items.Refresh(); if (lvSource.Items.Count != 0) { lvSource.SelectedItem = lvSource.Items[0]; } } if (sourceCollection.Articles.Count == 0) { sourceCollection = new ArticleCollection(); lvSource.ItemsSource = sourceCollection.Articles; lvSource.Items.Refresh(); if (lvSource.Items.Count != 0) { lvSource.SelectedItem = lvSource.Items[0]; } } lvSource.ItemsSource = sourceCollection.Articles; lvSource.Items.Refresh(); }
// GET: Article/Details/5 public ActionResult Details(int?id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } ArticleCollection articles = _db.ArticleCollections.Find(id); if (articles == null) { return(HttpNotFound()); } return(View(articles)); }
/// <summary> /// Returns all articles found in database. /// </summary> /// <returns></returns> public String GetJSONArticles() { List <Article> articles = SqlFuDAL.FindObjectsByType <Article>(); ArticleCollection articleCol = new ArticleCollection(); articleCol.Articles = articles; String json = JsonConvert.SerializeObject(articleCol); JsonResult jsonData = new JsonResult { Data = JsonConvert.DeserializeObject(json) }; return(jsonData.Data.ToString()); }
public static void Main(string[] args) { IArticleCollection collection = new ArticleCollection(); try { collection.Import(@"D:\Dropbox\MAPR Michiel\Project\hugo_claus.xml"); collection.Print(); Console.ForegroundColor = ConsoleColor.Green; Console.Out.Write("[SUCCESS]"); Console.ResetColor(); } catch (Exception e) { PrintError(e.Message); } Console.ReadLine(); }
//Article public ActionResult Edit(int?id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } var data = _db.ArticleCollections.Where(s => s.ArticleCollectionID == id).FirstOrDefault(); ArticleCollection articles = _db.ArticleCollections.Find(id); if (articles == null) { return(HttpNotFound()); } return(View(data)); }
public void ArticleSerializationTest() { var articles = new ArticleCollection(); var article1 = new Article() { ArticleID = 1, RawText = "Text of 1. article", ArticleImages = new ArticleImageCollection() }; article1.ArticleImages.AddImage(new ArticleImage() { ArticleImageID = 1, Path = "articleAssets/1/images/1.jpg" }); article1.ArticleImages.AddImage(new ArticleImage() { ArticleImageID = 2, Path = "articleAssets/1/images/2.jpg" }); articles.AddArticle(article1); var article2 = new Article() { ArticleID = 2, RawText = "Text of 2. article", ArticleImages = new ArticleImageCollection() }; article2.ArticleImages.AddImage(new ArticleImage() { ArticleImageID = 1, Path = "articleAssets/2/images/1.jpg" }); article2.ArticleImages.AddImage(new ArticleImage() { ArticleImageID = 2, Path = "articleAssets/2/images/2.jpg" }); articles.AddArticle(article2); var json = JsonConvert.SerializeObject(articles); Assert.True(json.Contains(article1.RawText)); Assert.True(json.Contains("1.jpg")); Assert.True(json.Contains("ArticleID")); }
public void InheritedListSerialize() { var a1 = new Article("a1"); var a2 = new Article("a2"); var articles1 = new ArticleCollection(); articles1.Add(a1); articles1.Add(a2); string jsonText = JavaScriptConvert.SerializeObject(articles1); var articles2 = JavaScriptConvert.DeserializeObject <ArticleCollection>(jsonText); Assert.AreEqual(articles1.Count, articles2.Count); Assert.AreEqual(articles1[0].Name, articles2[0].Name); }
public String GetJSONArticle(int id) { Article article = SqlFuDAL.FindArticleById(id); ArticleCollection articleCol = new ArticleCollection(); articleCol.Articles = new List <Article>() { article }; String json = JsonConvert.SerializeObject(articleCol); JsonResult jsonData = new JsonResult { Data = JsonConvert.DeserializeObject(json) }; return(jsonData.Data.ToString()); }
public ActionResult Edit(ArticleCollection _articleCol, HttpPostedFileBase file) //public ActionResult Edit([Bind(Include = "ArticleId,UserId,Title,ArticleImage,Description,Publication_date,Createa_at,Updated_at,Gallery,CategoryId,CityId")] Article _article, HttpPostedFileBase file) { if (ModelState.IsValid) { try { string pic = null; if (file != null) { pic = System.IO.Path.GetFileName(file.FileName); _articleCol.CollectionImage = pic; string path = System.IO.Path.Combine(Server.MapPath("~/Images/Article/"), _articleCol.CollectionImage); ViewBag.Message = "File uploaded successfully."; // file is uploaded file.SaveAs(path); } _articleCol.CollectionImage = file != null ? pic : _articleCol.CollectionImage; } catch (DataException) { ModelState.AddModelError("", "Unable to save changes"); } var data = _db.ArticleCollections.Find(_articleCol.ArticleCollectionID); data.ArticleCollectionTitle = _articleCol.ArticleCollectionTitle; data.ArticleCollectionDetails = _articleCol.ArticleCollectionDetails; data.ArticleCollectionDate = _articleCol.ArticleCollectionDate; data.UpdatedCol_at = DateTime.Now; data.UserId = User.Identity.GetUserId(); data.CollectionImage = _articleCol.CollectionImage; data.ArticleColOwner = _articleCol.ArticleColOwner; _db.Entry(data).State = EntityState.Modified; _db.SaveChanges(); // return Json(_article); return(RedirectToAction("Index")); } var dataEdit = _db.ArticleCollections.Where(s => s.ArticleCollectionID == _articleCol.ArticleCollectionID).FirstOrDefault(); return(View(dataEdit)); }
/// <summary> /// query article with condition. /// </summary> /// <param name="istop"></param> /// <param name="iscommand"></param> /// <returns></returns> public static ArticleCollection GetList(bool istop, bool iscommend) { bool bIsTop = false; bool bIsCommend = false; if (istop) { bIsTop = istop; } if (iscommend) { bIsCommend = iscommend; } ArticleCollection tempList = new ArticleCollection(); string sql = "select * from T_Article where IsTop=?IsTop and IsCommend=?IsCommend"; MySqlParameter[] parms = { new MySqlParameter("?IsTop", MySqlDbType.Bit), new MySqlParameter("?IsCommend", MySqlDbType.Bit) }; parms[0].Value = bIsTop; parms[0].Value = bIsCommend; MySqlDataReader reader = DbHelper.ExecuteDataReader(sql, parms); if (reader.HasRows) { tempList = new ArticleCollection(); while (reader.Read()) { tempList.Add(FillDataRecord(reader)); } } reader.Close(); return tempList; }
private bool downloadArticleHeaders() { string server = txtServer.Text; try { // Temporary connection to the server. NewsConnection connection = new NewsConnection(); connection.Connect(server); Newsgroup selectedGroup = (Newsgroup)lstGroups.SelectedItem; if (chkFilterArticles.Checked) { int articleLimit; int.TryParse(txtGetNumber.Text, out articleLimit); articleHeaders = connection.GetArticleHeaders(selectedGroup, articleLimit); } else { articleHeaders = connection.GetArticleHeaders(selectedGroup); } connection.Disconnect(); if (!groupHistory.ContainsKey(selectedGroup)) { groupHistory.Add(selectedGroup, articleHeaders); } return true; } catch (Exception ex) { MessageBox.Show(ex.Message, "Download Newsgroups", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return false; } }
public static ArticleCollection GetTop() { ArticleCollection list = new ArticleCollection(); string sql = @"SELECT * FROM t_article ORDER BY art_id DESC LIMIT 3;"; MySqlDataReader reader = DbHelper.ExecuteDataReader(sql); if (reader.HasRows) { while(reader.Read()) { list.Add(FillDataRecord(reader)); } } reader.Close(); return list; }
public ArticleCollection Process(ClassRepository rep) { ArticleCollection artc = new ArticleCollection(); List<Feature> features = new List<Feature>(); foreach (KeyValuePair<string, Feature> kv in rep) features.Add(kv.Value); // Sort so classes are processed first features.Sort(delegate(Feature a, Feature b) { if ((a is SubSystem) && !(b is SubSystem)) return -1; else if ((b is SubSystem) && !(a is SubSystem)) return 1; else if ((a is Class) && !(b is Class)) return 1; else if ((b is Class) && !(a is Class)) return -1; else return a.GetType().Name.CompareTo(b.GetType().Name); }); //var vocabArticle = new MohawkCollege.EHR.gpmr.Pipeline.Renderer.Deki.Article.Article() //{ // Title = "Vocabulary", // Children = new ArticleCollection() //}; //vocabArticle.Children.Add(new Article.Article() { Title = "Code Systems" }); //vocabArticle.Children.Add(new Article.Article() { Title = "Concept Domains" }); //vocabArticle.Children.Add(new Article.Article() { Title = "Value Sets" }); //artc.Add(vocabArticle); WaitThreadPool wtp = new WaitThreadPool(); // A thread that does the doohickey thing Thread doohickeyThread = new Thread((ThreadStart)delegate() { string[] hickeythings = { "|", "/", "-", "\\" }; int hickeyThingCount = 0; try { while (true) { int cPosX = Console.CursorLeft, cPosY = Console.CursorTop; Console.SetCursorPosition(1, cPosY); Console.Write(hickeythings[hickeyThingCount++ % hickeythings.Length]); Console.SetCursorPosition(cPosX, cPosY); Thread.Sleep(1000); } } catch { } }); doohickeyThread.Start(); // Loop through each feature foreach (Feature f in features) { // Find the feature template FeatureTemplate ftpl = NonParameterizedTemplate.Spawn(FindTemplate(f.GetType().FullName, f) as NonParameterizedTemplate, this, f) as FeatureTemplate; if (ftpl == null) System.Diagnostics.Trace.WriteLine(string.Format("Feature '{0}' won't be published as no feature template could be located", f.Name), "warn"); else if(f.Annotations.Find(o=>o is SuppressBrowseAnnotation) != null) System.Diagnostics.Trace.WriteLine(String.Format("Feature '{0}' won't be published as a SuppressBrowse annotation was found", f.Name), "warn"); else if(ftpl.NewPage) { System.Diagnostics.Trace.WriteLine(string.Format("Queueing ({1}) '{0}'...", f.Name, f.GetType().Name), "debug"); // Create a new worker Worker w = new Worker(); w.ArticleCollection = artc; w.FeatureTemplate = ftpl; w.OnComplete += delegate(object sender, EventArgs e) { Worker wrkr = sender as Worker; System.Diagnostics.Trace.WriteLine(String.Format("Rendered ({1}) '{0}'...", (wrkr.FeatureTemplate.Context as Feature).Name, wrkr.FeatureTemplate.Context.GetType().Name), "debug"); }; wtp.QueueUserWorkItem(w.Start); } } System.Diagnostics.Trace.WriteLine("Waiting for work items to complete...", "debug"); wtp.WaitOne(); doohickeyThread.Abort(); ArticleCollection retVal = new ArticleCollection(); Article.Article MasterTOC = new MohawkCollege.EHR.gpmr.Pipeline.Renderer.Deki.Article.Article(); MasterTOC.Children = artc; System.Diagnostics.Trace.WriteLine("Creating Table of Contents...", "information"); PrepareTOC(MasterTOC); MasterTOC.Children = null; artc.Add(MasterTOC); return artc; }
/// <summary> /// Downloads up to maxHeaders article headers from the given group. The latest ones are chosen. /// Currently, only some of the header fields are downloaded: id, from, date, subject, lines. /// The body is not downloaded. Use GetArticle to download an article's body text. /// </summary> /// <param name="group">Newsgroup whose articles headers will be downloaded.</param> /// <param name="maxHeaders">Maximum number of article headers to download. The latest ones are chosen.</param> /// <returns>A collection of Article objects contained in the given newsgroup. The articles' body /// text is not downloaded. Use GetArticle to download an article's body text.</returns> public ArticleCollection GetArticleHeaders(Newsgroup group, int maxHeaders) { string message; string response; ArticleCollection articles = null; // Get the article numbers of the first and last articles in the group, and an // estimate of the number of articles on file in the group. try { message = "GROUP " + group.Name + "\r\n"; Write(message); response = Response(); if (response.Substring(0, 3) != "211") { throw new NntpException(response); } char[] seps = { ' ' }; string[] values = response.Split(seps); int start = Int32.Parse(values[2]); int end = Int32.Parse(values[3]); int estimatedArticleCount = end - start; if (estimatedArticleCount < 0) estimatedArticleCount = 100; // Was a maximum specified? if (maxHeaders != -1 && start + maxHeaders < end) { start = end - maxHeaders; } articles = new ArticleCollection(estimatedArticleCount); // Create a collection of Article objects, storing just the heading information // into them. DateTime date; string from, subject, id; int numLines; bool allFieldsObtained; int sequenceNum; for (sequenceNum = start; sequenceNum < end; ++sequenceNum) { message = "HEAD " + sequenceNum + "\r\n"; Write(message); response = Response(); if (response.Substring(0, 3) == "423") { // 423 - No such article number in this group. continue; } // 221 means article retrieved, head follows. if (response.Substring(0, 3) != "221") { throw new NntpException(response); } date = DateTime.MinValue; from = subject = id = ""; numLines = -1; allFieldsObtained = false; response = Response(); while (response != ".\r\n" && response != ".\n" && !allFieldsObtained) { // Find the delimiter--usually a colon but seems to be equals sign sometimes. // If neither is found then move on. int delimiterIdx; delimiterIdx = response.IndexOf(':'); if (delimiterIdx == -1) delimiterIdx = response.IndexOf('='); if (delimiterIdx == -1) { response = Response(); continue; } string headerFieldName = response.Substring(0, delimiterIdx).ToLower(); string headerFieldValue = response.Substring(delimiterIdx + 2); headerFieldValue = headerFieldValue.Replace("\r\n", ""); switch (headerFieldName) { case "message-id": id = headerFieldValue; break; case "from": from = headerFieldValue; break; case "date": DateTime.TryParse(headerFieldValue, out date); break; case "subject": subject = headerFieldValue; break; case "lines": int.TryParse(headerFieldValue, out numLines); break; default: break; } allFieldsObtained = (id != "" && from != "" && date != DateTime.MinValue && subject != "" && numLines != -1); if (allFieldsObtained) { // Finish getting rest of header but don't go through the switch. response = Response(); while (response != ".\r\n" && response != ".\n") { response = Response(); } } else { response = Response(); } } Article newArticle; newArticle = new Article(id, sequenceNum, from, date, subject, numLines); articles.Add(newArticle); } } catch { // Ideally, I want to let this exception raise to the UI but we don't covered // exception handling until later, so just swallow it for now. } return articles; }
/// <summary> /// query article, all data /// </summary> /// <param name="ac_id"></param> /// <param name="startRowIndex"></param> /// <param name="maximumRows"></param> /// <param name="orderBy"></param> /// <returns>ArticleCollection include all data</returns> public static ArticleCollection GetList(int ac_id, int startRowIndex, int maximumRows) { int iStartRowIndex = -1; int iMaximumRows = -1; if (startRowIndex > 0 && maximumRows > 0) { iStartRowIndex = startRowIndex; iMaximumRows = maximumRows; } ArticleCollection tempList = new ArticleCollection(); string sql = @"SELECT * FROM ( select *, (select ifnull(sum(1) + 1, 1) from t_article where (?ac_id=0 or ac_id=?ac_id) and art_id > a.art_id) as row_rank from t_article a where ?ac_id=0 or ac_id in (select ac_id from (select ac_id from t_articleclass where ac_id=?ac_id union all select p.ac_id from t_articleclass p inner join (select ac_id from t_articleclass where ac_id=?ac_id) t on p.parent_id = t.ac_id) as temp) order by art_id desc ) as ArticleWithRowNumbers where ((row_rank between ?start_row_index AND ?start_row_index + ?maximum_rows - 1) OR ?start_row_index = -1 OR ?maximum_rows = -1)"; MySqlParameter[] parms = { new MySqlParameter("?ac_id",MySqlDbType.Int32), new MySqlParameter("?start_row_index",MySqlDbType.Int32), new MySqlParameter("?maximum_rows",MySqlDbType.Int32) }; parms[0].Value = ac_id; parms[1].Value = iStartRowIndex; parms[2].Value = iMaximumRows; MySqlDataReader myReader = DbHelper.ExecuteDataReader(sql, parms); if (myReader.HasRows) { tempList = new ArticleCollection(); while(myReader.Read()) { tempList.Add(FillDataRecord(myReader)); } } myReader.Close(); return tempList; }