/// <summary> /// Modifies the <see cref="RssFeed"/> to match the data source. /// </summary> /// <param name="resource">The <see cref="RssFeed"/> to be filled.</param> /// <exception cref="ArgumentNullException">The <paramref name="resource"/> is a null reference (Nothing in Visual Basic).</exception> public void Fill(RssFeed resource) { //------------------------------------------------------------ // Validate parameter //------------------------------------------------------------ Guard.ArgumentNotNull(resource, "resource"); //------------------------------------------------------------ // Create namespace resolver //------------------------------------------------------------ XmlNamespaceManager manager = new XmlNamespaceManager(this.Navigator.NameTable); //------------------------------------------------------------ // Attempt to fill syndication resource //------------------------------------------------------------ XPathNavigator feedNavigator = this.Navigator.SelectSingleNode("rss", manager); if (feedNavigator != null) { XPathNavigator channelNavigator = feedNavigator.SelectSingleNode("channel", manager); if (channelNavigator != null) { Rss091SyndicationResourceAdapter.FillChannel(resource.Channel, channelNavigator, manager, this.Settings); } SyndicationExtensionAdapter adapter = new SyndicationExtensionAdapter(feedNavigator, this.Settings); adapter.Fill(resource, manager); } }
internal static string AddExtensionToXml(SyndicationExtension ext) { RssFeed feed = new RssFeed(new Uri("http://www.example.com"), "Argotic - Extension Test"); feed.Channel.Description = "Test of an extension"; feed.Channel.ManagingEditor = "*****@*****.**"; feed.Channel.Webmaster = "*****@*****.**"; feed.Channel.Language = CultureInfo.CurrentCulture; #if false feed.Channel.Image = new RssImage(); feed.Channel.Image.Title = "Example Image Title"; feed.Channel.Image.Url = new Uri("http://www.example.com/sample.png"); feed.Channel.Image.Link = new Uri("http://www.example.com/"); feed.Channel.Image.Width = 32; feed.Channel.Image.Height = 32; #endif RssItem item = new RssItem(); item.Title = "Item #1"; item.Link = new Uri("http://www.example.com/item1.htm"); item.Description = "text for First Item"; item.PublicationDate = new DateTime(2010, 8, 1, 0, 0, 1); feed.Channel.AddItem(item); // var firstItem = feed.Channel.Items.First(); // firstItem.AddExtension(geo); item.AddExtension(ext); using (var sw = new StringWriter()) using (var tw = new XmlTextWriter(sw)) { feed.Save(tw); return sw.ToString(); } }
public string Generate(string title, List<string> filePaths, string imagePath = null) { // todo: add validation library - CuttingEdge.Conditions ? var feed = new RssFeed(); feed.Channel.Link = new Uri(GetUrl(Port, "feed.xml")); feed.Channel.Title = title; if (imagePath != null) { var file = new FileInfo(imagePath); if (file.Exists) { var extension = new YahooMediaSyndicationExtension(); extension.Context.Thumbnails.Add(new YahooMediaThumbnail(new Uri(GetUrl(Port, file.Name)))); feed.Channel.AddExtension(extension); } } foreach (string filePath in filePaths) { var item = GetItem(filePath); if (item != null) feed.Channel.AddItem(item); } return feed.CreateNavigator().OuterXml; }
protected override void WriteXml(ControllerContext context) { RssFeed feed = new RssFeed(); feed.Channel.Title = Feed.Title; feed.Channel.Link = GetLink(Feed.Url); feed.Channel.Description = Feed.Tagline; feed.Channel.PublicationDate = Feed.Published; feed.Channel.LastBuildDate = DateTime.Now; feed.Channel.Generator = "Zeus CMS"; feed.Channel.ManagingEditor = Feed.Author; foreach (ISyndicatable syndicatable in Feed.Items) { RssItem item = new RssItem(); item.Title = syndicatable.Title; item.Link = GetLink(syndicatable.Url); item.Description = syndicatable.Summary; item.PublicationDate = syndicatable.Published; feed.Channel.AddItem(item); } SyndicationResourceSaveSettings settings = new SyndicationResourceSaveSettings { CharacterEncoding = new UTF8Encoding(false) }; feed.Save(context.HttpContext.Response.OutputStream, settings); }
public static void Generate(Stream output) { RssFeed feed = new RssFeed(); feed.Channel.Link = new Uri(Link); feed.Channel.Title = Title; feed.Channel.Description = Description; feed.Save(output); }
//============================================================ // CLASS SUMMARY //============================================================ /// <summary> /// Provides example code for the RssTextInput class. /// </summary> public static void ClassExample() { #region RssTextInput RssFeed feed = new RssFeed(); feed.Channel.Title = "Dallas Times-Herald"; feed.Channel.Link = new Uri("http://dallas.example.com"); feed.Channel.Description = "Current headlines from the Dallas Times-Herald newspaper"; feed.Channel.TextInput = new RssTextInput("What software are you using?", new Uri("http://www.cadenhead.org/textinput.php"), "query", "TextInput Inquiry"); #endregion }
//============================================================ // CLASS SUMMARY //============================================================ /// <summary> /// Provides example code for the RssImage class. /// </summary> public static void ClassExample() { #region RssImage RssFeed feed = new RssFeed(); feed.Channel.Title = "Dallas Times-Herald"; feed.Channel.Link = new Uri("http://dallas.example.com"); feed.Channel.Description = "Current headlines from the Dallas Times-Herald newspaper"; RssImage image = new RssImage(new Uri("http://dallas.example.com"), "Dallas Times-Herald", new Uri("http://dallas.example.com/masthead.gif")); image.Description = "Read the Dallas Times-Herald"; image.Height = 32; image.Width = 96; feed.Channel.Image = image; #endregion }
//============================================================ // CLASS SUMMARY //============================================================ /// <summary> /// Provides example code for the RssGuid class. /// </summary> public static void ClassExample() { #region RssGuid RssFeed feed = new RssFeed(); feed.Channel.Title = "Dallas Times-Herald"; feed.Channel.Link = new Uri("http://dallas.example.com"); feed.Channel.Description = "Current headlines from the Dallas Times-Herald newspaper"; RssItem item = new RssItem(); item.Title = "Seventh Heaven! Ryan Hurls Another No Hitter"; item.Link = new Uri("http://dallas.example.com/1991/05/02/nolan.htm"); item.Description = "Texas Rangers pitcher Nolan Ryan hurled the seventh no-hitter of his legendary career on Arlington Appreciation Night, defeating the Toronto Blue Jays 3-0."; item.Guid = new RssGuid("http://dallas.example.com/1983/05/06/joebob.htm"); feed.Channel.AddItem(item); #endregion }
//============================================================ // CLASS SUMMARY //============================================================ /// <summary> /// Provides example code for the RssChannel class. /// </summary> public static void ClassExample() { #region RssChannel RssFeed feed = new RssFeed(); feed.Channel.Title = "Dallas Times-Herald"; feed.Channel.Link = new Uri("http://dallas.example.com"); feed.Channel.Description = "Current headlines from the Dallas Times-Herald newspaper"; feed.Channel.Categories.Add(new RssCategory("Media")); feed.Channel.Categories.Add(new RssCategory("News/Newspapers/Regional/United_States/Texas", "dmoz")); feed.Channel.Cloud = new RssCloud("server.example.com", "/rpc", 80, RssCloudProtocol.XmlRpc, "cloud.notify"); feed.Channel.Copyright = "Copyright 2007 Dallas Times-Herald"; feed.Channel.Generator = "Microsoft Spaces v1.1"; RssImage image = new RssImage(new Uri("http://dallas.example.com"), "Dallas Times-Herald", new Uri("http://dallas.example.com/masthead.gif")); image.Description = "Read the Dallas Times-Herald"; image.Height = 32; image.Width = 96; feed.Channel.Image = image; feed.Channel.Language = new CultureInfo("en-US"); feed.Channel.LastBuildDate = new DateTime(2007, 10, 14, 17, 17, 44); feed.Channel.ManagingEditor = "[email protected] (Jim Lehrer)"; feed.Channel.PublicationDate = new DateTime(2007, 10, 14, 5, 0, 0); feed.Channel.Rating = "(PICS-1.1 \"http://www.rsac.org/ratingsv01.html\" l by \"[email protected]\" on \"2007.01.29T10:09-0800\" r (n 0 s 0 v 0 l 0))"; feed.Channel.SkipDays.Add(DayOfWeek.Saturday); feed.Channel.SkipDays.Add(DayOfWeek.Sunday); feed.Channel.SkipHours.Add(0); feed.Channel.SkipHours.Add(1); feed.Channel.SkipHours.Add(2); feed.Channel.SkipHours.Add(22); feed.Channel.SkipHours.Add(23); feed.Channel.TextInput = new RssTextInput("What software are you using?", new Uri("http://www.cadenhead.org/textinput.php"), "query", "TextInput Inquiry"); feed.Channel.TimeToLive = 60; feed.Channel.Webmaster = "*****@*****.**"; #endregion }
protected override Feed CreateFeed(XmlReader reader, string url) { var rssFeed = new RssFeed(); rssFeed.Load(reader); var items = rssFeed.Channel.Items.OrderBy(i => GetPublishedDate(i)).Select(CreateFeedItem); var feed = new Feed { Title = rssFeed.Channel.Title, Url = url, SiteUrl = rssFeed.Channel.Link.ToString(), Description = rssFeed.Channel.Description, Items = new List<Item>(items) }; var latest = items.LastOrDefault(); if (latest != null) { feed.Updated = latest.Published; } return feed; }
public RssSource ReadOne(string feedUrl) { var result = new RssSource { FeedUrl = feedUrl}; var feed = new RssFeed(); feed.Load(new Uri(feedUrl), null); feed.Channel.Items .ToList() .ForEach(x => { if (x.Enclosures != null && x.Enclosures.Any(m => m.ContentType.ToLower().Contains("mp3"))) { var item = new RssSourceItem { Title = x.Title, Description = x.Description, Link = x.Link.ToString(), Mp3 = x.Enclosures.First(mp3 => mp3.ContentType.ToLower().Contains("mp3")).Url.ToString() }; item.PublicationDate = x.PublicationDate; result.Items.Add(item); } }); return result; }
protected override IList<Item> UpdateFeed(Feed feed, XmlReader reader) { var rssFeed = new RssFeed(); rssFeed.Load(reader); var items = (from i in rssFeed.Channel.Items let date = GetPublishedDate(i) orderby date where date > feed.Updated select CreateFeedItem(i)).ToList(); feed.Items.AddRange(items); var latest = items.LastOrDefault(); if (latest != null) { feed.Updated = latest.Published; } // OPML does not set full description so check for one when updating. if (String.IsNullOrEmpty(feed.Description)) { feed.Description = rssFeed.Channel.Description; } return items; }
//============================================================ // CLASS SUMMARY //============================================================ /// <summary> /// Provides example code for the RssCategory class. /// </summary> public static void ClassExample() { #region RssCategory RssFeed feed = new RssFeed(); feed.Channel.Title = "Dallas Times-Herald"; feed.Channel.Link = new Uri("http://dallas.example.com"); feed.Channel.Description = "Current headlines from the Dallas Times-Herald newspaper"; feed.Channel.Categories.Add(new RssCategory("Media")); feed.Channel.Categories.Add(new RssCategory("News/Newspapers/Regional/United_States/Texas", "dmoz")); RssItem item = new RssItem(); item.Title = "Seventh Heaven! Ryan Hurls Another No Hitter"; item.Link = new Uri("http://dallas.example.com/1991/05/02/nolan.htm"); item.Description = "Texas Rangers pitcher Nolan Ryan hurled the seventh no-hitter of his legendary career on Arlington Appreciation Night, defeating the Toronto Blue Jays 3-0."; item.Author = "[email protected] (Joe Bob Briggs)"; item.Categories.Add(new RssCategory("sports")); item.Categories.Add(new RssCategory("1991/Texas Rangers", "rec.sports.baseball")); feed.Channel.AddItem(item); #endregion }
public static void Generate(CheevoUser user, Stream output) { RssFeed feed = new RssFeed(); feed.Channel.Link = new Uri(Link); feed.Channel.Title = Title; feed.Channel.Description = Description; // the last build date must correspond to the 'newest' cheevo feed.Channel.LastBuildDate = user.GetLastUpdateTime(); feed.Channel.PublicationDate = user.GetLastUpdateTime(); foreach (var cheevo in user.ObtainedCheevos) { RssItem item = new RssItem(); item.Title = cheevo.Title; item.Link = new Uri(Link); item.Description = cheevo.Points.ToString(); item.PublicationDate = cheevo.Awarded; feed.Channel.AddItem(item); } feed.Save(output); }
public static void RefreshFeed( mojoPortal.Business.RssFeed feedInfo, int moduleId, Guid moduleGuid, int maxDaysOld, int maxEntriesPerFeed, bool enableSelectivePublishing) { if (feedInfo == null) { return; } try { if (FeedManagerConfiguration.UseReadWriteLockForCacheMenagement) { cacheLock.AcquireWriterLock(cacheLockTimeoutInMilliseconds); } DateTime cutoffDate = DateTime.Now.AddDays(-maxDaysOld); mojoPortal.Business.RssFeed.DeleteExpiredEntriesByModule(moduleGuid, cutoffDate); mojoPortal.Business.RssFeed.DeleteUnPublishedEntriesByFeed(feedInfo.ItemId); int entriesAdded = 0; string siteRoot = SiteUtils.GetNavigationSiteRoot(); string secureSiteRoot = SiteUtils.GetSecureNavigationSiteRoot(); bool publish = true; if (enableSelectivePublishing) { if (!feedInfo.PublishByDefault) { publish = false; } } string feedUrl = feedInfo.RssUrl; if (feedUrl.StartsWith("~/")) { feedUrl = WebUtils.ResolveServerUrl(feedUrl).Replace("https:", "http:"); } try { GenericSyndicationFeed gsFeed = GenericSyndicationFeed.Create(new Uri(FormatFeedUrl(feedUrl, siteRoot, secureSiteRoot))); #region RSSFeed_management if (gsFeed.Format == SyndicationContentFormat.Rss) { Argotic.Syndication.RssFeed rssFeed = gsFeed.Resource as Argotic.Syndication.RssFeed; if (rssFeed != null) { foreach (Argotic.Syndication.RssItem rssItem in rssFeed.Channel.Items) { if ((rssItem.PublicationDate >= cutoffDate) || (maxDaysOld == 0)) { if ((entriesAdded < maxEntriesPerFeed) || (maxEntriesPerFeed == 0)) { string entryBlob = rssItem.Title + rssItem.Link.ToString(); int entryHash = GetEntryHash(entryBlob); if (UpdateEntry( moduleGuid, EnsureDate(rssItem.PublicationDate), rssItem.Title, rssItem.Author, feedInfo.RssUrl, rssItem.Description, rssItem.Link.ToString(), entryHash, feedInfo.ItemGuid, feedInfo.ItemId, publish) > 0) { entriesAdded += 1; } } } } } } #endregion #region ATOMFeed_management if (gsFeed.Format == SyndicationContentFormat.Atom) { Argotic.Syndication.AtomFeed atomFeed = gsFeed.Resource as Argotic.Syndication.AtomFeed; foreach (AtomEntry atItem in atomFeed.Entries) { if ((atItem.PublishedOn >= cutoffDate) || (maxDaysOld == 0)) { if ((entriesAdded < maxEntriesPerFeed) || (maxEntriesPerFeed == 0)) { string entryLink = string.Empty; StringBuilder entryAuthor = new StringBuilder(); string comma = string.Empty; foreach (AtomPersonConstruct atPerson in atItem.Authors) { entryAuthor.Append(comma + atPerson.Name); comma = ","; } if (entryAuthor.Length == 0) { foreach (AtomPersonConstruct atPerson in atomFeed.Authors) { entryAuthor.Append(comma + atPerson.Name); comma = ","; } } foreach (AtomLink atLink in atItem.Links) { if (atLink.Relation == "alternate") { entryLink = atLink.Uri.ToString(); } } if ((entryLink.Length == 0) && (atItem.Links.Count > 0)) { entryLink = atItem.Links[0].Uri.ToString(); } string content = string.Empty; if (atItem.Content == null) { if (atItem.Summary != null) { content = atItem.Summary.Content; } } else { content = atItem.Content.Content; } if (content.Length == 0) { continue; } string entryBlob = atItem.Title.ToString() + entryLink; int entryHash = GetEntryHash(entryBlob); if (UpdateEntry( moduleGuid, EnsureDate(atItem.PublishedOn), atItem.Title.ToString(), entryAuthor.ToString(), feedInfo.RssUrl, content, entryLink, entryHash, feedInfo.ItemGuid, feedInfo.ItemId, publish) > 0) { entriesAdded += 1; } } } } } #endregion } catch (WebException ex) { if (log.IsErrorEnabled) { string logMsg = String.Format("There was a problem trying to read the feed for url {0}. Ignoring.", feedInfo.RssUrl); log.Error(logMsg, ex); } } catch (UriFormatException ex) { if (log.IsErrorEnabled) { string logMsg = String.Format("There was a problem trying to read the feed for url {0}. Ignoring.", feedInfo.RssUrl); log.Error(logMsg, ex); } } catch (System.Net.Sockets.SocketException ex) { if (log.IsErrorEnabled) { string logMsg = String.Format("There was a problem trying to read the feed for url {0}. Ignoring.", feedInfo.RssUrl); log.Error(logMsg, ex); } } catch (System.Xml.XmlException ex) { if (log.IsErrorEnabled) { string logMsg = String.Format("There was a problem trying to read the feed for url {0}. Ignoring.", feedInfo.RssUrl); log.Error(logMsg, ex); } } catch (System.Security.SecurityException ex) { log.Error("Could not load feed due to security exception. Must be running in restricted trust level. Creating server side web requests is not allowed in current configuration.", ex); } catch (System.Data.Common.DbException ex) { log.Error("Error updating feed database cache", ex); } } finally { if (FeedManagerConfiguration.UseReadWriteLockForCacheMenagement) { try { cacheLock.ReleaseWriterLock(); } catch (ApplicationException ex) { log.Error("swallowed error", ex); } } } }
public static DataTable GetRssFeedEntries( int moduleId, Guid moduleGuid, int entryCacheTimeout, int maxDaysOld, int maxEntriesPerFeed, bool enableSelectivePublishing) { DateTime cutoffDate = DateTime.UtcNow.AddDays(-maxDaysOld); DateTime cacheExpiration = DateTime.UtcNow.AddMinutes(-entryCacheTimeout); DateTime lastCacheTime = mojoPortal.Business.RssFeed.GetLastCacheTime(moduleGuid); if (lastCacheTime > cacheExpiration) { // data "cached" in the db has not expired so just return it return(mojoPortal.Business.RssFeed.GetEntries(moduleGuid)); } try { if (FeedManagerConfiguration.UseReadWriteLockForCacheMenagement) { cacheLock.AcquireWriterLock(cacheLockTimeoutInMilliseconds); } //if (debugLog) { log.Debug("got lock in GetRssFeeds"); } lastCacheTime = mojoPortal.Business.RssFeed.GetLastCacheTime(moduleGuid); if (lastCacheTime > cacheExpiration) { // data "cached" in the db has not expired so just return it return(mojoPortal.Business.RssFeed.GetEntries(moduleGuid)); } if (enableSelectivePublishing) { mojoPortal.Business.RssFeed.DeleteExpiredEntriesByModule(moduleGuid, cutoffDate); mojoPortal.Business.RssFeed.DeleteUnPublishedEntriesByModule(moduleGuid); } else { mojoPortal.Business.RssFeed.DeleteEntriesByModule(moduleGuid); } DataTable dtFeeds = mojoPortal.Business.RssFeed.GetFeeds(moduleId); string siteRoot = SiteUtils.GetNavigationSiteRoot(); string secureSiteRoot = SiteUtils.GetSecureNavigationSiteRoot(); foreach (DataRow dr in dtFeeds.Rows) { Guid feedGuid = new Guid(dr["ItemGuid"].ToString()); int feedId = Convert.ToInt32(dr["ItemID"]); string feedUrl = dr["RssUrl"].ToString(); if (feedUrl.StartsWith("~/")) { feedUrl = WebUtils.ResolveServerUrl(feedUrl).Replace("https:", "http:"); } bool publishByDefault = Convert.ToBoolean(dr["PublishByDefault"]); int countOfPreservedEntries = Convert.ToInt32(dr["TotalEntries"]); bool publish = true; if (enableSelectivePublishing) { if (!publishByDefault) { publish = false; } } int entriesAdded = countOfPreservedEntries; try { GenericSyndicationFeed gsFeed = GenericSyndicationFeed.Create(new Uri(FormatFeedUrl(feedUrl, siteRoot, secureSiteRoot))); #region RSSFeed_management if (gsFeed.Format == SyndicationContentFormat.Rss) { Argotic.Syndication.RssFeed rssFeed = gsFeed.Resource as Argotic.Syndication.RssFeed; if (rssFeed != null) { foreach (Argotic.Syndication.RssItem rssItem in rssFeed.Channel.Items) { DateTime itemPubDate = EnsureDate(rssItem.PublicationDate); if ((itemPubDate >= cutoffDate) || (maxDaysOld == 0)) { if ((entriesAdded < maxEntriesPerFeed) || (maxEntriesPerFeed == 0)) { string entryBlob = rssItem.Title + rssItem.Link.ToString(); int entryHash = GetEntryHash(entryBlob); string channelLink = string.Empty; if ((rssFeed.Channel != null) && (rssFeed.Channel.Link != null)) { channelLink = rssFeed.Channel.Link.ToString(); } if (UpdateEntry( moduleGuid, itemPubDate, rssItem.Title, rssItem.Author, channelLink, rssItem.Description, rssItem.Link.ToString(), entryHash, feedGuid, feedId, publish) > 0) { entriesAdded += 1; } } } } } } #endregion #region ATOMFeed_management if (gsFeed.Format == SyndicationContentFormat.Atom) { Argotic.Syndication.AtomFeed atomFeed = gsFeed.Resource as Argotic.Syndication.AtomFeed; foreach (AtomEntry atItem in atomFeed.Entries) { string entryLink = string.Empty; StringBuilder entryAuthor = new StringBuilder(); string comma = string.Empty; DateTime itemPubDate = EnsureDate(atItem.UpdatedOn); if ((itemPubDate >= cutoffDate) || (maxDaysOld == 0)) { if ((entriesAdded < maxEntriesPerFeed) || (maxEntriesPerFeed == 0)) { foreach (AtomPersonConstruct atPerson in atItem.Authors) { entryAuthor.Append(comma + atPerson.Name); comma = ","; } if (entryAuthor.Length == 0) { foreach (AtomPersonConstruct atPerson in atomFeed.Authors) { entryAuthor.Append(comma + atPerson.Name); comma = ","; } } foreach (AtomLink atLink in atItem.Links) { if (atLink.Relation == "alternate") { entryLink = atLink.Uri.ToString(); } } if ((entryLink.Length == 0) && (atItem.Links.Count > 0)) { entryLink = atItem.Links[0].Uri.ToString(); } string content = string.Empty; if (atItem.Content == null) { if (atItem.Summary != null) { content = atItem.Summary.Content; } } else { content = atItem.Content.Content; } // commented out 2010-02-27 some feeds have only a title and link //if (content.Length == 0) { continue; } string entryBlob = atItem.Title.Content + entryLink; int entryHash = GetEntryHash(entryBlob); if (UpdateEntry( moduleGuid, itemPubDate, atItem.Title.Content, entryAuthor.ToString(), feedUrl, content, entryLink, entryHash, feedGuid, feedId, publish) > 0) { entriesAdded += 1; } } } } } #endregion } catch (WebException ex) { if (log.IsErrorEnabled) { string logMsg = String.Format("There was a problem trying to read the feed for url {0}. Ignoring.", (string)dr["RssUrl"]); log.Error(logMsg, ex); } } catch (UriFormatException ex) { if (log.IsErrorEnabled) { string logMsg = String.Format("There was a problem trying to read the feed for url {0}. Ignoring.", (string)dr["RssUrl"]); log.Error(logMsg, ex); } } catch (System.Net.Sockets.SocketException ex) { if (log.IsErrorEnabled) { string logMsg = String.Format("There was a problem trying to read the feed for url {0}. Ignoring.", (string)dr["RssUrl"]); log.Error(logMsg, ex); } } catch (System.Xml.XmlException ex) { if (log.IsErrorEnabled) { string logMsg = String.Format("There was a problem trying to read the feed for url {0}. Ignoring.", (string)dr["RssUrl"]); log.Error(logMsg, ex); } } catch (System.Security.SecurityException ex) { log.Error("Could not load feed due to security exception. Must be running in restricted trust level. Creating server side web requests is not allowed in current configuration.", ex); } catch (ArgumentNullException ex) { string logMsg = String.Format("There was a problem trying to read the feed for url {0}. Ignoring.", (string)dr["RssUrl"]); log.Error(logMsg, ex); } catch (System.Data.Common.DbException ex) { log.Error("Error updating feed database cache", ex); } } } finally { if (FeedManagerConfiguration.UseReadWriteLockForCacheMenagement) { try { cacheLock.ReleaseWriterLock(); } catch (ApplicationException ex) { log.Error("swallowed error", ex); } } } return(mojoPortal.Business.RssFeed.GetEntries(moduleGuid)); }
private static void StartLoadingFeed() { RssFeed feed = new RssFeed(); feed.Loaded += feed_Loaded; feed.LoadAsync(new Uri(FeedUrl), null); }
/// <summary> /// Modifies the <see cref="RssFeed"/> to match the data source. /// </summary> /// <param name="resource">The <see cref="RssFeed"/> to be filled.</param> /// <exception cref="ArgumentNullException">The <paramref name="resource"/> is a null reference (Nothing in Visual Basic).</exception> public void Fill(RssFeed resource) { //------------------------------------------------------------ // Validate parameter //------------------------------------------------------------ Guard.ArgumentNotNull(resource, "resource"); //------------------------------------------------------------ // Create namespace resolver //------------------------------------------------------------ XmlNamespaceManager manager = new XmlNamespaceManager(this.Navigator.NameTable); manager.AddNamespace("rdf", "http://www.w3.org/1999/02/22-rdf-syntax-ns#"); manager.AddNamespace("rss", "http://my.netscape.com/rdf/simple/0.9/"); //------------------------------------------------------------ // Attempt to fill syndication resource //------------------------------------------------------------ XPathNavigator channelNavigator = this.Navigator.SelectSingleNode("rdf:RDF/rss:channel", manager); if (channelNavigator != null) { Rss090SyndicationResourceAdapter.FillChannel(resource.Channel, channelNavigator, manager, this.Settings); } XPathNavigator imageNavigator = this.Navigator.SelectSingleNode("rdf:RDF/rss:image", manager); if (imageNavigator != null) { resource.Channel.Image = new RssImage(); Rss090SyndicationResourceAdapter.FillImage(resource.Channel.Image, imageNavigator, manager, this.Settings); } XPathNavigator textInputNavigator = this.Navigator.SelectSingleNode("rdf:RDF/rss:textinput", manager); if (textInputNavigator != null) { resource.Channel.TextInput = new RssTextInput(); Rss090SyndicationResourceAdapter.FillTextInput(resource.Channel.TextInput, textInputNavigator, manager, this.Settings); } XPathNodeIterator itemIterator = this.Navigator.Select("rdf:RDF/rss:item", manager); if (itemIterator != null && itemIterator.Count > 0) { int counter = 0; while (itemIterator.MoveNext()) { RssItem item = new RssItem(); counter++; if (this.Settings.RetrievalLimit != 0 && counter > this.Settings.RetrievalLimit) { break; } XPathNavigator titleNavigator = itemIterator.Current.SelectSingleNode("rss:title", manager); XPathNavigator linkNavigator = itemIterator.Current.SelectSingleNode("rss:link", manager); if (titleNavigator != null) { item.Title = titleNavigator.Value; } if (linkNavigator != null) { Uri link; if (Uri.TryCreate(linkNavigator.Value, UriKind.RelativeOrAbsolute, out link)) { item.Link = link; } } SyndicationExtensionAdapter itemExtensionAdapter = new SyndicationExtensionAdapter(itemIterator.Current, this.Settings); itemExtensionAdapter.Fill(item, manager); ((Collection<RssItem>)resource.Channel.Items).Add(item); } } SyndicationExtensionAdapter feedExtensionAdapter = new SyndicationExtensionAdapter(this.Navigator.SelectSingleNode("rdf:RDF", manager), this.Settings); feedExtensionAdapter.Fill(resource, manager); }
private void RenderFeed() { if (siteSettings == null) { return; } Argotic.Syndication.RssFeed feed = new Argotic.Syndication.RssFeed(); RssChannel channel = new RssChannel(); channel.Generator = "mojoPortal CMS Recent Content Feed Geenrator"; feed.Channel = channel; List<IndexItem> recentContent = GetData(); // gets the data and initilizes the channel params if (!shouldRender) { WebUtils.SetupRedirect(this, redirectUrl); return; } if (channelTitle.Length == 0) { channelTitle = "Recent Content"; } //empty string will cause an error channel.Title = channelTitle; channel.Link = new System.Uri(channelLink); if (channelDescription.Length == 0) { channelDescription = "Recent Content"; } //empty string will cause an error channel.Description = channelDescription; channel.Copyright = channelCopyright; channel.ManagingEditor = channelManagingEditor; channel.TimeToLive = channelTimeToLive; int itemsAdded = 0; if (recentContent != null) { foreach (IndexItem indexItem in recentContent) { RssItem item = new RssItem(); string itemUrl = BuildUrl(indexItem); item.Link = new Uri(itemUrl); item.Guid = new RssGuid(itemUrl); item.Title = FormatLinkText(indexItem); item.PublicationDate = indexItem.LastModUtc; item.Author = indexItem.Author; item.Description = indexItem.ContentAbstract; channel.AddItem(item); itemsAdded += 1; } } if (itemsAdded == 0) { //channel must have at least one item RssItem item = new RssItem(); item.Link = new Uri(siteRoot); item.Title = "Stay tuned for future updates. "; //item.Description = item.PublicationDate = DateTime.UtcNow; channel.AddItem(item); } // no cache locally if (Request.Url.AbsolutePath.Contains("localhost")) { Response.Cache.SetExpires(DateTime.Now.AddMinutes(-30)); Response.Cache.SetCacheability(HttpCacheability.NoCache); } else { Response.Cache.SetExpires(DateTime.Now.AddMinutes(feedCacheTimeInMinutes)); Response.Cache.SetCacheability(HttpCacheability.Public); Response.Cache.VaryByParams["f;gc;n;pageid;mid"] = true; } Response.ContentType = "application/xml"; Encoding encoding = new UTF8Encoding(); Response.ContentEncoding = encoding; using (XmlTextWriter xmlTextWriter = new XmlTextWriter(Response.OutputStream, encoding)) { xmlTextWriter.Formatting = Formatting.Indented; ////////////////// // style for RSS Feed viewed in browsers if (ConfigurationManager.AppSettings["RSSCSS"] != null) { string rssCss = ConfigurationManager.AppSettings["RSSCSS"].ToString(); xmlTextWriter.WriteWhitespace(" "); xmlTextWriter.WriteRaw("<?xml-stylesheet type=\"text/css\" href=\"" + cssBaseUrl + rssCss + "\" ?>"); } if (ConfigurationManager.AppSettings["RSSXsl"] != null) { string rssXsl = ConfigurationManager.AppSettings["RSSXsl"].ToString(); xmlTextWriter.WriteWhitespace(" "); xmlTextWriter.WriteRaw("<?xml-stylesheet type=\"text/xsl\" href=\"" + cssBaseUrl + rssXsl + "\" ?>"); } /////////////////////////// feed.Save(xmlTextWriter); } }
private int GetRssFeedItems(RssFeed feed, Subscription subscription) { var itemsAdded = 0; foreach (var rssItem in feed.Channel.Items.Where(x => subscription.LastFeedUpdatesUTC == null || x.PublicationDate.ToUniversalTime() > subscription.LastFeedUpdatesUTC)) { var categories = rssItem.Categories.Aggregate(String.Empty, (current, category) => current + (category.Value + ",")).TrimEnd(','); var subscriptionPost = new SubscriptionPost { Categories = categories, OriginalUrl = rssItem.Link.ToString(), PublishDateUTC = GetGoodDateTime(rssItem.PublicationDate.ToUniversalTime()), Subscription = subscription, Title = rssItem.Title, Content = GetRssContent(rssItem), Authors = GetRssAuthors(rssItem) }; itemsAdded++; _dbContext.SubscriptionPosts.Add(subscriptionPost); subscription.SubscriptionPosts.Add(subscriptionPost); } return itemsAdded; }
/// <summary> /// Instantiates a <see cref="ISyndicationResource"/> that conforms to the specified <see cref="SyndicationContentFormat"/> using the supplied <see cref="Stream"/>. /// </summary> /// <param name="stream">The <see cref="Stream"/> used to load the syndication resource.</param> /// <param name="format">A <see cref="SyndicationContentFormat"/> enumeration value that indicates the type syndication resource the <paramref name="stream"/> represents.</param> /// <returns> /// An <see cref="ISyndicationResource"/> object that conforms to the specified <paramref name="format"/>, initialized using the supplied <paramref name="stream"/>. /// If the <paramref name="format"/> is not supported by the provider, returns a <b>null</b> reference. /// </returns> /// <exception cref="ArgumentNullException">The <paramref name="stream"/> is a null reference (Nothing in Visual Basic).</exception> private static ISyndicationResource BuildResource(SyndicationContentFormat format, Stream stream) { //------------------------------------------------------------ // Validate parameters //------------------------------------------------------------ Guard.ArgumentNotNull(stream, "stream"); //------------------------------------------------------------ // Create syndication resource based on content format //------------------------------------------------------------ if (format == SyndicationContentFormat.Apml) { ApmlDocument document = new ApmlDocument(); document.Load(stream); return document; } else if (format == SyndicationContentFormat.Atom) { XPathDocument document = new XPathDocument(stream); XPathNavigator navigator = document.CreateNavigator(); navigator.MoveToRoot(); navigator.MoveToChild(XPathNodeType.Element); if(String.Compare(navigator.LocalName, "entry", StringComparison.OrdinalIgnoreCase) == 0) { AtomEntry entry = new AtomEntry(); entry.Load(navigator); return entry; } else if (String.Compare(navigator.LocalName, "feed", StringComparison.OrdinalIgnoreCase) == 0) { AtomFeed feed = new AtomFeed(); feed.Load(navigator); return feed; } else { return null; } } else if (format == SyndicationContentFormat.BlogML) { BlogMLDocument document = new BlogMLDocument(); document.Load(stream); return document; } else if (format == SyndicationContentFormat.Opml) { OpmlDocument document = new OpmlDocument(); document.Load(stream); return document; } else if (format == SyndicationContentFormat.Rsd) { RsdDocument document = new RsdDocument(); document.Load(stream); return document; } else if (format == SyndicationContentFormat.Rss) { RssFeed feed = new RssFeed(); feed.Load(stream); return feed; } else { return null; } }
/// <summary> /// Loads the generic syndication feed using the specified <see cref="XPathNavigator"/> and <see cref="SyndicationResourceLoadSettings"/>. /// </summary> /// <param name="navigator">A read-only <see cref="XPathNavigator"/> object for navigating through the syndication resource information.</param> /// <param name="settings">The <see cref="SyndicationResourceLoadSettings"/> object used to configure the load operation of the <see cref="GenericSyndicationFeed"/>.</param> /// <param name="eventData">A <see cref="SyndicationResourceLoadedEventArgs"/> that contains the event data used when raising the <see cref="GenericSyndicationFeed.Loaded"/> event.</param> /// <remarks> /// After the load operation has successfully completed, the <see cref="GenericSyndicationFeed.Loaded"/> event is raised using the specified <paramref name="eventData"/>. /// </remarks> /// <exception cref="ArgumentNullException">The <paramref name="navigator"/> is a null reference (Nothing in Visual Basic).</exception> /// <exception cref="ArgumentNullException">The <paramref name="settings"/> is a null reference (Nothing in Visual Basic).</exception> /// <exception cref="ArgumentNullException">The <paramref name="eventData"/> is a null reference (Nothing in Visual Basic).</exception> /// <exception cref="FormatException">The <paramref name="navigator"/> data does not conform to the expected syndication content format. In this case, the feed remains empty.</exception> private void Load(XPathNavigator navigator, SyndicationResourceLoadSettings settings, SyndicationResourceLoadedEventArgs eventData) { //------------------------------------------------------------ // Validate parameters //------------------------------------------------------------ Guard.ArgumentNotNull(navigator, "navigator"); Guard.ArgumentNotNull(settings, "settings"); Guard.ArgumentNotNull(eventData, "eventData"); //------------------------------------------------------------ // Initialize generic feed based on syndication resource format //------------------------------------------------------------ SyndicationResourceMetadata metadata = new SyndicationResourceMetadata(navigator); if (metadata.Format == SyndicationContentFormat.Atom) { AtomFeed feed = new AtomFeed(); SyndicationResourceAdapter adapter = new SyndicationResourceAdapter(navigator, settings); adapter.Fill(feed, SyndicationContentFormat.Atom); this.Parse(feed); } else if (metadata.Format == SyndicationContentFormat.Rss) { RssFeed feed = new RssFeed(); SyndicationResourceAdapter adapter = new SyndicationResourceAdapter(navigator, settings); adapter.Fill(feed, SyndicationContentFormat.Rss); this.Parse(feed); } else if (metadata.Format == SyndicationContentFormat.Opml) { OpmlDocument opmlDoc = new OpmlDocument(); SyndicationResourceAdapter adapter = new SyndicationResourceAdapter(navigator, settings); adapter.Fill(opmlDoc, SyndicationContentFormat.Opml); this.Parse(opmlDoc); } //------------------------------------------------------------ // Raise Loaded event to notify registered handlers of state change //------------------------------------------------------------ this.OnFeedLoaded(eventData); }
private void RenderRss() { if (pageSettings == null) { return; } RssForum rssForum = new RssForum(); rssForum.SiteId = siteSettings.SiteId; rssForum.ModuleId = moduleId; rssForum.PageId = pageId; rssForum.ItemId = itemId; rssForum.ThreadId = threadId; rssForum.MaximumDays = maxDaysOld; Argotic.Syndication.RssFeed feed = new Argotic.Syndication.RssFeed(); RssChannel channel = new RssChannel(); channel.Generator = "mojoPortal Forum module"; string channelLink = WebUtils.ResolveServerUrl(SiteUtils.GetPageUrl(pageSettings)); channel.Link = new System.Uri(channelLink); // if (config.ChannelDescription.Length > 0) { channel.Description = config.ChannelDescription; } feed.Channel = channel; string target = navigationSiteRoot + "/Forums/Thread.aspx?pageid="; using (IDataReader posts = rssForum.GetPostsForRss()) { while ((posts.Read()) && (entryCount <= entriesLimit)) { string pageViewRoles = posts["AuthorizedRoles"].ToString(); string moduleViewRoles = posts["ViewRoles"].ToString(); bool include = (bypassPageSecurity || (pageViewRoles.Contains("All Users")) && ((moduleViewRoles.Length == 0) || (moduleViewRoles.Contains("All Users"))) ) ; if (!include) { continue; } RssItem item = new RssItem(); item.Title = posts["Subject"].ToString(); item.Description = SiteUtils.ChangeRelativeUrlsToFullyQualifiedUrls(navigationSiteRoot, imageSiteRoot, posts["Post"].ToString()); item.PublicationDate = Convert.ToDateTime(posts["PostDate"]); int p = Convert.ToInt32(posts["PageID"]); int t = Convert.ToInt32(posts["ThreadID"]); //if (target.IndexOf("&thread=") < 0 && target.IndexOf("?thread=") < 0) //{ // if (target.IndexOf("?") < 0) // { // target += "?thread=" + posts["ThreadID"].ToString() + "#post" + posts["PostID"].ToString(); // } // else // { // target += "&thread=" + posts["ThreadID"].ToString() + "#post" + posts["PostID"].ToString(); // } //} //https://www.mojoportal.com/Forums/Thread.aspx?pageid=5&t=11417~1#post47516 if ((isGoogleFeedReader) && (ForumConfiguration.UseOldParamsForGoogleReader)) { //item.Link = new System.Uri(target + p.ToInvariantString() + "&thread=" + t.ToInvariantString() + "#post" + posts["PostID"].ToString()); item.Link = new System.Uri(target + p.ToInvariantString() + "&thread=" + t.ToInvariantString()); } else { item.Link = new System.Uri(target + p.ToInvariantString() + "&t=" + t.ToInvariantString() + "~-1#post" + posts["PostID"].ToString()); } RssGuid g = new RssGuid(target, true); item.Guid = g; item.Author = posts["StartedBy"].ToString(); channel.AddItem(item); entryCount += 1; } } Response.Cache.SetExpires(DateTime.Now.AddMinutes(5)); Response.Cache.SetCacheability(HttpCacheability.Public); Response.ContentType = "application/xml"; Encoding encoding = new UTF8Encoding(); Response.ContentEncoding = encoding; using (XmlTextWriter xmlTextWriter = new XmlTextWriter(Response.OutputStream, encoding)) { xmlTextWriter.Formatting = Formatting.Indented; ////////////////// // style for RSS Feed viewed in browsers if (ConfigurationManager.AppSettings["RSSCSS"] != null) { string rssCss = ConfigurationManager.AppSettings["RSSCSS"].ToString(); xmlTextWriter.WriteWhitespace(" "); xmlTextWriter.WriteRaw("<?xml-stylesheet type=\"text/css\" href=\"" + cssBaseUrl + rssCss + "\" ?>"); } if (ConfigurationManager.AppSettings["RSSXsl"] != null) { string rssXsl = ConfigurationManager.AppSettings["RSSXsl"].ToString(); xmlTextWriter.WriteWhitespace(" "); xmlTextWriter.WriteRaw("<?xml-stylesheet type=\"text/xsl\" href=\"" + cssBaseUrl + rssXsl + "\" ?>"); } /////////////////////////// feed.Save(xmlTextWriter); } }
private int ReadSource(Source source,bool? IsForTest) { var count = 0; var client = new WebClient(); try { using (var stream = client.OpenRead(source.StreamUrl)) { try { #region RssFeed RssFeed feed = new RssFeed(); feed.Load(stream); foreach (var i in feed.Channel.Items) { try { if (ReadFeedItem(i, source,IsForTest)) count++; Thread.Sleep(500); } catch (Exception e) { var failed = new FailedUrl(); failed.Url = i.Link.ToString(); failed.Exception = e.Message; this.Data.FailedUrls.Add(failed); this.Data.SaveChanges(); continue; } } #endregion RssFeed } catch (FormatException f) { #region AtomFeed AtomFeed afeed = new AtomFeed(); using (var astream = client.OpenRead(source.StreamUrl)) { afeed.Load(astream); foreach (var i in afeed.Entries) { try { if (ReadFeedItem(i, source,IsForTest)) count++; Thread.Sleep(500); } catch (Exception e) { var failed = new FailedUrl(); failed.Url = i.Links.FirstOrDefault().ToString(); failed.Exception = e.Message; this.Data.FailedUrls.Add(failed); this.Data.SaveChanges(); continue; } } } #endregion AtomFeed } Source s = this.Data.Sources.FirstOrDefault(d => d.Id == source.Id); s.LastUpdated = DateTime.Now; this.Data.Sources.Update(s); this.Data.SaveChanges(); } //try //{ // if (count > 0) // CacheManager.Clear(CacheRegions.News); //} //catch (Exception e) //{ // //TODO handle exc //} } catch (Exception e) { //TODO handle exc } Console.WriteLine(source.Name); return count; }
private void RenderRss() { Argotic.Syndication.RssFeed feed = new Argotic.Syndication.RssFeed(); RssChannel channel = new RssChannel(); channel.Generator = "mojoPortal Blog Module"; channel.Language = SiteUtils.GetDefaultCulture(); feed.Channel = channel; if (module.ModuleTitle.Length > 0) { channel.Title = module.ModuleTitle; } else { channel.Title = "Blog"; // it will cause an error if this is left blank so we must populate it if the module title is an emty string. } // this became broken when we combined query string params, since pageid is not one of the params this always returns the home page url // instead of the blog page url //string pu = WebUtils.ResolveServerUrl(SiteUtils.GetCurrentPageUrl()); string pu = WebUtils.ResolveServerUrl(SiteUtils.GetPageUrl(pageSettings)); channel.Link = new System.Uri(pu); channel.SelfLink = Request.Url; if (config.ChannelDescription.Length > 0) { channel.Description = config.ChannelDescription; } if (config.Copyright.Length > 0) { channel.Copyright = config.Copyright; } channel.ManagingEditor = config.ManagingEditorEmail; if (config.ManagingEditorName.Length > 0) { channel.ManagingEditor += " (" + config.ManagingEditorName + ")"; } if (config.FeedTimeToLive > -1) { channel.TimeToLive = config.FeedTimeToLive; } // Create and add iTunes information to feed channel ITunesSyndicationExtension channelExtension = new ITunesSyndicationExtension(); channelExtension.Context.Subtitle = config.ChannelDescription; if (config.HasExplicitContent) { channelExtension.Context.ExplicitMaterial = ITunesExplicitMaterial.Yes; } else { channelExtension.Context.ExplicitMaterial = ITunesExplicitMaterial.No; } channelExtension.Context.Author = config.ManagingEditorEmail; if (config.ManagingEditorName.Length > 0) { channelExtension.Context.Author += " (" + config.ManagingEditorName + ")"; } channelExtension.Context.Summary = config.ChannelDescription; channelExtension.Context.Owner = new ITunesOwner(config.ManagingEditorEmail, config.ManagingEditorName); if (config.FeedLogoUrl.Length > 0) { try { channelExtension.Context.Image = new Uri(config.FeedLogoUrl); } catch (ArgumentNullException) { } catch (UriFormatException) { } } if (config.FeedMainCategory.Length > 0) { ITunesCategory mainCat = new ITunesCategory(config.FeedMainCategory); if (config.FeedSubCategory.Length > 0) { mainCat.Categories.Add(new ITunesCategory(config.FeedSubCategory)); } channelExtension.Context.Categories.Add(mainCat); } feed.Channel.AddExtension(channelExtension); DataSet dsBlogPosts = GetData(); DataTable posts = dsBlogPosts.Tables["Posts"]; foreach (DataRow dr in posts.Rows) { bool inFeed = Convert.ToBoolean(dr["IncludeInFeed"]); if (!inFeed) { continue; } RssItem item = new RssItem(); int itemId = Convert.ToInt32(dr["ItemID"]); string blogItemUrl = FormatBlogUrl(dr["ItemUrl"].ToString(), itemId); item.Link = new Uri(Request.Url, blogItemUrl); item.Guid = new RssGuid(blogItemUrl); item.Title = dr["Heading"].ToString(); item.PublicationDate = Convert.ToDateTime(dr["StartDate"]); bool showAuthor = Convert.ToBoolean(dr["ShowAuthorName"]); if (showAuthor) { // techically this is supposed to be an email address // but wouldn't that lead to a lot of spam? string authorEmail = dr["Email"].ToString(); string authorName = dr["Name"].ToString(); if (BlogConfiguration.IncludeAuthorEmailInFeed) { item.Author = authorEmail + " (" + authorName + ")"; } else { item.Author = authorName; } } else if (config.ManagingEditorEmail.Length > 0) { item.Author = config.ManagingEditorEmail; } item.Comments = new Uri(blogItemUrl); string signature = string.Empty; if (config.AddSignature) { signature = "<br /><a href='" + blogItemUrl + "'>" + dr["Name"].ToString() + "</a>"; } if ((config.AddCommentsLinkToFeed) && (config.AllowComments)) { signature += " " + "<a href='" + blogItemUrl + "'>...</a>"; } if (config.AddTweetThisToFeed) { signature += GenerateTweetThisLink(item.Title, blogItemUrl); } if (config.AddFacebookLikeToFeed) { signature += GenerateFacebookLikeButton(blogItemUrl); } string blogPost = SiteUtils.ChangeRelativeUrlsToFullyQualifiedUrls(navigationSiteRoot, imageSiteRoot, dr["Description"].ToString().RemoveCDataTags()); string staticMapLink = BuildStaticMapMarkup(dr); if (staticMapLink.Length > 0) { // add a google static map blogPost += staticMapLink; } if ((!config.UseExcerptInFeed) || (blogPost.Length <= config.ExcerptLength)) { item.Description = blogPost + signature; } else { string excerpt = SiteUtils.ChangeRelativeUrlsToFullyQualifiedUrls(navigationSiteRoot, imageSiteRoot, dr["Abstract"].ToString().RemoveCDataTags()); if ((excerpt.Length > 0) && (excerpt != "<p> </p>")) { excerpt = excerpt + config.ExcerptSuffix + " <a href='" + blogItemUrl + "'>" + config.MoreLinkText + "</a><div class='excerptspacer'> </div>"; } else { excerpt = UIHelper.CreateExcerpt(dr["Description"].ToString(), config.ExcerptLength, config.ExcerptSuffix) + " <a href='" + blogItemUrl + "'>" + config.MoreLinkText + "</a><div class='excerptspacer'> </div>"; ; } item.Description = excerpt; } // how to add media enclosures for podcasting //http://www.podcast411.com/howto_1.html //http://argotic.codeplex.com/wikipage?title=Generating%20an%20extended%20RSS%20feed //http://techwhimsy.com/stream-mp3s-with-google-mp3-player //Uri url = new Uri("http://media.libsyn.com/media/podcast411/411_060325.mp3"); //string type = "audio/mpeg"; //long length = 11779397; string blogGuid = dr["BlogGuid"].ToString(); string whereClause = string.Format("ItemGuid = '{0}'", blogGuid); if (!config.UseExcerptInFeed) { DataView dv = new DataView(dsBlogPosts.Tables["Attachments"], whereClause, "", DataViewRowState.CurrentRows); foreach (DataRowView rowView in dv) { DataRow row = rowView.Row; Uri mediaUrl = new Uri(WebUtils.ResolveServerUrl(attachmentBaseUrl + row["ServerFileName"].ToString())); long contentLength = Convert.ToInt64(row["ContentLength"]); string contentType = row["ContentType"].ToString(); RssEnclosure enclosure = new RssEnclosure(contentLength, contentType, mediaUrl); item.Enclosures.Add(enclosure); //http://argotic.codeplex.com/wikipage?title=Generating%20an%20extended%20RSS%20feed ITunesSyndicationExtension itemExtension = new ITunesSyndicationExtension(); itemExtension.Context.Author = dr["Name"].ToString(); itemExtension.Context.Subtitle = dr["SubTitle"].ToString(); //itemExtension.Context.Summary = "The iTunes syndication extension properties that are used vary based on whether extending the channel or an item"; //itemExtension.Context.Duration = new TimeSpan(1, 2, 13); //itemExtension.Context.Keywords.Add("Podcast"); //itemExtension.Context.Keywords.Add("iTunes"); whereClause = string.Format("ItemID = '{0}'", itemId); DataView dvCat = new DataView(dsBlogPosts.Tables["Categories"], whereClause, "", DataViewRowState.CurrentRows); foreach (DataRowView rView in dvCat) { DataRow r = rView.Row; item.Categories.Add(new RssCategory(r["Category"].ToString())); itemExtension.Context.Keywords.Add(r["Category"].ToString()); } item.AddExtension(itemExtension); } } channel.AddItem(item); } if ((config.FeedburnerFeedUrl.Length > 0) || (Request.Url.AbsolutePath.Contains("localhost"))) { Response.Cache.SetExpires(DateTime.Now.AddMinutes(-30)); Response.Cache.SetCacheability(HttpCacheability.NoCache); Response.Cache.VaryByParams["r"] = true; } else { Response.Cache.SetExpires(DateTime.Now.AddMinutes(30)); Response.Cache.SetCacheability(HttpCacheability.Public); } Response.ContentType = "application/xml"; Encoding encoding = new UTF8Encoding(); Response.ContentEncoding = encoding; using (XmlTextWriter xmlTextWriter = new XmlTextWriter(Response.OutputStream, encoding)) { xmlTextWriter.Formatting = Formatting.Indented; ////////////////// // style for RSS Feed viewed in browsers if (ConfigurationManager.AppSettings["RSSCSS"] != null) { string rssCss = ConfigurationManager.AppSettings["RSSCSS"].ToString(); xmlTextWriter.WriteWhitespace(" "); xmlTextWriter.WriteRaw("<?xml-stylesheet type=\"text/css\" href=\"" + cssBaseUrl + rssCss + "\" ?>"); } if (ConfigurationManager.AppSettings["RSSXsl"] != null) { string rssXsl = ConfigurationManager.AppSettings["RSSXsl"].ToString(); xmlTextWriter.WriteWhitespace(" "); xmlTextWriter.WriteRaw("<?xml-stylesheet type=\"text/xsl\" href=\"" + cssBaseUrl + rssXsl + "\" ?>"); } /////////////////////////// feed.Save(xmlTextWriter); } }
public void BasicGeocoding_FullTest() { var strXml = ExtensionTestUtil.GetWrappedXml(namespc, strExtXml); using (XmlReader reader = new XmlTextReader(strXml, XmlNodeType.Document, null)) { RssFeed feed = new RssFeed(); feed.Load(reader); // Assert.IsTrue(feed.Channel.HasExtensions); // Assert.IsInstanceOfType(feed.Channel.FindExtension(BasicGeocodingSyndicationExtension.MatchByType) as BasicGeocodingSyndicationExtension, // typeof(BasicGeocodingSyndicationExtension)); Assert.AreEqual(1, feed.Channel.Items.Count()); var item = feed.Channel.Items.Single(); Assert.IsTrue(item.HasExtensions); var itemExtension = item.FindExtension<BasicGeocodingSyndicationExtension>(); Assert.IsNotNull(itemExtension); Assert.IsInstanceOfType(item.FindExtension(BasicGeocodingSyndicationExtension.MatchByType) as BasicGeocodingSyndicationExtension, typeof(BasicGeocodingSyndicationExtension)); } }
/// <summary> /// Initializes the generic syndication feed using the supplied <see cref="RssFeed"/>. /// </summary> /// <param name="feed">The <see cref="RssFeed"/> to build an abstraction against.</param> /// <exception cref="ArgumentNullException">The <paramref name="feed"/> is a null reference (Nothing in Visual Basic).</exception> public void Parse(RssFeed feed) { //------------------------------------------------------------ // Validate parameters //------------------------------------------------------------ Guard.ArgumentNotNull(feed, "feed"); //------------------------------------------------------------ // Initialize generic feed //------------------------------------------------------------ feedResource = feed; feedFormat = SyndicationContentFormat.Rss; if (!String.IsNullOrEmpty(feed.Channel.Title)) { feedTitle = feed.Channel.Title; } if (!String.IsNullOrEmpty(feed.Channel.Description)) { feedDescription = feed.Channel.Description; } if (feed.Channel.LastBuildDate != DateTime.MinValue) { feedLastUpdatedOn = feed.Channel.LastBuildDate; } if (feed.Channel.Language != null) { feedLanguage = feed.Channel.Language; } foreach (RssCategory category in feed.Channel.Categories) { GenericSyndicationCategory genericCategory = new GenericSyndicationCategory(category); feedCategories.Add(genericCategory); } foreach (RssItem item in feed.Channel.Items) { GenericSyndicationItem genericItem = new GenericSyndicationItem(item); ((Collection<GenericSyndicationItem>)feedItems).Add(genericItem); } }
/// <summary> /// Creates a new <see cref="RssFeed"/> instance using the specified <see cref="Uri"/>, <see cref="ICredentials"/>, <see cref="IWebProxy"/>, and <see cref="SyndicationResourceLoadSettings"/> object. /// </summary> /// <param name="source">A <see cref="Uri"/> that represents the URL of the syndication resource XML data.</param> /// <param name="options">A <see cref="WebRequestOptions"/> that holds options that should be applied to web requests.</param> /// <param name="settings">The <see cref="SyndicationResourceLoadSettings"/> object used to configure the <see cref="RssFeed"/> instance. This value can be <b>null</b>.</param> /// <returns>An <see cref="RssFeed"/> object loaded using the <paramref name="source"/> data.</returns> /// <exception cref="ArgumentNullException">The <paramref name="source"/> is a null reference (Nothing in Visual Basic).</exception> /// <exception cref="FormatException">The <paramref name="source"/> data does not conform to the expected syndication content format. In this case, the feed remains empty.</exception> public static RssFeed Create(Uri source, WebRequestOptions options, SyndicationResourceLoadSettings settings) { //------------------------------------------------------------ // Local members //------------------------------------------------------------ RssFeed syndicationResource = new RssFeed(); //------------------------------------------------------------ // Validate parameters //------------------------------------------------------------ Guard.ArgumentNotNull(source, "source"); //------------------------------------------------------------ // Create new instance using supplied parameters //------------------------------------------------------------ syndicationResource.Load(source, options, settings); return syndicationResource; }
/// <summary> /// Called when a corresponding asynchronous load operation completes. /// </summary> /// <param name="result">The result of the asynchronous operation.</param> private static void AsyncLoadCallback(IAsyncResult result) { //------------------------------------------------------------ // Local members //------------------------------------------------------------ System.Text.Encoding encoding = System.Text.Encoding.UTF8; XPathNavigator navigator = null; WebRequest httpWebRequest = null; GenericSyndicationFeed feed = null; Uri source = null; WebRequestOptions options = null; SyndicationResourceLoadSettings settings = null; //------------------------------------------------------------ // Determine if the async send operation completed //------------------------------------------------------------ if (result.IsCompleted) { //------------------------------------------------------------ // Extract the send operations parameters from the user state //------------------------------------------------------------ object[] parameters = (object[])result.AsyncState; httpWebRequest = parameters[0] as WebRequest; feed = parameters[1] as GenericSyndicationFeed; source = parameters[2] as Uri; settings = parameters[3] as SyndicationResourceLoadSettings; options = parameters[4] as WebRequestOptions; object userToken = parameters[5]; //------------------------------------------------------------ // Verify expected parameters were found //------------------------------------------------------------ if (feed != null) { //------------------------------------------------------------ // Get the response to the syndication resource request //------------------------------------------------------------ WebResponse httpWebResponse = (WebResponse)httpWebRequest.EndGetResponse(result); //------------------------------------------------------------ // Load syndication resource //------------------------------------------------------------ using (Stream stream = httpWebResponse.GetResponseStream()) { if (settings != null) { encoding = settings.CharacterEncoding; } using (StreamReader streamReader = new StreamReader(stream, encoding)) { XmlReaderSettings readerSettings = new XmlReaderSettings(); readerSettings.IgnoreComments = true; readerSettings.IgnoreWhitespace = true; readerSettings.ProhibitDtd = false; using (XmlReader reader = XmlReader.Create(streamReader, readerSettings)) { if (encoding == System.Text.Encoding.UTF8) { navigator = SyndicationEncodingUtility.CreateSafeNavigator(source, options, null); } else { navigator = SyndicationEncodingUtility.CreateSafeNavigator(source, options, settings.CharacterEncoding); } //------------------------------------------------------------ // Initialize generic feed based on syndication resource format //------------------------------------------------------------ SyndicationResourceMetadata metadata = new SyndicationResourceMetadata(navigator); if (metadata.Format == SyndicationContentFormat.Atom) { AtomFeed atomFeed = new AtomFeed(); SyndicationResourceAdapter adapter = new SyndicationResourceAdapter(navigator, settings); adapter.Fill(atomFeed, SyndicationContentFormat.Atom); feed.Parse(atomFeed); } else if (metadata.Format == SyndicationContentFormat.Rss) { RssFeed rssFeed = new RssFeed(); SyndicationResourceAdapter adapter = new SyndicationResourceAdapter(navigator, settings); adapter.Fill(rssFeed, SyndicationContentFormat.Rss); feed.Parse(rssFeed); } //------------------------------------------------------------ // Raise Loaded event to notify registered handlers of state change //------------------------------------------------------------ feed.OnFeedLoaded(new SyndicationResourceLoadedEventArgs(navigator, source, options, userToken)); } } } //------------------------------------------------------------ // Reset load operation in progress indicator //------------------------------------------------------------ feed.LoadOperationInProgress = false; } } }
private void RenderRss() { Argotic.Syndication.RssFeed feed = new Argotic.Syndication.RssFeed(); RssChannel channel = new RssChannel(); channel.Generator = "mojoPortal Blog Module"; channel.Language = SiteUtils.GetDefaultCulture(); feed.Channel = channel; if (module.ModuleTitle.Length > 0) { channel.Title = module.ModuleTitle; } else { channel.Title = "Blog"; // it will cause an error if this is left blank so we must populate it if the module title is an emty string. } // this became broken when we combined query string params, since pageid is not one of the params this always returns the home page url // instead of the blog page url //string pu = WebUtils.ResolveServerUrl(SiteUtils.GetCurrentPageUrl()); string pu = WebUtils.ResolveServerUrl(SiteUtils.GetPageUrl(pageSettings)); channel.Link = new System.Uri(pu); channel.SelfLink = Request.Url; if (config.ChannelDescription.Length > 0) { channel.Description = config.ChannelDescription; } if (config.Copyright.Length > 0) { channel.Copyright = config.Copyright; } channel.ManagingEditor = config.ManagingEditorEmail; if (config.ManagingEditorName.Length > 0) { channel.ManagingEditor += " (" + config.ManagingEditorName + ")"; } if (config.FeedTimeToLive > -1) { channel.TimeToLive = config.FeedTimeToLive; } // Create and add iTunes information to feed channel ITunesSyndicationExtension channelExtension = new ITunesSyndicationExtension(); channelExtension.Context.Subtitle = config.ChannelDescription; if (config.HasExplicitContent) { channelExtension.Context.ExplicitMaterial = ITunesExplicitMaterial.Yes; } else { channelExtension.Context.ExplicitMaterial = ITunesExplicitMaterial.No; } channelExtension.Context.Author = config.ManagingEditorEmail; if (config.ManagingEditorName.Length > 0) { channelExtension.Context.Author += " (" + config.ManagingEditorName + ")"; } channelExtension.Context.Summary = config.ChannelDescription; channelExtension.Context.Owner = new ITunesOwner(config.ManagingEditorEmail, config.ManagingEditorName); if (config.FeedLogoUrl.Length > 0) { try { channelExtension.Context.Image = new Uri(config.FeedLogoUrl); } catch (ArgumentNullException) { } catch (UriFormatException) { } } if (config.FeedMainCategory.Length > 0) { ITunesCategory mainCat = new ITunesCategory(config.FeedMainCategory); if (config.FeedSubCategory.Length > 0) { mainCat.Categories.Add(new ITunesCategory(config.FeedSubCategory)); } channelExtension.Context.Categories.Add(mainCat); } feed.Channel.AddExtension(channelExtension); DataSet dsBlogPosts = GetData(); DataTable posts = dsBlogPosts.Tables["Posts"]; foreach (DataRow dr in posts.Rows) { bool inFeed = Convert.ToBoolean(dr["IncludeInFeed"]); if (!inFeed) { continue; } RssItem item = new RssItem(); int itemId = Convert.ToInt32(dr["ItemID"]); string blogItemUrl = FormatBlogUrl(dr["ItemUrl"].ToString(), itemId); item.Link = new Uri(Request.Url, blogItemUrl); item.Guid = new RssGuid(blogItemUrl); item.Title = dr["Heading"].ToString(); item.PublicationDate = Convert.ToDateTime(dr["StartDate"]); bool showAuthor = Convert.ToBoolean(dr["ShowAuthorName"]); if (showAuthor) { // techically this is supposed to be an email address // but wouldn't that lead to a lot of spam? string authorEmail = dr["Email"].ToString(); string authorName = dr["Name"].ToString(); if (BlogConfiguration.IncludeAuthorEmailInFeed) { item.Author = authorEmail + " (" + authorName + ")"; } else { item.Author = authorName; } } else if (config.ManagingEditorEmail.Length > 0) { item.Author = config.ManagingEditorEmail; } item.Comments = new Uri(blogItemUrl); string signature = string.Empty; if (config.AddSignature) { signature = "<br /><a href='" + blogItemUrl + "'>" + dr["Name"].ToString() + "</a>"; } if ((config.AddCommentsLinkToFeed) && (config.AllowComments)) { signature += " " + "<a href='" + blogItemUrl + "'>...</a>"; } if (config.AddTweetThisToFeed) { signature += GenerateTweetThisLink(item.Title, blogItemUrl); } if (config.AddFacebookLikeToFeed) { signature += GenerateFacebookLikeButton(blogItemUrl); } string blogPost = SiteUtils.ChangeRelativeUrlsToFullyQualifiedUrls(navigationSiteRoot, imageSiteRoot, dr["Description"].ToString().RemoveCDataTags()); string staticMapLink = BuildStaticMapMarkup(dr); if (staticMapLink.Length > 0) { // add a google static map blogPost += staticMapLink; } if ((!config.UseExcerptInFeed) || (blogPost.Length <= config.ExcerptLength)) { item.Description = blogPost + signature; } else { string excerpt = SiteUtils.ChangeRelativeUrlsToFullyQualifiedUrls(navigationSiteRoot, imageSiteRoot, dr["Abstract"].ToString().RemoveCDataTags()); if ((excerpt.Length > 0) && (excerpt != "<p> </p>")) { excerpt = excerpt + config.ExcerptSuffix + " <a href='" + blogItemUrl + "'>" + config.MoreLinkText + "</a><div class='excerptspacer'> </div>"; } else { excerpt = UIHelper.CreateExcerpt(dr["Description"].ToString(), config.ExcerptLength, config.ExcerptSuffix) + " <a href='" + blogItemUrl + "'>" + config.MoreLinkText + "</a><div class='excerptspacer'> </div>";; } item.Description = excerpt; } // how to add media enclosures for podcasting //http://www.podcast411.com/howto_1.html //http://argotic.codeplex.com/wikipage?title=Generating%20an%20extended%20RSS%20feed //http://techwhimsy.com/stream-mp3s-with-google-mp3-player //Uri url = new Uri("http://media.libsyn.com/media/podcast411/411_060325.mp3"); //string type = "audio/mpeg"; //long length = 11779397; string blogGuid = dr["BlogGuid"].ToString(); string whereClause = string.Format("ItemGuid = '{0}'", blogGuid); if (!config.UseExcerptInFeed) { DataView dv = new DataView(dsBlogPosts.Tables["Attachments"], whereClause, "", DataViewRowState.CurrentRows); foreach (DataRowView rowView in dv) { DataRow row = rowView.Row; Uri mediaUrl = new Uri(WebUtils.ResolveServerUrl(attachmentBaseUrl + row["ServerFileName"].ToString())); long contentLength = Convert.ToInt64(row["ContentLength"]); string contentType = row["ContentType"].ToString(); RssEnclosure enclosure = new RssEnclosure(contentLength, contentType, mediaUrl); item.Enclosures.Add(enclosure); //http://argotic.codeplex.com/wikipage?title=Generating%20an%20extended%20RSS%20feed ITunesSyndicationExtension itemExtension = new ITunesSyndicationExtension(); itemExtension.Context.Author = dr["Name"].ToString(); itemExtension.Context.Subtitle = dr["SubTitle"].ToString(); //itemExtension.Context.Summary = "The iTunes syndication extension properties that are used vary based on whether extending the channel or an item"; //itemExtension.Context.Duration = new TimeSpan(1, 2, 13); //itemExtension.Context.Keywords.Add("Podcast"); //itemExtension.Context.Keywords.Add("iTunes"); whereClause = string.Format("ItemID = '{0}'", itemId); DataView dvCat = new DataView(dsBlogPosts.Tables["Categories"], whereClause, "", DataViewRowState.CurrentRows); foreach (DataRowView rView in dvCat) { DataRow r = rView.Row; item.Categories.Add(new RssCategory(r["Category"].ToString())); itemExtension.Context.Keywords.Add(r["Category"].ToString()); } item.AddExtension(itemExtension); } } channel.AddItem(item); } if ((config.FeedburnerFeedUrl.Length > 0) || (Request.Url.AbsolutePath.Contains("localhost"))) { Response.Cache.SetExpires(DateTime.Now.AddMinutes(-30)); Response.Cache.SetCacheability(HttpCacheability.NoCache); Response.Cache.VaryByParams["r"] = true; } else { Response.Cache.SetExpires(DateTime.Now.AddMinutes(30)); Response.Cache.SetCacheability(HttpCacheability.Public); } Response.ContentType = "application/xml"; Encoding encoding = new UTF8Encoding(); Response.ContentEncoding = encoding; using (XmlTextWriter xmlTextWriter = new XmlTextWriter(Response.OutputStream, encoding)) { xmlTextWriter.Formatting = Formatting.Indented; ////////////////// // style for RSS Feed viewed in browsers if (ConfigurationManager.AppSettings["RSSCSS"] != null) { string rssCss = ConfigurationManager.AppSettings["RSSCSS"].ToString(); xmlTextWriter.WriteWhitespace(" "); xmlTextWriter.WriteRaw("<?xml-stylesheet type=\"text/css\" href=\"" + cssBaseUrl + rssCss + "\" ?>"); } if (ConfigurationManager.AppSettings["RSSXsl"] != null) { string rssXsl = ConfigurationManager.AppSettings["RSSXsl"].ToString(); xmlTextWriter.WriteWhitespace(" "); xmlTextWriter.WriteRaw("<?xml-stylesheet type=\"text/xsl\" href=\"" + cssBaseUrl + rssXsl + "\" ?>"); } /////////////////////////// feed.Save(xmlTextWriter); } }
private void RenderFeed() { if (siteSettings == null) { return; } Argotic.Syndication.RssFeed feed = new Argotic.Syndication.RssFeed(); RssChannel channel = new RssChannel(); channel.Generator = "mojoPortal CMS Recent Content Feed Geenrator"; feed.Channel = channel; List <IndexItem> recentContent = GetData(); // gets the data and initilizes the channel params if (!shouldRender) { WebUtils.SetupRedirect(this, redirectUrl); return; } if (channelTitle.Length == 0) { channelTitle = "Recent Content"; } //empty string will cause an error channel.Title = channelTitle; channel.Link = new System.Uri(channelLink); if (channelDescription.Length == 0) { channelDescription = "Recent Content"; } //empty string will cause an error channel.Description = channelDescription; channel.Copyright = channelCopyright; channel.ManagingEditor = channelManagingEditor; channel.TimeToLive = channelTimeToLive; int itemsAdded = 0; if (recentContent != null) { foreach (IndexItem indexItem in recentContent) { RssItem item = new RssItem(); string itemUrl = BuildUrl(indexItem); item.Link = new Uri(itemUrl); item.Guid = new RssGuid(itemUrl); item.Title = FormatLinkText(indexItem); item.PublicationDate = indexItem.LastModUtc; item.Author = indexItem.Author; item.Description = indexItem.ContentAbstract; channel.AddItem(item); itemsAdded += 1; } } if (itemsAdded == 0) { //channel must have at least one item RssItem item = new RssItem(); item.Link = new Uri(siteRoot); item.Title = "Stay tuned for future updates. "; //item.Description = item.PublicationDate = DateTime.UtcNow; channel.AddItem(item); } // no cache locally if (Request.Url.AbsolutePath.Contains("localhost")) { Response.Cache.SetExpires(DateTime.Now.AddMinutes(-30)); Response.Cache.SetCacheability(HttpCacheability.NoCache); } else { Response.Cache.SetExpires(DateTime.Now.AddMinutes(feedCacheTimeInMinutes)); Response.Cache.SetCacheability(HttpCacheability.Public); Response.Cache.VaryByParams["f;gc;n;pageid;mid"] = true; } Response.ContentType = "application/xml"; Encoding encoding = new UTF8Encoding(); Response.ContentEncoding = encoding; using (XmlTextWriter xmlTextWriter = new XmlTextWriter(Response.OutputStream, encoding)) { xmlTextWriter.Formatting = Formatting.Indented; ////////////////// // style for RSS Feed viewed in browsers if (ConfigurationManager.AppSettings["RSSCSS"] != null) { string rssCss = ConfigurationManager.AppSettings["RSSCSS"].ToString(); xmlTextWriter.WriteWhitespace(" "); xmlTextWriter.WriteRaw("<?xml-stylesheet type=\"text/css\" href=\"" + cssBaseUrl + rssCss + "\" ?>"); } if (ConfigurationManager.AppSettings["RSSXsl"] != null) { string rssXsl = ConfigurationManager.AppSettings["RSSXsl"].ToString(); xmlTextWriter.WriteWhitespace(" "); xmlTextWriter.WriteRaw("<?xml-stylesheet type=\"text/xsl\" href=\"" + cssBaseUrl + rssXsl + "\" ?>"); } /////////////////////////// feed.Save(xmlTextWriter); } }
private void RenderRss() { DataView dv = FeedCache.GetRssFeedEntries( module.ModuleId, module.ModuleGuid, entryCacheTimeout, maxDaysOld, maxEntriesPerFeed, EnableSelectivePublishing).DefaultView; dv.Sort = "PubDate DESC"; if (dv.Table.Rows.Count == 0) { return; } Argotic.Syndication.RssFeed feed = new Argotic.Syndication.RssFeed(); RssChannel channel = new RssChannel(); channel.Generator = "mojoPortal Feed Manager module"; feed.Channel = channel; if (module != null) { channel.Title = module.ModuleTitle; channel.Description = module.ModuleTitle; //channel.LastBuildDate = channel.Items.LatestPubDate(); try { channel.Link = new System.Uri(WebUtils.ResolveServerUrl(SiteUtils.GetCurrentPageUrl())); } catch (UriFormatException) { channel.Link = new System.Uri(SiteUtils.GetNavigationSiteRoot()); } } else { // this prevents an error: Can't close RssWriter without first writing a channel. channel.Title = "Not Found"; channel.Description = "Not Found"; channel.LastBuildDate = DateTime.UtcNow; //channel.Link = new System.Uri(SiteUtils.GetCurrentPageUrl()); } foreach (DataRowView row in dv) { bool confirmed = Convert.ToBoolean(row["Confirmed"]); if (!EnableSelectivePublishing) { confirmed = true; } if (confirmed) { RssItem item = new RssItem(); item.Title = row["Title"].ToString(); item.Description = row["Description"].ToString(); item.PublicationDate = Convert.ToDateTime(row["PubDate"]); item.Link = new System.Uri(row["Link"].ToString()); Trace.Write(item.Link.ToString()); item.Author = row["Author"].ToString(); channel.AddItem(item); } } Response.Cache.SetExpires(DateTime.Now.AddMinutes(5)); Response.Cache.SetCacheability(HttpCacheability.Public); Response.ContentType = "application/xml"; Encoding encoding = new UTF8Encoding(); Response.ContentEncoding = encoding; using (XmlTextWriter xmlTextWriter = new XmlTextWriter(Response.OutputStream, encoding)) { xmlTextWriter.Formatting = Formatting.Indented; ////////////////// // style for RSS Feed viewed in browsers if (ConfigurationManager.AppSettings["RSSCSS"] != null) { string rssCss = ConfigurationManager.AppSettings["RSSCSS"].ToString(); xmlTextWriter.WriteWhitespace(" "); xmlTextWriter.WriteRaw("<?xml-stylesheet type=\"text/css\" href=\"" + cssBaseUrl + rssCss + "\" ?>"); } if (ConfigurationManager.AppSettings["RSSXsl"] != null) { string rssXsl = ConfigurationManager.AppSettings["RSSXsl"].ToString(); xmlTextWriter.WriteWhitespace(" "); xmlTextWriter.WriteRaw("<?xml-stylesheet type=\"text/xsl\" href=\"" + cssBaseUrl + rssXsl + "\" ?>"); } /////////////////////////// feed.Save(xmlTextWriter); } }
public void BasicGeocoding_LoadTest() { BasicGeocodingSyndicationExtension target = new BasicGeocodingSyndicationExtension(); // TODO: Initialize to an appropriate value var nt = new NameTable(); var ns = new XmlNamespaceManager(nt); var xpc = new XmlParserContext(nt, ns, "US-en",XmlSpace.Default); var strXml = ExtensionTestUtil.GetWrappedXml(namespc, strExtXml); using (XmlReader reader = new XmlTextReader(strXml, XmlNodeType.Document, xpc) ) { #if false //var document = new XPathDocument(reader); //var nav = document.CreateNavigator(); //nav.Select("//item"); do { if (!reader.Read()) break; } while (reader.NodeType != XmlNodeType.EndElement || reader.Name != "webMaster"); bool expected = true; bool actual; actual = target.Load(reader); Assert.AreEqual(expected, actual); #else RssFeed feed = new RssFeed(); feed.Load(reader); #endif } }