Esempio n. 1
0
        //============================================================
        //    CLASS SUMMARY
        //============================================================
        /// <summary>
        /// Provides example code for the AtomSource class.
        /// </summary>
        public static void ClassExample()
        {
            #region AtomSource
            AtomFeed feed   = new AtomFeed();

            feed.Id         = new AtomId(new Uri("urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6"));
            feed.Title      = new AtomTextConstruct("Example Feed");
            feed.UpdatedOn  = new DateTime(2003, 12, 13, 18, 30, 2);

            feed.Links.Add(new AtomLink(new Uri("http://example.org/")));
            feed.Links.Add(new AtomLink(new Uri("/feed"), "self"));

            feed.Authors.Add(new AtomPersonConstruct("John Doe"));

            AtomEntry entry = new AtomEntry();

            entry.Id        = new AtomId(new Uri("urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a"));
            entry.Title     = new AtomTextConstruct("Atom-Powered Robots Run Amok");
            entry.UpdatedOn = new DateTime(2003, 12, 13, 18, 30, 2);

            entry.Summary   = new AtomTextConstruct("Some text.");

            //  Entry was copied from another feed, so preserve source meta-data
            AtomSource source   = new AtomSource();
            source.Id           = new AtomId(new Uri("http://example2.org/"));
            source.Title        = new AtomTextConstruct("Fourty-Two");
            source.UpdatedOn    = new DateTime(2003, 11, 13, 18, 30, 2);
            source.Rights       = new AtomTextConstruct("© 2003 Example, Inc.");
            entry.Source        = source;

            feed.AddEntry(entry);
            #endregion
        }
Esempio n. 2
0
        //============================================================
        //    CLASS SUMMARY
        //============================================================
        /// <summary>
        /// Provides example code for the AtomTextConstruct class.
        /// </summary>
        public static void ClassExample()
        {
            #region AtomTextConstruct
            AtomFeed feed   = new AtomFeed();

            feed.Id         = new AtomId(new Uri("urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6"));
            feed.Title      = new AtomTextConstruct("Example Feed");
            feed.UpdatedOn  = new DateTime(2003, 12, 13, 18, 30, 2);

            feed.Links.Add(new AtomLink(new Uri("http://example.org/")));
            feed.Links.Add(new AtomLink(new Uri("/feed"), "self"));

            feed.Authors.Add(new AtomPersonConstruct("John Doe"));

            AtomEntry entry = new AtomEntry();

            entry.Id        = new AtomId(new Uri("urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a"));
            entry.Title     = new AtomTextConstruct("Atom-Powered Robots Run Amok");
            entry.UpdatedOn = new DateTime(2003, 12, 13, 18, 30, 2);

            //  Provide summary as entity escaped html
            AtomTextConstruct summary   = new AtomTextConstruct();
            summary.Content             = "AT&amp;amp;T bought &lt;b&gt;by SBC&lt;/b&gt;!";
            summary.TextType            = AtomTextConstructType.Html;
            entry.Summary               = summary;

            feed.AddEntry(entry);
            #endregion
        }
Esempio n. 3
0
        //============================================================
        //    CLASS SUMMARY
        //============================================================
        /// <summary>
        /// Provides example code for the AtomFeed class.
        /// </summary>
        public static void ClassExample()
        {
            #region AtomFeed
            AtomFeed feed   = new AtomFeed();

            feed.Id         = new AtomId(new Uri("urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6"));
            feed.Title      = new AtomTextConstruct("Example Feed");
            feed.UpdatedOn  = new DateTime(2003, 12, 13, 18, 30, 2);

            feed.Links.Add(new AtomLink(new Uri("http://example.org/")));
            feed.Links.Add(new AtomLink(new Uri("/feed"), "self"));

            feed.Authors.Add(new AtomPersonConstruct("John Doe"));

            AtomEntry entry = new AtomEntry();

            entry.Id        = new AtomId(new Uri("urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a"));
            entry.Title     = new AtomTextConstruct("Atom-Powered Robots Run Amok");
            entry.UpdatedOn = new DateTime(2003, 12, 13, 18, 30, 2);

            entry.Summary   = new AtomTextConstruct("Some text.");

            feed.AddEntry(entry);
            #endregion
        }
Esempio n. 4
0
        //============================================================
        //    CLASS SUMMARY
        //============================================================
        /// <summary>
        /// Provides example code for the AtomGenerator class.
        /// </summary>
        public static void ClassExample()
        {
            #region AtomGenerator
            AtomFeed feed   = new AtomFeed();

            feed.Id         = new AtomId(new Uri("urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6"));
            feed.Title      = new AtomTextConstruct("Example Feed");
            feed.UpdatedOn  = new DateTime(2003, 12, 13, 18, 30, 2);

            feed.Links.Add(new AtomLink(new Uri("http://example.org/")));
            feed.Links.Add(new AtomLink(new Uri("/feed"), "self"));

            feed.Authors.Add(new AtomPersonConstruct("John Doe"));

            //  Identify the software used to generate the feed
            AtomGenerator generator = new AtomGenerator("Example Toolkit");
            generator.Uri           = new Uri("/myblog.php");
            generator.Version       = "1.0";
            feed.Generator          = generator;

            AtomEntry entry = new AtomEntry();

            entry.Id        = new AtomId(new Uri("urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a"));
            entry.Title     = new AtomTextConstruct("Atom-Powered Robots Run Amok");
            entry.UpdatedOn = new DateTime(2003, 12, 13, 18, 30, 2);

            entry.Summary   = new AtomTextConstruct("Some text.");

            feed.AddEntry(entry);
            #endregion
        }
 private static string ToXmlString(AtomFeed feed)
 {
     var stringBuilder = new StringBuilder();
     var xmlWriter = XmlWriter.Create(stringBuilder);
     feed.Save(xmlWriter);
     xmlWriter.Flush();
     xmlWriter.Close();
     return stringBuilder.ToString();
 }
 private static AtomFeed CreateAtomFeed(DateTime updatedOn)
 {
     var feed = new AtomFeed
         {
             Id = new AtomId(new Uri("http://henrylawson.net/atom")),
             Title = new AtomTextConstruct("Henry Lawson"),
             UpdatedOn = updatedOn
         };
     feed.Authors.Add(new AtomPersonConstruct("Henry Lawson"));
     feed.Links.Add(new AtomLink
         {
             Uri = new Uri("http://henrylawson.net")
         });
     feed.Links.Add(new AtomLink
         {
             Relation = "self",
             Uri = new Uri("http://henrylawson.net/atom")
         });
     return feed;
 }
        protected override Feed CreateFeed(XmlReader reader, string url) {
            var atomFeed = new AtomFeed();
            atomFeed.Load(reader);

            var items = atomFeed.Entries.OrderBy(e => GetPublishedDate(e)).Select(CreateFeedItem);

            var feed = new Feed {
                Title = atomFeed.Title.Content,
                Url = url,
                SiteUrl = atomFeed.Links.Any() ? atomFeed.Links[0].ToString() : String.Empty,
                Description = atomFeed.Subtitle == null ? String.Empty : atomFeed.Subtitle.Content,
                Items = new List<Item>(items)
            };

            var latest = items.LastOrDefault();
            if (latest != null) {
                feed.Updated = latest.Published;
            }

            return feed;
        }
        //============================================================
        //    CLASS SUMMARY
        //============================================================
        /// <summary>
        /// Provides example code for the AtomPersonConstruct class.
        /// </summary>
        public static void ClassExample()
        {
            #region AtomPersonConstruct
            AtomFeed feed   = new AtomFeed();

            feed.Id         = new AtomId(new Uri("urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6"));
            feed.Title      = new AtomTextConstruct("Example Feed");
            feed.UpdatedOn  = new DateTime(2003, 12, 13, 18, 30, 2);

            feed.Links.Add(new AtomLink(new Uri("http://example.org/")));
            feed.Links.Add(new AtomLink(new Uri("/feed"), "self"));

            //  Identify the author of the feed
            feed.Authors.Add(new AtomPersonConstruct("John Doe"));

            //  Identify the contributors to the feed
            feed.Contributors.Add(new AtomPersonConstruct("Jane Doe"));

            AtomPersonConstruct contributor = new AtomPersonConstruct();
            contributor.EmailAddress        = "*****@*****.**";
            contributor.Name                = "Some Person";
            contributor.Uri                 = new Uri("http://example.org/somePerson");
            feed.Contributors.Add(contributor);

            AtomEntry entry = new AtomEntry();

            entry.Id        = new AtomId(new Uri("urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a"));
            entry.Title     = new AtomTextConstruct("Atom-Powered Robots Run Amok");
            entry.UpdatedOn = new DateTime(2003, 12, 13, 18, 30, 2);

            entry.Summary   = new AtomTextConstruct("Some text.");

            //  Identify the author of the entry
            entry.Authors.Add(new AtomPersonConstruct("Jane Doe"));

            feed.AddEntry(entry);
            #endregion
        }
        protected override IList<Item> UpdateFeed(Feed feed, XmlReader reader) {
            var atomFeed = new AtomFeed();
            atomFeed.Load(reader);

            var items = (from e in atomFeed.Entries
                         let date = GetPublishedDate(e)
                         orderby date
                         where date > feed.Updated
                         select CreateFeedItem(e)).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) && atomFeed.Subtitle != null) {
                feed.Description = atomFeed.Subtitle.Content;
            }

            return items;
        }
Esempio n. 10
0
        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);
                    }
                }
            }
        }
Esempio n. 11
0
    private void GetPosts(object sender, EventArgs e)
    {
        TransitPostQueryOptions options = new TransitPostQueryOptions();
        options.PageNumber = 0;
        options.PageSize = 25;
        options.SortDirection = WebServiceQuerySortDirection.Descending;
        options.SortExpression = "Created";
        options.PublishedOnly = true;
        options.DisplayedOnly = true;

        Response.ContentType = "application/atom+xml;charset=\"utf-8\"";

        AtomFeed feed = new AtomFeed();
        feed.Title = new AtomTextConstruct(SessionManager.GetSetting("title", "Untitled"));

        List<TransitPost> posts = SessionManager.GetCachedCollection<TransitPost>(
            "GetPosts", SessionManager.PostTicket, options);

        foreach (TransitPost post in posts)
        {
            AtomEntry atomEntry = GetPost(post);
            feed.AddEntry(atomEntry);
        }

        feed.Save(Response.OutputStream);
        Response.End();
    }
        /// <summary>
        /// Modifies the <see cref="AtomFeed"/> optional entities to match the supplied <see cref="XPathNavigator"/> data source.
        /// </summary>
        /// <param name="feed">The <see cref="AtomFeed"/> to be filled.</param>
        /// <param name="source">The <see cref="XPathNavigator"/> to extract information from.</param>
        /// <param name="manager">The <see cref="XmlNamespaceManager"/> used to resolve XML namespace prefixes.</param>
        /// <param name="settings">The <see cref="SyndicationResourceLoadSettings"/> used to configure the fill operation.</param>
        /// <remarks>
        ///     This method expects the supplied <paramref name="source"/> to be positioned on the XML element that represents a <see cref="AtomFeed"/>.
        /// </remarks>
        /// <exception cref="ArgumentNullException">The <paramref name="feed"/> is a null reference (Nothing in Visual Basic).</exception>
        /// <exception cref="ArgumentNullException">The <paramref name="source"/> is a null reference (Nothing in Visual Basic).</exception>
        /// <exception cref="ArgumentNullException">The <paramref name="manager"/> 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>
        private static void FillFeedOptionals(AtomFeed feed, XPathNavigator source, XmlNamespaceManager manager, SyndicationResourceLoadSettings settings)
        {
            //------------------------------------------------------------
            //	Validate parameter
            //------------------------------------------------------------
            Guard.ArgumentNotNull(feed, "feed");
            Guard.ArgumentNotNull(source, "source");
            Guard.ArgumentNotNull(manager, "manager");
            Guard.ArgumentNotNull(settings, "settings");

            //------------------------------------------------------------
            //	Attempt to extract syndication information
            //------------------------------------------------------------
            XPathNavigator generatorNavigator       = source.SelectSingleNode("atom:generator", manager);
            XPathNavigator iconNavigator            = source.SelectSingleNode("atom:icon", manager);
            XPathNavigator logoNavigator            = source.SelectSingleNode("atom:logo", manager);
            XPathNavigator rightsNavigator          = source.SelectSingleNode("atom:rights", manager);
            XPathNavigator subtitleNavigator        = source.SelectSingleNode("atom:subtitle", manager);

            if (generatorNavigator != null)
            {
                feed.Generator  = new AtomGenerator();
                feed.Generator.Load(generatorNavigator, settings);
            }

            if (iconNavigator != null)
            {
                feed.Icon   = new AtomIcon();
                feed.Icon.Load(iconNavigator, settings);
            }

            if (logoNavigator != null)
            {
                feed.Logo   = new AtomLogo();
                feed.Logo.Load(logoNavigator, settings);
            }

            if (rightsNavigator != null)
            {
                feed.Rights = new AtomTextConstruct();
                feed.Rights.Load(rightsNavigator, settings);
            }

            if (subtitleNavigator != null)
            {
                feed.Subtitle   = new AtomTextConstruct();
                feed.Subtitle.Load(subtitleNavigator, settings);
            }
        }
Esempio n. 13
0
        //============================================================
        //    ASYNC METHODS
        //============================================================
        /// <summary>
        /// Provides example code for the LoadAsync(Uri, Object) method
        /// </summary>
        public static void LoadAsyncExample()
        {
            #region LoadAsync(Uri source, Object userToken)
            //------------------------------------------------------------
            //	Load feed asynchronously using event-based notification
            //------------------------------------------------------------
            AtomFeed feed   = new AtomFeed();

            feed.Loaded += new EventHandler<SyndicationResourceLoadedEventArgs>(FeedLoadedCallback);

            feed.LoadAsync(new Uri("http://news.google.com/?output=atom"), null);
            #endregion
        }
        /// <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;
            }
        }
Esempio n. 15
0
        /// <summary>
        /// Provides example code for the Save(XmlWriter) method
        /// </summary>
        public static void SaveXmlWriterExample()
        {
            #region Save(XmlWriter writer)
            AtomFeed feed   = new AtomFeed();

            //  Modify feed state using public properties and methods

            using (Stream stream = new FileStream("AtomFeed.xml", FileMode.Create, FileAccess.Write))
            {
                XmlWriterSettings settings  = new XmlWriterSettings();
                settings.Indent             = true;

                using(XmlWriter writer = XmlWriter.Create(stream, settings))
                {
                    feed.Save(writer);
                }
            }
            #endregion
        }
Esempio n. 16
0
        /// <summary>
        /// Provides example code for the Save(Stream) method
        /// </summary>
        public static void SaveStreamExample()
        {
            #region Save(Stream stream)
            AtomFeed feed   = new AtomFeed();

            //  Modify feed state using public properties and methods

            using(Stream stream = new FileStream("AtomFeed.xml", FileMode.Create, FileAccess.Write))
            {
                feed.Save(stream);
            }
            #endregion
        }
        /// <summary>
        /// Modifies the <see cref="AtomFeed"/> optional entities to match the supplied <see cref="XPathNavigator"/> data source.
        /// </summary>
        /// <param name="feed">The <see cref="AtomFeed"/> to be filled.</param>
        /// <param name="source">The <see cref="XPathNavigator"/> to extract information from.</param>
        /// <param name="manager">The <see cref="XmlNamespaceManager"/> used to resolve XML namespace prefixes.</param>
        /// <param name="settings">The <see cref="SyndicationResourceLoadSettings"/> used to configure the fill operation.</param>
        /// <remarks>
        ///     This method expects the supplied <paramref name="source"/> to be positioned on the XML element that represents a <see cref="AtomFeed"/>.
        /// </remarks>
        /// <exception cref="ArgumentNullException">The <paramref name="feed"/> is a null reference (Nothing in Visual Basic).</exception>
        /// <exception cref="ArgumentNullException">The <paramref name="source"/> is a null reference (Nothing in Visual Basic).</exception>
        /// <exception cref="ArgumentNullException">The <paramref name="manager"/> 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>
        private static void FillFeedOptionals(AtomFeed feed, XPathNavigator source, XmlNamespaceManager manager, SyndicationResourceLoadSettings settings)
        {
            //------------------------------------------------------------
            //	Validate parameter
            //------------------------------------------------------------
            Guard.ArgumentNotNull(feed, "feed");
            Guard.ArgumentNotNull(source, "source");
            Guard.ArgumentNotNull(manager, "manager");
            Guard.ArgumentNotNull(settings, "settings");

            //------------------------------------------------------------
            //	Attempt to extract syndication information
            //------------------------------------------------------------
            XPathNavigator generatorNavigator   = source.SelectSingleNode("atom:generator", manager);
            XPathNavigator copyrightNavigator   = source.SelectSingleNode("atom:copyright", manager);
            XPathNavigator taglineNavigator     = source.SelectSingleNode("atom:tagline", manager);

            if (generatorNavigator != null)
            {
                feed.Generator  = Atom03SyndicationResourceAdapter.CreateGenerator(generatorNavigator, manager, settings);
            }

            if (copyrightNavigator != null)
            {
                feed.Rights     = Atom03SyndicationResourceAdapter.CreateTextContent(copyrightNavigator, manager, settings);
            }

            if (taglineNavigator != null)
            {
                feed.Subtitle   = Atom03SyndicationResourceAdapter.CreateTextContent(taglineNavigator, manager, settings);
            }
        }
Esempio n. 18
0
        /// <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;
                }
            }
        }
Esempio n. 19
0
        /// <summary>
        /// Initializes the generic syndication feed using the supplied <see cref="AtomFeed"/>.
        /// </summary>
        /// <param name="feed">The <see cref="AtomFeed"/> 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(AtomFeed feed)
        {
            //------------------------------------------------------------
            //	Validate parameters
            //------------------------------------------------------------
            Guard.ArgumentNotNull(feed, "feed");

            //------------------------------------------------------------
            //	Initialize generic feed
            //------------------------------------------------------------
            feedResource            = feed;
            feedFormat              = SyndicationContentFormat.Atom;

            if (feed.Title != null && !String.IsNullOrEmpty(feed.Title.Content))
            {
                feedTitle           = feed.Title.Content;
            }

            if (feed.Subtitle != null && !String.IsNullOrEmpty(feed.Title.Content))
            {
                feedDescription     = feed.Subtitle.Content;
            }

            if (feed.UpdatedOn != DateTime.MinValue)
            {
                feedLastUpdatedOn   = feed.UpdatedOn;
            }

            if(feed.Language != null)
            {
                feedLanguage        = feed.Language;
            }

            foreach(AtomCategory category in feed.Categories)
            {
                GenericSyndicationCategory genericCategory  = new GenericSyndicationCategory(category);
                feedCategories.Add(genericCategory);
            }

            foreach(AtomEntry entry in feed.Entries)
            {
                GenericSyndicationItem genericItem  = new GenericSyndicationItem(entry);
                ((Collection<GenericSyndicationItem>)feedItems).Add(genericItem);
            }
        }
Esempio n. 20
0
        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));
        }
Esempio n. 21
0
        /// <summary>
        /// Creates a new <see cref="AtomFeed"/> 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="AtomFeed"/> instance. This value can be <b>null</b>.</param>
        /// <returns>An <see cref="AtomFeed"/> 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 AtomFeed Create(Uri source, WebRequestOptions options, SyndicationResourceLoadSettings settings)
        {
            //------------------------------------------------------------
            //	Local members
            //------------------------------------------------------------
            AtomFeed syndicationResource = new AtomFeed();

            //------------------------------------------------------------
            //	Validate parameters
            //------------------------------------------------------------
            Guard.ArgumentNotNull(source, "source");

            //------------------------------------------------------------
            //	Create new instance using supplied parameters
            //------------------------------------------------------------
            syndicationResource.Load(source, options, settings);

            return syndicationResource;
        }
        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;
        }
Esempio n. 23
0
 private int GetAtomFeedItems(AtomFeed feed, Subscription subscription)
 {
     var itemsAdded = 0;
     foreach (var entry in feed.Entries.Where(x => subscription.LastFeedUpdatesUTC == null
         || x.PublishedOn.ToUniversalTime() > subscription.LastFeedUpdatesUTC))
     {
         var categories = entry.Categories.Aggregate(String.Empty, (current, category) => current + (category.Label + ",")).TrimEnd(',');
         var authors = entry.Authors.Aggregate(String.Empty, (current, author) => current + (author.Name + ",")).TrimEnd(',');
         var subscriptionPost = new SubscriptionPost
                                    {
                                        Authors = authors,
                                        Categories = categories,
                                        Content = entry.Content != null ? entry.Content.Content : (entry.Summary != null) ? entry.Summary.Content : String.Empty,
                                        OriginalUrl = GetOriginalUrl(entry),
                                        PublishDateUTC = GetGoodDateTime(entry.PublishedOn.ToUniversalTime()),
                                        Subscription = subscription,
                                        Title = entry.Title.Content
                                    };
         itemsAdded++;
         _dbContext.SubscriptionPosts.Add(subscriptionPost);
         subscription.SubscriptionPosts.Add(subscriptionPost);
     }
     return itemsAdded;
 }
Esempio n. 24
0
 private static string GetAtomSubscriptionTitle(AtomFeed atom)
 {
     if (atom.BaseUri == null)
     {
         var link = atom.Links.SingleOrDefault(x => x.Relation == String.Empty);
         if (link != null)
         {
             return link.Uri.ToString();
         }
         var alternateUrl = atom.Links.SingleOrDefault(x => x.Relation == "alternate");
         if (alternateUrl != null)
         {
             return alternateUrl.Uri.ToString();
         }
     }
     return atom.BaseUri.ToString();
 }
Esempio n. 25
0
        //============================================================
        //    INSTANCE METHODS
        //============================================================
        /// <summary>
        /// Provides example code for the Load(IXPathNavigable) method
        /// </summary>
        public static void LoadIXPathNavigableExample()
        {
            #region Load(IXPathNavigable source)
            XPathDocument source    = new XPathDocument("http://news.google.com/?output=atom");

            AtomFeed feed   = new AtomFeed();
            feed.Load(source);

            foreach (AtomEntry entry in feed.Entries)
            {
                if (entry.PublishedOn >= DateTime.Today)
                {
                    //  Perform some processing on the feed entry
                }
            }
            #endregion
        }
Esempio n. 26
0
        /// <summary>
        /// Provides example code for the Load(Stream) method
        /// </summary>
        public static void LoadStreamExample()
        {
            #region Load(Stream stream)
            AtomFeed feed   = new AtomFeed();

            using (Stream stream = new FileStream("AtomFeed.xml", FileMode.Open, FileAccess.Read))
            {
                feed.Load(stream);

                foreach (AtomEntry entry in feed.Entries)
                {
                    if (entry.PublishedOn >= DateTime.Today)
                    {
                        //  Perform some processing on the feed entry
                    }
                }
            }
            #endregion
        }
Esempio n. 27
0
        /// <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);
        }
Esempio n. 28
0
        /// <summary>
        /// Provides example code for the Load(Uri, ICredentials, IWebProxy) method
        /// </summary>
        public static void LoadUriExample()
        {
            #region Load(Uri source, ICredentials credentials, IWebProxy proxy)
            AtomFeed feed   = new AtomFeed();
            Uri source      = new Uri("http://news.google.com/?output=atom");

            feed.Load(source, CredentialCache.DefaultNetworkCredentials, null);

            foreach (AtomEntry entry in feed.Entries)
            {
                if (entry.PublishedOn >= DateTime.Today)
                {
                    //  Perform some processing on the feed entry
                }
            }
            #endregion
        }
        /// <summary>
        /// Modifies the <see cref="AtomFeed"/> collection entities to match the supplied <see cref="XPathNavigator"/> data source.
        /// </summary>
        /// <param name="feed">The <see cref="AtomFeed"/> to be filled.</param>
        /// <param name="source">The <see cref="XPathNavigator"/> to extract information from.</param>
        /// <param name="manager">The <see cref="XmlNamespaceManager"/> used to resolve XML namespace prefixes.</param>
        /// <param name="settings">The <see cref="SyndicationResourceLoadSettings"/> used to configure the fill operation.</param>
        /// <remarks>
        ///     This method expects the supplied <paramref name="source"/> to be positioned on the XML element that represents a <see cref="AtomFeed"/>.
        /// </remarks>
        /// <exception cref="ArgumentNullException">The <paramref name="feed"/> is a null reference (Nothing in Visual Basic).</exception>
        /// <exception cref="ArgumentNullException">The <paramref name="source"/> is a null reference (Nothing in Visual Basic).</exception>
        /// <exception cref="ArgumentNullException">The <paramref name="manager"/> 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>
        private static void FillFeedCollections(AtomFeed feed, XPathNavigator source, XmlNamespaceManager manager, SyndicationResourceLoadSettings settings)
        {
            //------------------------------------------------------------
            //	Validate parameter
            //------------------------------------------------------------
            Guard.ArgumentNotNull(feed, "feed");
            Guard.ArgumentNotNull(source, "source");
            Guard.ArgumentNotNull(manager, "manager");
            Guard.ArgumentNotNull(settings, "settings");

            //------------------------------------------------------------
            //	Attempt to extract syndication information
            //------------------------------------------------------------
            XPathNodeIterator authorIterator        = source.Select("atom:author", manager);
            XPathNodeIterator contributorIterator   = source.Select("atom:contributor", manager);
            XPathNodeIterator linkIterator          = source.Select("atom:link", manager);
            XPathNodeIterator entryIterator         = source.Select("atom:entry", manager);

            if (authorIterator != null && authorIterator.Count > 0)
            {
                while (authorIterator.MoveNext())
                {
                    AtomPersonConstruct author  = Atom03SyndicationResourceAdapter.CreatePerson(authorIterator.Current, manager, settings);
                    feed.Authors.Add(author);
                }
            }

            if (contributorIterator != null && contributorIterator.Count > 0)
            {
                while (contributorIterator.MoveNext())
                {
                    AtomPersonConstruct contributor = Atom03SyndicationResourceAdapter.CreatePerson(contributorIterator.Current, manager, settings);
                    feed.Contributors.Add(contributor);
                }
            }

            if (entryIterator != null && entryIterator.Count > 0)
            {
                int counter = 0;
                while (entryIterator.MoveNext())
                {
                    AtomEntry entry = new AtomEntry();
                    counter++;

                    Atom03SyndicationResourceAdapter.FillEntry(entry, entryIterator.Current, manager, settings);

                    if (settings.RetrievalLimit != 0 && counter > settings.RetrievalLimit)
                    {
                        break;
                    }

                    ((Collection<AtomEntry>)feed.Entries).Add(entry);
                }
            }

            if (linkIterator != null && linkIterator.Count > 0)
            {
                while (linkIterator.MoveNext())
                {
                    AtomLink link   = new AtomLink();
                    if (link.Load(linkIterator.Current, settings))
                    {
                        feed.Links.Add(link);
                    }
                }
            }
        }
Esempio n. 30
0
        /// <summary>
        /// Provides example code for the Load(XmlReader) method
        /// </summary>
        public static void LoadXmlReaderExample()
        {
            #region Load(XmlReader reader)
            AtomFeed feed   = new AtomFeed();

            using (Stream stream = new FileStream("AtomFeed.xml", FileMode.Open, FileAccess.Read))
            {
                XmlReaderSettings settings  = new XmlReaderSettings();
                settings.IgnoreComments     = true;
                settings.IgnoreWhitespace   = true;

                using(XmlReader reader = XmlReader.Create(stream, settings))
                {
                    feed.Load(reader);

                    foreach (AtomEntry entry in feed.Entries)
                    {
                        if (entry.PublishedOn >= DateTime.Today)
                        {
                            //  Perform some processing on the feed entry
                        }
                    }
                }
            }
            #endregion
        }
        /// <summary>
        /// Modifies the <see cref="AtomFeed"/> to match the data source.
        /// </summary>
        /// <param name="resource">The <see cref="AtomFeed"/> to be filled.</param>
        /// <exception cref="ArgumentNullException">The <paramref name="resource"/> is a null reference (Nothing in Visual Basic).</exception>
        public void Fill(AtomFeed resource)
        {
            //------------------------------------------------------------
            //	Validate parameter
            //------------------------------------------------------------
            Guard.ArgumentNotNull(resource, "resource");

            //------------------------------------------------------------
            //	Create namespace resolver
            //------------------------------------------------------------
            XmlNamespaceManager manager     = Atom03SyndicationResourceAdapter.CreateNamespaceManager(this.Navigator.NameTable);

            //------------------------------------------------------------
            //	Attempt to fill syndication resource
            //------------------------------------------------------------
            XPathNavigator feedNavigator    = this.Navigator.SelectSingleNode("atom:feed", manager);

            if (feedNavigator != null)
            {
                AtomUtility.FillCommonObjectAttributes(resource, feedNavigator);

                XPathNavigator idNavigator          = feedNavigator.SelectSingleNode("atom:id", manager);
                XPathNavigator titleNavigator       = feedNavigator.SelectSingleNode("atom:title", manager);
                XPathNavigator modifiedNavigator    = feedNavigator.SelectSingleNode("atom:modified", manager);

                if (idNavigator != null)
                {
                    resource.Id = new AtomId();
                    resource.Id.Load(idNavigator, this.Settings);
                }

                if (titleNavigator != null)
                {
                    resource.Title  = Atom03SyndicationResourceAdapter.CreateTextContent(titleNavigator, manager, this.Settings);
                }

                if (modifiedNavigator != null)
                {
                    DateTime updatedOn;
                    if (SyndicationDateTimeUtility.TryParseRfc3339DateTime(modifiedNavigator.Value, out updatedOn))
                    {
                        resource.UpdatedOn  = updatedOn;
                    }
                }

                Atom03SyndicationResourceAdapter.FillFeedOptionals(resource, feedNavigator, manager, this.Settings);
                Atom03SyndicationResourceAdapter.FillFeedCollections(resource, feedNavigator, manager, this.Settings);

                SyndicationExtensionAdapter adapter = new SyndicationExtensionAdapter(feedNavigator, this.Settings);
                adapter.Fill(resource, manager);
            }
        }
Esempio n. 32
0
        public override void ExecuteItemSequence(string groupByValue, IEnumerable<Tuple<ITaskItem, ITaskItem, ITaskItem>> items)
        {
            var feed = new AtomFeed
            {
                Id = new AtomId(new Uri(FeedId)),
                Title = new AtomTextConstruct(FeedTitle ?? ""),
                UpdatedOn = DateTime.Now,
            };

            if (!string.IsNullOrWhiteSpace(FeedRights))
            {
                feed.Rights = new AtomTextConstruct(FeedRights);
            }

            if (!string.IsNullOrWhiteSpace(FeedIcon))
            {
                feed.Icon = new AtomIcon(new Uri(FeedIcon));
            }

            if (!string.IsNullOrWhiteSpace(FeedLogo))
            {
                feed.Logo = new AtomLogo(new Uri(FeedLogo));
            }

            if (!string.IsNullOrWhiteSpace(FeedSubtitle))
            {
                feed.Subtitle = new AtomTextConstruct(FeedSubtitle);
            }

            if (!string.IsNullOrWhiteSpace(FeedAuthors))
            {
                foreach (string author in FeedAuthors.Split(';').Select(item => item.Trim()))
                {
                    feed.Authors.Add(new AtomPersonConstruct(author));
                }
            }

            if (!string.IsNullOrWhiteSpace(FeedContributors))
            {
                foreach (string contributor in FeedContributors.Split(';').Select(item => item.Trim()))
                {
                    feed.Contributors.Add(new AtomPersonConstruct(contributor));
                }
            }

            if (!string.IsNullOrWhiteSpace(FeedCategories))
            {
                foreach (string category in FeedCategories.Split(';').Select(item => item.Trim()))
                {
                    feed.Categories.Add(new AtomCategory(category));
                }
            }

            if (FeedLinkRelationSelf != null)
            {

                var selfLink = new AtomLink
                       {
                           Relation = "self",
                           Uri = new Uri(FeedLinkRelationSelf)
                       };
                feed.Links.Add(selfLink);
            }

            foreach (Tuple<ITaskItem, ITaskItem, ITaskItem> tuple in items.OrderByDescending(item => item.Item2.GetTimestamp()))
            {
                ITaskItem modelInput = tuple.Item1;
                ITaskItem receiptInput = tuple.Item2;
                ITaskItem contentInput = tuple.Item3;

                modelInput.LoadCustomMetadata();

                DateTime receiptModified = receiptInput.GetTimestamp();
                var entry = new AtomEntry
                {
                    Id = new AtomId(new Uri(modelInput.GetMetadata(EntryIdSelector ?? "Uri"))),
                    Title = new AtomTextConstruct(modelInput.GetMetadata(EntryTitleSelector ?? "Title")),
                    UpdatedOn = receiptModified,
                    Summary = new AtomTextConstruct(modelInput.GetMetadata(EntrySummarySelector ?? "Summary")),
                };

                if (string.IsNullOrWhiteSpace(entry.Title.Content))
                {
                    entry.Title.Content = tuple.Item1.ItemSpec;
                }
                if (string.IsNullOrWhiteSpace(entry.Summary.Content))
                {
                    entry.Summary.Content = entry.Title.Content;
                }

                if (contentInput.Exists())
                {
                    if (string.IsNullOrWhiteSpace(EntryContentEncoding))
                    {
                        entry.Content = new AtomContent(contentInput.ReadAllText());
                    }
                    else
                    {
                        entry.Content = new AtomContent(contentInput.ReadAllText(), EntryContentEncoding);
                    }

                    if (!string.IsNullOrWhiteSpace(EntryContentType))
                    {
                        entry.Content.ContentType = EntryContentType;
                    }
                }

                var alternateLink = new AtomLink
                {
                    Relation = "alternate",
                    Uri = new Uri(modelInput.GetMetadata(EntryLinkAlternateSelector ?? "Uri"))
                };
                entry.Links.Add(alternateLink);
                feed.AddEntry(entry);
            }
            using (FileStream stream = File.OpenWrite(Output.ItemSpec))
            {
                SyndicationResourceSaveSettings s = new SyndicationResourceSaveSettings() { CharacterEncoding = Encoding.UTF8 };
                feed.Save(stream, s);
            }
        }