Example #1
0
        public RssFeed Get()
        {
            var items = from v in _repository.Query()
                        .OrderByDescending(x => x.Created)
                        .Take(10)
                        .AsEnumerable()
                        select new RssItem()
                                   {
                                      Guid = new RssGuid(){Value = v.Id, IsPermaLink = true},
                                      Description = v.ToString(),
                                      Link = _urlRegistry.UrlFor(new GetVideoRequest(){Id = v.Id}).ToAbsoluteUrl(),
                                      PublishDate = v.Created.ToString("r"),
                                      Title = v.Title
                                   };

            var feed = new RssFeed()
                           {
                               Version = "2.0",
                               Xmlns = new XmlSerializerNamespaces(),
                               Channel = new RssChannel()
                                             {
                                                 Copyright = "© 2010 by NineCollective. All rights reserved.",
                                                 Description = "Just some sweet vids bro, what you mad?",
                                                 Language = "en-US",
                                                 Title = "Sweet Vids",
                                                 Link = _urlRegistry.UrlFor<RssAction>(x => x.Get()).ToAbsoluteUrl(),
                                                 Items = items.ToArray()
                                             }
                           };
            return feed;
        }
Example #2
0
        /// <summary>
        ///     Return a RssFeed object using the XDocument data
        /// </summary>
        /// <param name="doc"></param>
        /// <returns></returns>
        public override RssFeed LoadFeed(XDocument doc)
        {
            var feed = new RssFeed();
            XNamespace defaultNamespace = string.Empty;

            SetMediaImage(feed, doc);
            if (doc.Root != null)
            {
                defaultNamespace = doc.Root.GetDefaultNamespace();

                feed.Description = doc.Root.Element("channel").GetSafeElementString("description");
                feed.Items = new ObservableCollection<RssItem>();
                feed.Link = doc.Root.Element("channel").GetSafeElementString("link");
            }

            foreach (XElement item in doc.Descendants(defaultNamespace + "item"))
            {
                RssItem rssItem = ParseItem(item);
                feed.Items.Add(rssItem);
            }

            RssItem lastItem = feed.Items.OrderByDescending(i => i.PublishDate).FirstOrDefault();
            if (lastItem != null)
                feed.LastBuildDate = lastItem.PublishDate;

            return feed;
        }
Example #3
0
 public static void UpdateTimes(RssFeed feed)
 {
     XDocument xml = XDocument.Load(RssDataPath);
     var feedElem = xml.Descendants("Feed").FirstOrDefault(x => x.Element("Url").Value == feed.Url);
     if (feedElem != null)
     {
         feedElem.Element("LastUpdated").Value = feed.LastUpdated;
     }
     xml.Save(RssDataPath);
 }
Example #4
0
        /// <summary>
        ///     Return a RssFeed object using the XDocument data
        /// </summary>
        /// <param name="doc"></param>
        /// <returns></returns>
        public override RssFeed LoadFeed(XDocument doc)
        {
            var feed = new RssFeed();

            SetMediaImage(feed, doc);
            feed.Description = doc.Root.GetSafeElementString("summary");
            feed.Items = new ObservableCollection<RssItem>();
            feed.LastBuildDate = doc.Root.GetSafeElementDate("updated");
            feed.Link = doc.Root.GetLink("self");

            if (doc.Root == null) return feed;
            foreach (XElement item in doc.Root.Elements(doc.Root.GetDefaultNamespace() + "entry"))
            {
                RssItem rssItem = ParseItem(item);
                feed.Items.Add(rssItem);
            }

            return feed;
        }
Example #5
0
        /// <summary>
        ///     Set the feed's image with the image extracted from the XDocument
        /// </summary>
        /// <param name="feed"></param>
        /// <param name="doc"></param>
        public void SetMediaImage(RssFeed feed, XDocument doc)
        {
            if (doc.Root != null)
            {
                XElement image = doc.Root.Descendants(NsItunes + "image").FirstOrDefault();
                if (image != null)
                {
                    XAttribute xAttribute = image.Attribute("href");
                    if (xAttribute != null) feed.ImageUri = new Uri(xAttribute.Value);
                    return;
                }
            }

            XElement thumbnail = doc.Element(NsMedia + "thumbnail");
            if (thumbnail != null)
            {
                feed.ImageUri = new Uri(thumbnail.Value);
                return;
            }

            feed.ImageUri = new Uri("/Images/DefaultFeedIcon.jpg", UriKind.Relative);
        }
Example #6
0
    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);

        RssFeed feed = new RssFeed();

        feed.Channel.Link = new Uri("http://blag.Jiyuu.org/");
        feed.Channel.Title = "אנימה בלאג";
        feed.Channel.Description = "סיכום הפוסטים האחרונים שאונדקסו בבלאג";

        List<BlogPost> posts = AggregationManager.GetPosts(null, null).Take(15).ToList();

        RssItem item;
        foreach (BlogPost post in posts)
        {
            item = new RssItem();
            item.Title = post.Title;
            item.Link = new Uri(post.Link);
            item.Description = post.Summary;

            Argotic.Extensions.Core.SiteSummaryContentSyndicationExtension contentExt = new Argotic.Extensions.Core.SiteSummaryContentSyndicationExtension();
            contentExt.Context.Encoded = "";// HttpUtility.HtmlDecode(string.Format(@"<dir=""rtl"" style=""text-align: right;"" trbidi=""on"">{0}</div>", post.Summary));
            //Argotic.Extensions.Core.SiteSummaryContentItem content = new Argotic.Extensions.Core.SiteSummaryContentItem();
            //content.Content = new XCData(string.Format(@"<dir=""rtl"" style=""text-align: right;"" trbidi=""on"">{0}</div>", post.Summary)).ToString();
            //contentExt.Context.Items.Add(content);
            item.AddExtension(contentExt);
            item.PublicationDate = post.PublicationTS;
            feed.Channel.AddItem(item);

        }

        //using (FileStream stream = new FileStream("SimpleRssFeed.xml", FileMode.Create, FileAccess.Write))
        //{
        Response.ContentType = "application/rss+xml";
        Response.Write(feed.CreateNavigator().OuterXml);

        //}
    }
 private void UpdateRssFeed(Rss.Structure.RssFeed rss, RssFeed rssFeed)
 {
     var miniRss = new RssFeed(rss);
     rssFeed.Stories.Clear();
     foreach (RssStory story in miniRss.Stories){
         rssFeed.Stories.Add(story);
     }
     _applicationSettings.Remove(rssFeed.RssTitle);
     rssFeed.RssTitle = miniRss.RssTitle.ToLower();
     NotifyPropertyChanged("StorySources");
     NotifyPropertyChanged("Stories");
     rssFeed.LastUpdated = DateTime.Now;
     _applicationSettings[RssFeedsKey] = new Collection<RssFeed> (StorySources);
     _applicationSettings.Save();
 }
 private void LoadRssFeed(RssFeed rssFeed)
 {
     var timeSpan = new TimeSpan(DateTime.Now.Ticks - rssFeed.LastUpdated.Ticks);
     if (timeSpan.Days > 0) {
         RefreshRssFeed(rssFeed);
     }
 }
 public void RefreshRssFeed(RssFeed rssFeed)
 {
     if (DeviceNetworkInformation.IsNetworkAvailable) {
         IsDataLoaded = false;
         WebRequest request = WebRequest.Create(rssFeed.RssLink);
         request.BeginGetResponse(EndGetResponse, new RequestState {Request = request, Address = rssFeed.RssLink, RssFeed = rssFeed});
     } else {
         Deployment.Current.Dispatcher.BeginInvoke(() => MessageBox.Show("Unable to connect.  Please check your network settings."));
     }
 }
Example #10
0
        public void Init()
        {
            IoC.InitializeWith(new WindsorContainer());
            IoC.InitializeWith(new WindsorContainer());
            ApplicationInit.InitializeRepositories();
            base.SetUp();
            DBInit.RegisterDocumentStore(Store);
            DBInit.RegisterIndexes(Store);

            using (var tran = RepositoryFactory.StartTransaction())
            {
                _feed = new RssFeed
                {
                    Id   = Guid.NewGuid(),
                    Name = "feed",
                    Url  = "feed_url"
                };
                SessionFactory <RssFeed> .Store(_feed);

                _rssItems = new[]
                {
                    new RssItem
                    {
                        Id                = Guid.NewGuid(),
                        FeedItemId        = "1",
                        Title             = "title1",
                        Text              = "Text1",
                        Description       = "Description1",
                        Author            = "twit_user1",
                        Url               = "url1",
                        Hidden            = false,
                        CreatedDate       = new DateTime(2010, 10, 10),
                        Modified          = new DateTime(2010, 10, 10),
                        PublishDate       = new DateTime(2010, 10, 10),
                        CreatedBy         = null,
                        AreCommentAllowed = false,
                        RssFeed           = _feed
                    },
                    new RssItem
                    {
                        Id                = Guid.NewGuid(),
                        FeedItemId        = "2",
                        Title             = "title2",
                        Text              = "Text2",
                        Description       = "Description2",
                        Author            = "twit_user2",
                        Url               = "url2",
                        Hidden            = false,
                        CreatedDate       = new DateTime(2010, 10, 12),
                        Modified          = new DateTime(2010, 10, 12),
                        PublishDate       = new DateTime(2010, 10, 12),
                        CreatedBy         = null,
                        AreCommentAllowed = false,
                        RssFeed           = _feed
                    },
                    new RssItem
                    {
                        Id                = Guid.NewGuid(),
                        FeedItemId        = "3",
                        Title             = "title3",
                        Text              = "Text3",
                        Description       = "Description3",
                        Author            = "twit_user3",
                        Url               = "url3",
                        Hidden            = true,
                        CreatedDate       = new DateTime(2010, 10, 13),
                        Modified          = new DateTime(2010, 10, 13),
                        PublishDate       = new DateTime(2010, 10, 13),
                        CreatedBy         = null,
                        AreCommentAllowed = false,
                        RssFeed           = _feed
                    }
                };
                foreach (var rssItem in _rssItems)
                {
                    SessionFactory <RssItem> .Store(rssItem);
                }
                tran.Commit();
            }
            WaitForIndexing();
        }
Example #11
0
        private void LoadRssFeed(XDocument doc, RssFeed feed)
        {
            SetMediaImage(feed, doc);
            feed.Description = doc.Root.Element("channel").GetSafeElementString("description");
            feed.Items = new ObservableCollection<RssItem>();
            feed.Link = doc.Root.Element("channel").GetSafeElementString("link");

            foreach (var item in doc.Descendants("item"))
            {
                var newItem = new RssItem()
                {
                    Title = item.GetSafeElementString("title"),
                    Link = item.GetSafeElementString("link"),
                    Description = item.GetSafeElementString("description"),
                    PublishDate = item.GetSafeElementDate("pubDate"),
                    Guid = item.GetSafeElementString("guid"),
                };
                feed.Items.Add(newItem);
            }

            var lastItem = feed.Items.OrderByDescending(i => i.PublishDate).FirstOrDefault();
            if (lastItem != null)
            {
                feed.LastBuildDate = lastItem.PublishDate;
            }
        }
Example #12
0
        private RssFeed GetFeedDataFromReader(XmlReader reader)
        {
            var doc = XDocument.Load(reader);

            var feed = new RssFeed();

            var defaultNamespace = doc.Root.GetDefaultNamespace();
            if (defaultNamespace.NamespaceName.EndsWith("Atom"))
                LoadAtomFeed(doc, feed);
            else
                LoadRssFeed(doc, feed);

            return feed;
        }
Example #13
0
 /// <summary>Reads the specified RSS feed</summary>
 /// <param name="Request">The specified way to connect to the web server</param>
 /// <param name="oldFeed">The cached version of the feed</param>
 /// <returns>The current contents of the feed</returns>
 /// <remarks>Will not download the feed if it has not been modified</remarks>
 public static RssFeed Read(HttpWebRequest Request, RssFeed oldFeed)
 {
     return read(oldFeed.url, Request, oldFeed);
 }
Example #14
0
		protected void Page_Load(object sender, EventArgs e)
		{
			// Put user code to initialize the page here
			RssFeed rf = new RssFeed();

			XmlTextWriter writer = new XmlTextWriter(Response.OutputStream, Encoding.UTF8);

			writer.Formatting = Formatting.Indented;
			rf.WriteRSSPrologue(writer);

			// Usage rf.AddRSSItem(writer, "Item Title", "http://test.com", "This is a test item");

			switch (Request.QueryString["pg"])
			{
				case "latestposts":
					if (!PageContext.ForumReadAccess)
						YafBuildLink.AccessDenied();
					using (DataTable dt = DB.topic_latest(PageContext.PageBoardID, 7, PageContext.PageUserID))
					{
						foreach (DataRow row in dt.Rows)
							rf.AddRSSItem(writer,
							              General.BadWordReplace(row["Subject"].ToString()),
							              YafForumInfo.ServerURL +
							              YafBuildLink.GetLinkNotEscaped(ForumPages.posts, "t={0}", Request.QueryString["t"]),
							              General.BadWordReplace(row["Message"].ToString()),
							              Convert.ToDateTime(row["Posted"]).ToString("r"));
					}
					break;
				case "latestannouncements":
					if (!PageContext.ForumReadAccess)
						YafBuildLink.AccessDenied();
					using (DataTable dt = DB.topic_announcements(PageContext.PageBoardID, 7, PageContext.PageUserID))
					{
						foreach (DataRow row in dt.Rows)
							rf.AddRSSItem(writer,
							              General.BadWordReplace(row["Subject"].ToString()),
							              YafForumInfo.ServerURL +
							              YafBuildLink.GetLinkNotEscaped(ForumPages.posts, "t={0}", Request.QueryString["t"]),
							              General.BadWordReplace(row["Message"].ToString()),
							              Convert.ToDateTime(row["Posted"]).ToString("r"));
					}
					break;
				case "posts":
					if (!PageContext.ForumReadAccess)
						YafBuildLink.AccessDenied();

					if (Request.QueryString["t"] != null)
					{
						using (
							DataTable dt =
								DB.post_list(PageContext.PageTopicID, 1, PageContext.BoardSettings.ShowDeletedMessages))
						{
							foreach (DataRow row in dt.Rows)
								rf.AddRSSItem(writer,
								              General.BadWordReplace(row["Subject"].ToString()),
								              YafForumInfo.ServerURL +
								              YafBuildLink.GetLinkNotEscaped(ForumPages.posts, "t={0}", Request.QueryString["t"]),
								              FormatMsg.FormatMessage(row["Message"].ToString(), new MessageFlags(row["Flags"])),
								              Convert.ToDateTime(row["Posted"]).ToString("r"));
						}
					}

					break;
				case "forum":
					using (
						DataTable dt = DB.forum_listread(PageContext.PageBoardID, PageContext.PageUserID, null, null))
					{
						foreach (DataRow row in dt.Rows)
						{
							rf.AddRSSItem(writer,
							              General.BadWordReplace(row["Forum"].ToString()),
							              YafForumInfo.ServerURL + YafBuildLink.GetLinkNotEscaped(ForumPages.topics, "f={0}", row["ForumID"]),
							              General.BadWordReplace(row["Description"].ToString()));
						}
					}
					break;
				case "topics":
					if (!PageContext.ForumReadAccess)
						YafBuildLink.AccessDenied();

					int forumId;
					if (Request.QueryString["f"] != null &&
					    int.TryParse(Request.QueryString["f"], out forumId))
					{
                        //vzrus changed to separate DLL specific code
                        using (DataTable dt = DB.rsstopic_list(forumId))
                        {
                            foreach (DataRow row in dt.Rows)
                            {
                                rf.AddRSSItem(writer,
                                              General.BadWordReplace(row["Topic"].ToString()),
                                              YafForumInfo.ServerURL + YafBuildLink.GetLinkNotEscaped(ForumPages.posts, "t={0}", row["TopicID"]),
                                              General.BadWordReplace(row["Topic"].ToString()),
                                              Convert.ToDateTime(row["Posted"]).ToString("r"));
                            }
                        }
				
					}

					break;
				case "active":
using (
	DataTable dt =
		DB.topic_active(PageContext.PageBoardID, PageContext.PageUserID,
		DateTime.Now + TimeSpan.FromHours( -24 ), ( PageContext.Settings.CategoryID == 0 ) ? null : (object)PageContext.Settings.CategoryID ) )
{
	foreach (DataRow row in dt.Rows)
	{
		rf.AddRSSItem(writer,
		              General.BadWordReplace(row["Subject"].ToString()),
		              YafForumInfo.ServerURL +
		              YafBuildLink.GetLinkNotEscaped(ForumPages.posts, "t={0}", row["LinkTopicID"]),
		              General.BadWordReplace(row["Subject"].ToString()));
	}
}
break;
				default:
					break;
			}

			rf.WriteRSSClosing(writer);
			writer.Flush();

			writer.Close();

			Response.ContentEncoding = Encoding.UTF8;
			Response.ContentType = "text/xml";
			Response.Cache.SetCacheability(HttpCacheability.Public);

			Response.End();
		}
Example #15
0
 public RssResult(RssFeed feed)
 {
     this.Feed = feed;
 }
        private void LoadRssFeed(XDocument doc, RssFeed feed)
        {
            SetMediaImage(feed, doc);
            feed.Description = doc.Root.GetSafeElementString("description");
            feed.Items = new ObservableCollection<RssItem>();
            feed.LastBuildDate = doc.Root.GetSafeElementDate("pubDate");
            feed.Link = doc.Root.GetSafeElementString("link");

            foreach (var item in doc.Descendants("item"))
            {
                var newItem = new RssItem()
                {
                    Title = item.GetSafeElementString("title"),
                    Link = item.GetSafeElementString("link"),
                    Description = item.GetSafeElementString("description"),
                    PublishDate = item.GetSafeElementDate("pubDate"),
                    Guid = item.GetSafeElementString("guid"),
                };
                feed.Items.Add(newItem);
            }
        }
Example #17
0
        private static IEnumerable <NewsInfo> GetNewsInfo(string feedurl)
        {
            var feed = DbUtil.Db.RssFeeds.FirstOrDefault(r => r.Url == feedurl);

            if (!feedurl.HasValue())
            {
                return(new List <NewsInfo>());
            }

            var req = WebRequest.Create(feedurl) as HttpWebRequest;

            if (feed != null && req != null)
            {
                if (feed.LastModified.HasValue)
                {
                    req.IfModifiedSince = feed.LastModified.Value;
                }
            }
            else
            {
                feed = new RssFeed();
                DbUtil.Db.RssFeeds.InsertOnSubmit(feed);
                feed.Url = feedurl;
            }

            if (req == null)
            {
                return(new List <NewsInfo>());
            }

            try
            {
                var resp = req.GetHttpResponse();
                if (resp == null)
                {
                    return(new List <NewsInfo>());
                }
                if (resp.StatusCode != HttpStatusCode.NotModified)
                {
                    feed.LastModified = resp.LastModified;
                    var rs = resp.GetResponseStream();
                    if (rs == null)
                    {
                        return(new List <NewsInfo>());
                    }
                    var sr = new StreamReader(rs);
                    feed.Data = sr.ReadToEnd();
                    sr.Close();
                    DbUtil.Db.SubmitChanges();
                }
            }
            catch
            {
                return(new List <NewsInfo>());
            }
            if (feed.Data == null)
            {
                return(new List <NewsInfo>());
            }

            try
            {
                var reader = XmlReader.Create(new StringReader(feed.Data));
                var f      = SyndicationFeed.Load(reader);
                if (f == null)
                {
                    return(new List <NewsInfo>());
                }

                var posts = from item in f.Items
                            select new NewsInfo
                {
                    Title     = item.Title.Text,
                    Published = item.PublishDate.DateTime,
                    Url       = item.Links.Single(i => i.RelationshipType == "alternate")?.GetAbsoluteUri()?.AbsoluteUri
                };
                return(posts);
            }
            catch
            {
                return(new List <NewsInfo>());
            }
        }
 /// <summary>
 /// Creates and adds a few ItemViewModel objects into the Items collection.
 /// </summary>
 public void LoadData()
 {
     if (!_applicationSettings.Contains("initialized"))
     {
         _applicationSettings["initialized"] = true;
         var hackerNewRssFeed = new RssFeed();
         hackerNewRssFeed.RssTitle = "hacker news";
         hackerNewRssFeed.RssLink = new Uri("https://news.ycombinator.com/rss");
         var nprScienceNewRssFeed = new RssFeed();
         nprScienceNewRssFeed.RssTitle = "science";
         nprScienceNewRssFeed.RssLink = new Uri("https://www.npr.org/rss/rss.php?id=1007");
         _applicationSettings[RssFeedsKey] = new Collection<RssFeed> {hackerNewRssFeed, nprScienceNewRssFeed};
         _applicationSettings.Save();
     }
     StorySources = new ObservableCollection<RssFeed>(_applicationSettings[RssFeedsKey] as Collection<RssFeed>);
     LoadRssFeeds();
     IsDataLoaded = true;
 }
Example #19
0
        protected void Page_Load(object sender, EventArgs e)
        {
            // Put user code to initialize the page here
            RssFeed rf = new RssFeed();

            XmlTextWriter writer = new XmlTextWriter(Response.OutputStream, Encoding.UTF8);

            writer.Formatting = Formatting.Indented;
            rf.WriteRSSPrologue(writer);

            // Usage rf.AddRSSItem(writer, "Item Title", "http://test.com", "This is a test item");

            switch (Request.QueryString["pg"])
            {
            case "latestposts":
                if (!PageContext.ForumReadAccess)
                {
                    YafBuildLink.AccessDenied();
                }
                using (DataTable dt = DB.topic_latest(PageContext.PageBoardID, 7, PageContext.PageUserID))
                {
                    foreach (DataRow row in dt.Rows)
                    {
                        rf.AddRSSItem(writer,
                                      General.BadWordReplace(row["Subject"].ToString()),
                                      YafForumInfo.ServerURL +
                                      YafBuildLink.GetLinkNotEscaped(ForumPages.posts, "t={0}", Request.QueryString["t"]),
                                      General.BadWordReplace(row["Message"].ToString()),
                                      Convert.ToDateTime(row["Posted"]).ToString("r"));
                    }
                }
                break;

            case "latestannouncements":
                if (!PageContext.ForumReadAccess)
                {
                    YafBuildLink.AccessDenied();
                }
                using (DataTable dt = DB.topic_announcements(PageContext.PageBoardID, 7, PageContext.PageUserID))
                {
                    foreach (DataRow row in dt.Rows)
                    {
                        rf.AddRSSItem(writer,
                                      General.BadWordReplace(row["Subject"].ToString()),
                                      YafForumInfo.ServerURL +
                                      YafBuildLink.GetLinkNotEscaped(ForumPages.posts, "t={0}", Request.QueryString["t"]),
                                      General.BadWordReplace(row["Message"].ToString()),
                                      Convert.ToDateTime(row["Posted"]).ToString("r"));
                    }
                }
                break;

            case "posts":
                if (!PageContext.ForumReadAccess)
                {
                    YafBuildLink.AccessDenied();
                }

                if (Request.QueryString["t"] != null)
                {
                    using (
                        DataTable dt =
                            DB.post_list(PageContext.PageTopicID, 1, PageContext.BoardSettings.ShowDeletedMessages))
                    {
                        foreach (DataRow row in dt.Rows)
                        {
                            rf.AddRSSItem(writer,
                                          General.BadWordReplace(row["Subject"].ToString()),
                                          YafForumInfo.ServerURL +
                                          YafBuildLink.GetLinkNotEscaped(ForumPages.posts, "t={0}", Request.QueryString["t"]),
                                          FormatMsg.FormatMessage(row["Message"].ToString(), new MessageFlags(row["Flags"])),
                                          Convert.ToDateTime(row["Posted"]).ToString("r"));
                        }
                    }
                }

                break;

            case "forum":
                using (
                    DataTable dt = DB.forum_listread(PageContext.PageBoardID, PageContext.PageUserID, null, null))
                {
                    foreach (DataRow row in dt.Rows)
                    {
                        rf.AddRSSItem(writer,
                                      General.BadWordReplace(row["Forum"].ToString()),
                                      YafForumInfo.ServerURL + YafBuildLink.GetLinkNotEscaped(ForumPages.topics, "f={0}", row["ForumID"]),
                                      General.BadWordReplace(row["Description"].ToString()));
                    }
                }
                break;

            case "topics":
                if (!PageContext.ForumReadAccess)
                {
                    YafBuildLink.AccessDenied();
                }

                int forumId;
                if (Request.QueryString["f"] != null &&
                    int.TryParse(Request.QueryString["f"], out forumId))
                {
                    //vzrus changed to separate DLL specific code
                    using (DataTable dt = DB.rsstopic_list(forumId))
                    {
                        foreach (DataRow row in dt.Rows)
                        {
                            rf.AddRSSItem(writer,
                                          General.BadWordReplace(row["Topic"].ToString()),
                                          YafForumInfo.ServerURL + YafBuildLink.GetLinkNotEscaped(ForumPages.posts, "t={0}", row["TopicID"]),
                                          General.BadWordReplace(row["Topic"].ToString()),
                                          Convert.ToDateTime(row["Posted"]).ToString("r"));
                        }
                    }
                }

                break;

            case "active":
                using (
                    DataTable dt =
                        DB.topic_active(PageContext.PageBoardID, PageContext.PageUserID,
                                        DateTime.Now + TimeSpan.FromHours(-24), (PageContext.Settings.CategoryID == 0) ? null : (object)PageContext.Settings.CategoryID))
                {
                    foreach (DataRow row in dt.Rows)
                    {
                        rf.AddRSSItem(writer,
                                      General.BadWordReplace(row["Subject"].ToString()),
                                      YafForumInfo.ServerURL +
                                      YafBuildLink.GetLinkNotEscaped(ForumPages.posts, "t={0}", row["LinkTopicID"]),
                                      General.BadWordReplace(row["Subject"].ToString()));
                    }
                }
                break;

            default:
                break;
            }

            rf.WriteRSSClosing(writer);
            writer.Flush();

            writer.Close();

            Response.ContentEncoding = Encoding.UTF8;
            Response.ContentType     = "text/xml";
            Response.Cache.SetCacheability(HttpCacheability.Public);

            Response.End();
        }
Example #20
0
 /// <summary>Reads the specified RSS feed</summary>
 /// <param name="oldFeed">The cached version of the feed</param>
 /// <returns>The current contents of the feed</returns>
 /// <remarks>Will not download the feed if it has not been modified</remarks>
 public static RssFeed Read(RssFeed oldFeed)
 {
     return read(oldFeed.url, null, oldFeed);
 }
Example #21
0
        private RssFeed ReadRssFeed(int feedID, string webSource)
        {
            database.Rss dbRss = new de.dhoffmann.mono.adfcnewsapp.buslog.database.Rss();
            RssFeed ret = new RssFeed();

            try
            {
                XDocument doc = XDocument.Parse(webSource);

                var channel = doc.Descendants("channel");

                if (channel != null)
                {
                    var qTitle = channel.Descendants("title").First();
                    string title = null;

                    if (qTitle != null)
                        title = FromHtml(qTitle.Value);

                    var qLink = channel.Descendants("link").First();
                    string link = null;

                    if (qLink != null)
                        link = qLink.Value;

                    var qDescription = channel.Descendants("description").First();
                    string description = null;

                    if (qDescription != null)
                        description = FromHtml(qDescription.Value);

                    DateTime lastBuildDate = DateTime.MinValue;
                    try
                    {
                        var qLastBuildDate = channel.Descendants("lastBuildDate").First();

                        // TODO prüfen
                        if (qLastBuildDate != null)
                            lastBuildDate = DateTime.Parse(qLastBuildDate.Value);
                    }
                    catch(Exception)
                    { ; }

                    ret.Header = new RssHeader()
                    {
                        FeedID = feedID,
                        Title = title,
                        Link = link,
                        Description = description,
                        LastBuildDate = lastBuildDate
                    };

                    // Das Datum der letzten Daten importieren
                    DateTime? dbLastBuildDate = dbRss.GetLastBuildDate(feedID);
                    dbLastBuildDate = null;

                    // Müssen die Items wirklich geparsed werden?
                    if(!dbLastBuildDate.HasValue || (ret != null && ret.Header != null && ret.Header.LastBuildDate.HasValue && dbLastBuildDate.Value < ret.Header.LastBuildDate.Value))
                    {
                        var items = doc.Descendants("item");

                        if (items != null)
                        {
                            List<RssItem> rssItems = new List<RssItem>();

                            foreach (var item in items)
                            {
                                RssItem rssItem = new RssItem();

                                rssItem.FeedID = feedID;

                                var qiTitle = item.Descendants("title").First();

                                if (qiTitle != null)
                                    rssItem.Title = FromHtml(qiTitle.Value);

                                var qiLink = item.Descendants("link").First();
                                if (qiLink != null)
                                    rssItem.Link = qiLink.Value;

                                var qiDescription = item.Descendants("description").First();

                                if (qiDescription != null)
                                    rssItem.Description = FromHtml(qiDescription.Value);

                                // Nicht alle haben diesen Node
                                try
                                {
                                    var qiCategory = item.Descendants("category").First();

                                    if (qiCategory != null)
                                        rssItem.Category = FromHtml(qiCategory.Value);
                                }
                                catch(Exception)
                                { ; }

                                try
                                {
                                    // TODO prüfen!!
                                    var qiPubDate = item.Descendants("pubDate").First();
                                    if (qiPubDate != null)
                                        rssItem.PubDate = DateTime.Parse(qiPubDate.Value);
                                }
                                catch(Exception)
                                { ; }

                                rssItems.Add(rssItem);
                            }

                            ret.Items = rssItems;
                        }
                    }
                }
            }
            catch(Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("ex: " + ex.ToString());
            }

            return ret;
        }
Example #22
0
        private static RssFeed read(string url, HttpWebRequest request, RssFeed oldFeed)
        {
            // ***** Marked for substantial improvement
            RssFeed feed = new RssFeed();
            RssElement element;
            Stream stream = null;
            Uri uri = new Uri(url);
            feed.url = url;

            switch (uri.Scheme)
            {
                case "file":
                    feed.lastModified = File.GetLastWriteTime(url);
                    if ((oldFeed != null) && (feed.LastModified == oldFeed.LastModified))
                    {
                        oldFeed.cached = true;
                        return oldFeed;
                    }
                    stream = new FileStream(url, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                    break;
                case "https":
                    goto case "http";
                case "http":
                    if (request == null)
                        request = (HttpWebRequest) WebRequest.Create(uri);
                    if (oldFeed != null)
                    {
                        request.IfModifiedSince = oldFeed.LastModified;
                        request.Headers.Add("If-None-Match", oldFeed.ETag);
                    }
                    try
                    {
                        HttpWebResponse response = (HttpWebResponse) request.GetResponse();
                        feed.lastModified = response.LastModified;
                        feed.etag = response.Headers["ETag"];
                        try
                        {
                            if (response.ContentEncoding != "")
                                feed.encoding = Encoding.GetEncoding(response.ContentEncoding);
                        }
                        catch
                        {
                        }
                        stream = response.GetResponseStream();
                    }
                    catch (WebException we)
                    {
                        if (oldFeed != null)
                        {
                            oldFeed.cached = true;
                            return oldFeed;
                        }
                        else throw we; // bad
                    }
                    break;
            }

            if (stream != null)
            {
                RssReader reader = null;
                try
                {
                    reader = new RssReader(stream);
                    do
                    {
                        element = reader.Read();
                        if (element is DSD.Site.UtilityClasses.RSS.NET.RssChannel.RssChannel)
                            feed.Channels.Add((DSD.Site.UtilityClasses.RSS.NET.RssChannel.RssChannel) element);
                    } while (element != null);
                    feed.rssVersion = reader.Version;
                }
                finally
                {
                    feed.exceptions = reader.Exceptions;
                    reader.Close();
                }
            }
            else
                throw new ApplicationException("Not a valid Url");

            return feed;
        }
Example #23
0
 public ReadResult(RssFeed feed, UpdateStatus status)
 {
     this.feed = feed;
     this.status = status;
 }
Example #24
0
        private void LoadAtomFeed(XDocument doc, RssFeed feed)
        {
            SetMediaImage(feed, doc);
            feed.Description = doc.Root.GetSafeElementString("summary");
            feed.Items = new ObservableCollection<RssItem>();
            feed.LastBuildDate = doc.Root.GetSafeElementDate("updated");
            feed.Link = doc.Root.GetLink("self");

            foreach (var item in doc.Root.Elements(doc.Root.GetDefaultNamespace() + "entry"))
            {
                var newItem = new RssItem()
                {
                    Title = item.GetSafeElementString("title"),
                    Description = item.GetSafeElementString("description"),
                    PublishDate = item.GetSafeElementDate("published"),
                    Guid = item.GetSafeElementString("id"),
                    Link = item.GetLink("alternate"),
                };
                feed.Items.Add(newItem);
            }
        }
 protected override void UpdateView()
 {
     CurrentFeed = Service.GetNext();
 }
Example #26
0
        private void SetMediaImage(RssFeed feed, XDocument doc)
        {
            var image = doc.Root.Descendants(NS_ITUNES + "image").FirstOrDefault();
            if (image != null)
            {
                feed.ImageUri = new Uri(image.Attribute("href").Value);
                return;
            }

            var thumbnail = doc.Element(NS_MEDIA + "thumbnail");
            if (thumbnail != null)
            {
                feed.ImageUri = new Uri(thumbnail.Value);
                return;
            }

            // if all else fails...
            feed.ImageUri = new Uri("/Images/FeedType/rss.jpg", UriKind.Relative);
        }
Example #27
0
        public void ProcessRequest(HttpContext context)
        {
            string pagePath = "";

            if (context.Request.QueryString["p"] != null)
            {
                pagePath = context.Request.QueryString["p"];
            }
            CmsLanguage pageLang = CmsConfig.Languages[0];

            if (CmsConfig.Languages.Length > 1 && context.Request.QueryString["l"] != null)
            {
                string      langCode = context.Request.QueryString["l"];
                CmsLanguage testLang = CmsLanguage.GetFromHaystack(langCode, CmsConfig.Languages);
                if (!testLang.isInvalidLanguage)
                {
                    pageLang = testLang;
                }
            }

            CmsPage pageToRenderRSSFor = CmsContext.getPageByPath(pagePath, pageLang);

            if (pageToRenderRSSFor.Id < 0 || !pageToRenderRSSFor.currentUserCanRead)
            {
                context.Response.ContentType = "text/plain";
                context.Response.Write("Error: CMS page not found");
                context.Response.Flush();
                context.Response.End();
            }
            else
            {
                // -- generate the RssFeed
                RssFeed rssFeed = new RssFeed(System.Text.UTF8Encoding.UTF8);
                rssFeed.Version = RssVersion.RSS20;


                // -- setup the RSS channel
                string titlePrefix  = CmsConfig.getConfigValue("pageTitlePrefix", "");
                string titlePostfix = CmsConfig.getConfigValue("pageTitlePostfix", "");

                string     rssTitle       = titlePrefix + pageToRenderRSSFor.getTitle(pageLang) + titlePostfix;
                string     rssDescription = pageToRenderRSSFor.getSearchEngineDescription(pageLang);
                Uri        rssLink        = new Uri(pageToRenderRSSFor.getUrl(CmsUrlFormat.FullIncludingProtocolAndDomainName, pageLang), UriKind.RelativeOrAbsolute);
                RssChannel rssChannel     = new RssChannel(rssTitle, rssDescription, rssLink);
                rssChannel.Generator = "HatCMS: https://code.google.com/p/hatcms/";

                // -- call "GetRssFeedItems()" for each placeholder.
                CmsPlaceholderDefinition[] phDefs = pageToRenderRSSFor.getAllPlaceholderDefinitions();

                foreach (CmsPlaceholderDefinition phDef in phDefs)
                {
                    RssItem[] items = Placeholders.PlaceholderUtils.GetRssFeedItems(phDef.PlaceholderType, pageToRenderRSSFor, phDef, pageLang);
                    foreach (RssItem item in items)
                    {
                        rssChannel.Items.Add(item);
                    }
                }

                rssFeed.Channels.Add(rssChannel);

                context.Response.ContentType = "application/rss+xml";
                rssFeed.Write(context.Response.OutputStream);
                context.Response.Flush();
                context.Response.End();
            }
        }
Example #28
0
    static void RunOnce()
    {
        if (bloggers == null || File.GetLastWriteTime (bloggersFile) > lastReadOfBloggersFile) {
            lastReadOfBloggersFile = File.GetLastWriteTime (bloggersFile);
            bloggers = BloggerCollection.LoadFromFile (bloggersFile);
        }

        disable_load = false;
        all = (Blogger []) bloggers.Bloggers.ToArray (typeof (Blogger));
        lock (all) {
            next = 10;
            for (int i = 0; i < 10 && i < all.Length; i++) {
                Blogger b = all [i];
                ReadDelegate d = new ReadDelegate (FeedCache.Read);
                d.BeginInvoke (b.Name, b.RssUrl, feed_done, b);
            }
        }

        wait_handle.WaitOne (300000, false);
        disable_load = true;

        for (int i = 0; i < (int) UpdateStatus.MAX; i++) {
            Console.WriteLine ("{0}: {1}", (UpdateStatus) i, counters [i]);
        }

        int error = counters [(int) UpdateStatus.Error];
        int downloaded = counters [(int) UpdateStatus.Downloaded];
        int updated = counters [(int) UpdateStatus.Updated];
        if (error == 0 && downloaded == 0 && updated == 0)
            return;

        outFeed = new RssFeed ();
        RssChannel ch = new RssChannel ();
        ch.Title = "Monologue";
        ch.Generator = "Monologue worker: b-diddy powered";
        ch.Description = "The voices of Mono";
        ch.Link = new Uri ("http://www.go-mono.com/monologue/");

        ArrayList stories = new ArrayList ();

        DateTime minPubDate = DateTime.Now.AddDays (-14);
        foreach (Blogger b in bloggers.BloggersByUrl) {
            if (b.Channel == null) continue;
            foreach (RssItem i in b.Channel.Items) {
                if (i.PubDate == DateTime.MinValue) {
                    b.DateError = true;
                } else if (i.PubDate >= minPubDate) {
                    i.Title = b.Name + ": " + i.Title;
                    i.PubDate = i.PubDate.ToUniversalTime ();
                    stories.Add (i);
                }
            }
        }

        stories.Sort (new ReverseRssItemComparer ());

        foreach (RssItem itm in stories)
            ch.Items.Add (itm);

        if (ch.Items.Count == 0) {
            Settings.Log ("No feeds to store.");
            return;
        }
        outFeed.Channels.Add (ch);
        outFeed.Write (rssOutFile);

        Render ();
    }
Example #29
0
        private static RssFeed SetRssAndChannel(string RssTitle, string RssDescription,
                                               string RssLink)
        {
            RssFeed ObjRss = new RssFeed { Version = RssVersion.RSS20, Encoding = Encoding.UTF8 };

            RssChannel ObjRSSChannel = new RssChannel
                                           {
                                               Title = RssTitle,
                                               Description = RssDescription,
                                               LastBuildDate = PersianDateTime.MiladiToPersian(DateTime.Now).ToShortDateString(),
                                               Link = new Uri(RssLink),
                                               PubDate = DateTime.Now,
                                               WebMaster = "BMI WebSite",
                                               Copyright = "(c) 2010, www.hossein-shirazi.ir. All rights reserved.",
                                               Generator = "www.hossein-shirazi.ir"
                                           };
            ObjRss.Channels.Add(ObjRSSChannel);

            return ObjRss;
        }
Example #30
0
        protected void Page_Load( object sender, System.EventArgs e )
        {
            // Put user code to initialize the page here
            RssFeed rf = new RssFeed();

            XmlTextWriter writer = new XmlTextWriter( Response.OutputStream, System.Text.Encoding.UTF8 );

            writer.Formatting = Formatting.Indented;
            rf.WriteRSSPrologue( writer, this );

            // Usage rf.AddRSSItem(writer, "Item Title", "http://test.com", "This is a test item");

            switch ( Request.QueryString ["pg"] )
            {
                case "posts":
                    if ( !ForumReadAccess )
                        Data.AccessDenied();

                    if ( Request.QueryString ["t"] != null )
                    {
                        using ( DataTable dt = DB.post_list( PageTopicID, 1 ) )
                        {
                            foreach ( DataRow row in dt.Rows )
                                rf.AddRSSItem( writer, row ["Subject"].ToString(), ServerURL + Forum.GetLink( Pages.posts, "t={0}", Request.QueryString ["t"] ), row ["Message"].ToString(), Convert.ToDateTime( row ["Posted"] ).ToString( "r" ) );
                        }
                    }

                    break;
                case "forum":
                    using ( DataTable dt = DB.forum_listread( PageBoardID, PageUserID, null, null ) )
                    {
                        foreach ( DataRow row in dt.Rows )
                        {
                            if ( row ["LastTopicID"] != DBNull.Value )
                            {
                                rf.AddRSSItem( writer, row ["Forum"].ToString(), ServerURL + Forum.GetLink( Pages.topics, "f={0}", row ["ForumID"] ), row ["Description"].ToString() );
                            }
                            else
                            {
                                rf.AddRSSItem( writer, row ["Forum"].ToString(), ServerURL + Forum.GetLink( Pages.topics, "f={0}", row ["ForumID"] ), row ["Description"].ToString() );
                            }
                        }
                    }
                    break;
                case "topics":
                    if ( !ForumReadAccess )
                        Data.AccessDenied();

                    if ( Request.QueryString ["f"] != null )
                    {
                        string tSQL = "select Topic = a.Topic, TopicID = a.TopicID, Name = b.Name, Posted = a.Posted from yaf_Topic a, yaf_Forum b where a.ForumID=" + Request.QueryString ["f"] + " and b.ForumID = a.ForumID";
                        using ( DataTable dt = DB.GetData( tSQL ) )
                        {
                            foreach ( DataRow row in dt.Rows )
                            {
                                rf.AddRSSItem( writer, row ["Topic"].ToString(), ServerURL + Forum.GetLink( Pages.posts, "t={0}", row ["TopicID"] ), row ["Topic"].ToString(), Convert.ToDateTime( row ["Posted"] ).ToString( "r" ) );
                            }
                        }
                    }

                    break;
                case "active":
                    object categoryIDObject = null;
                    if ( ForumControl.CategoryID != 0 ) categoryIDObject = ForumControl.CategoryID;

                    using ( DataTable dt = DB.topic_active( PageBoardID, PageUserID, DateTime.Now + TimeSpan.FromHours( -24 ), categoryIDObject ) )
                    {
                        foreach ( DataRow row in dt.Rows )
                        {
                            rf.AddRSSItem( writer, row ["Subject"].ToString(), ServerURL + Forum.GetLink( Pages.posts, "t={0}", row ["LinkTopicID"] ), row ["Subject"].ToString() );
                        }
                    }
                    break;
                default:
                    break;
            }

            rf.WriteRSSClosing( writer );
            writer.Flush();

            writer.Close();

            Response.ContentEncoding = System.Text.Encoding.UTF8;
            Response.ContentType = "text/xml";
            Response.Cache.SetCacheability( HttpCacheability.Public );

            Response.End();
        }
 public List <RssFeedItem> GenerateRssFeedItemList(RssFeed feed, string html)
 {
     return(GenerateRssFeedItemList(feed.CollectionName, feed.Url, feed.Filters, html));
 }