/// <summary>
        /// Loads the generic syndication item using the supplied <see cref="RssItem"/>.
        /// </summary>
        /// <param name="item">The <see cref="RssItem"/> to build an abstraction against.</param>
        /// <exception cref="ArgumentNullException">The <paramref name="item"/> is a null reference (Nothing in Visual Basic).</exception>
        private void LoadFrom(RssItem item)
        {
            //------------------------------------------------------------
            //	Validate parameters
            //------------------------------------------------------------
            Guard.ArgumentNotNull(item, "item");

            //------------------------------------------------------------
            //	Initialize generic item
            //------------------------------------------------------------
            if (!String.IsNullOrEmpty(item.Title))
            {
                itemTitle = item.Title.Trim();
            }

            if (item.PublicationDate != DateTime.MinValue)
            {
                itemPublishedOn = item.PublicationDate;
            }

            if (!String.IsNullOrEmpty(item.Description))
            {
                itemSummary = item.Description.Trim();
            }

            foreach (RssCategory category in item.Categories)
            {
                GenericSyndicationCategory genericCategory = new GenericSyndicationCategory(category);
                itemCategories.Add(genericCategory);
            }
        }
Exemplo n.º 2
0
        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);
        }
        private RssItem GetItem(string filePath)
        {
            var file = new FileInfo(filePath);

            if (!file.Exists)
                return null;

            string mimeType = GetMimeType(file);

            string fileName = Path.GetFileNameWithoutExtension(filePath);
            var uri = new Uri(GetUrl(Port, file.Name));

            var item = new RssItem();
            item.Title = fileName;
            item.Link = uri;

            item.Enclosures.Add(new RssEnclosure(file.Length, mimeType, item.Link));

            var extension = new YahooMediaSyndicationExtension();
            var mediaContent = new YahooMediaContent(uri);
            mediaContent.FileSize = file.Length;
            mediaContent.ContentType = mimeType;

            extension.Context.AddContent(mediaContent);
            item.AddExtension(extension);

            return item;
        }
Exemplo n.º 4
0
        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();
            }
        }
 private static DateTime GetPublishedDate(RssItem item) {
     if (item.PublicationDate == DateTime.MinValue && item.HasExtensions) {
         var ext = item.FindExtension(DublinCoreElementSetSyndicationExtension.MatchByType) as DublinCoreElementSetSyndicationExtension;
         if (ext != null) {
             return ext.Context.Date;
         }
     }
     return item.PublicationDate;
 }
 private static Item CreateFeedItem(RssItem rssItem) {
     return new Item {
         Title = HtmlHelper.DecodeHtml(rssItem.Title),
         Url = rssItem.Link == null ? String.Empty : rssItem.Link.ToString(),
         PodcastUrl = GetPodcastUrl(rssItem),
         Summary = GetHtmlString(rssItem.Description, MaxSummaryLength),
         Published = GetPublishedDate(rssItem),
         IsRead = false
     };
 }
Exemplo n.º 7
0
        /// <summary>
        /// Initializes a new instance of the <see cref="GenericSyndicationItem"/> class using the supplied <see cref="RssItem"/>.
        /// </summary>
        /// <param name="item">The <see cref="RssItem"/> to build an abstraction against.</param>
        /// <exception cref="ArgumentNullException">The <paramref name="item"/> is a null reference (Nothing in Visual Basic).</exception>
        public GenericSyndicationItem(RssItem item)
        {
            //------------------------------------------------------------
            //	Validate parameter
            //------------------------------------------------------------
            Guard.ArgumentNotNull(item, "item");

            //------------------------------------------------------------
            //	Extract information from the format specific content
            //------------------------------------------------------------
            this.LoadFrom(item);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="GenericSyndicationItem"/> class using the supplied <see cref="RssItem"/>.
        /// </summary>
        /// <param name="item">The <see cref="RssItem"/> to build an abstraction against.</param>
        /// <exception cref="ArgumentNullException">The <paramref name="item"/> is a null reference (Nothing in Visual Basic).</exception>
        public GenericSyndicationItem(RssItem item)
        {
            //------------------------------------------------------------
            //	Validate parameter
            //------------------------------------------------------------
            Guard.ArgumentNotNull(item, "item");

            //------------------------------------------------------------
            //	Extract information from the format specific content
            //------------------------------------------------------------
            this.LoadFrom(item);
        }
Exemplo n.º 9
0
        //============================================================
        //	ICOMPARABLE IMPLEMENTATION
        //============================================================
        #region CompareTo(object obj)
        /// <summary>
        /// Compares the current instance with another object of the same type.
        /// </summary>
        /// <param name="obj">An object to compare with this instance.</param>
        /// <returns>A 32-bit signed integer that indicates the relative order of the objects being compared.</returns>
        /// <exception cref="ArgumentException">The <paramref name="obj"/> is not the expected <see cref="Type"/>.</exception>
        public int CompareTo(object obj)
        {
            //------------------------------------------------------------
            //	If target is a null reference, instance is greater
            //------------------------------------------------------------
            if (obj == null)
            {
                return(1);
            }

            //------------------------------------------------------------
            //	Determine comparison result using property state of objects
            //------------------------------------------------------------
            RssItem value = obj as RssItem;

            if (value != null)
            {
                int result = String.Compare(this.Author, value.Author, StringComparison.OrdinalIgnoreCase);
                result = result | Uri.Compare(this.Comments, value.Comments, UriComponents.AbsoluteUri, UriFormat.SafeUnescaped, StringComparison.OrdinalIgnoreCase);
                result = result | String.Compare(this.Description, value.Description, StringComparison.OrdinalIgnoreCase);
                result = result | Uri.Compare(this.Link, value.Link, UriComponents.AbsoluteUri, UriFormat.SafeUnescaped, StringComparison.OrdinalIgnoreCase);
                result = result | this.PublicationDate.CompareTo(value.PublicationDate);
                result = result | String.Compare(this.Title, value.Title, StringComparison.OrdinalIgnoreCase);

                if (this.Guid != null)
                {
                    result = result | this.Guid.CompareTo(value.Guid);
                }
                else if (this.Guid == null && value.Guid != null)
                {
                    result = result | -1;
                }

                if (this.Source != null)
                {
                    result = result | this.Source.CompareTo(value.Source);
                }
                else if (this.Source == null && value.Source != null)
                {
                    result = result | -1;
                }

                result = result | RssFeed.CompareSequence(this.Categories, value.Categories);
                result = result | RssItem.CompareSequence(this.Enclosures, value.Enclosures);

                return(result);
            }
            else
            {
                throw new ArgumentException(String.Format(null, "obj is not of type {0}, type was found to be '{1}'.", this.GetType().FullName, obj.GetType().FullName), "obj");
            }
        }
Exemplo n.º 10
0
        private static string GetPodcastUrl(RssItem item) {
            var podcasts = GetPodcastsFromExtensions(item);
            var podcast = podcasts.FirstOrDefault();
            if (podcast != null) {
                return podcast;
            }

            podcasts = GetPodcastsFromEnclousures(item);
            podcast = podcasts.FirstOrDefault();
            if (podcast != null) {
                return podcast;
            }

            return null;
        }
Exemplo n.º 11
0
        //============================================================
        //    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
        }
Exemplo n.º 12
0
        public List<string> GetPostImages(RssItem i)
        {
            List<string> imagelist = new List<string>();
            foreach (ISyndicationExtension s in i.Extensions)
            {
                if (s is SiteSummaryContentSyndicationExtension)
                {
                    SiteSummaryContentSyndicationExtension ss = s as SiteSummaryContentSyndicationExtension;
                    var t = ss.Context.Encoded;
                    string regexImgSrc = "<img.+?src=[\"'](.+?)[\"'].+?>";
                    MatchCollection matches = Regex.Matches(t, regexImgSrc,RegexOptions.IgnoreCase | RegexOptions.Compiled);

                   imagelist.AddRange(from Match m in matches
                                      select m.Groups[1].Value);
                                      //select Regex.Match(m.Value,"").Value);

                }
            }

            return imagelist;
        }
Exemplo n.º 13
0
        public string GetBlogPostContent(RssItem i, bool removeHtml)
        {
            string content = null;
            foreach (ISyndicationExtension s in i.Extensions)
            {

                if (s is SiteSummaryContentSyndicationExtension)
                {

                    SiteSummaryContentSyndicationExtension ss = s as SiteSummaryContentSyndicationExtension;
                    var t = ss.Context.Encoded;
                    content = HttpUtility.HtmlDecode(t);
                    //content =

                    if (removeHtml)
                    {

                        content = Regex.Replace(content, "<[^>]*>", "", RegexOptions.Compiled);
                    }
                }
            }
            return content;
        }
Exemplo n.º 14
0
        //============================================================
        //    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
        }
Exemplo n.º 15
0
        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);
        }
Exemplo n.º 16
0
        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);

            }
        }
Exemplo n.º 17
0
        /// <summary>
        /// Loads the generic syndication item using the supplied <see cref="RssItem"/>.
        /// </summary>
        /// <param name="item">The <see cref="RssItem"/> to build an abstraction against.</param>
        /// <exception cref="ArgumentNullException">The <paramref name="item"/> is a null reference (Nothing in Visual Basic).</exception>
        private void LoadFrom(RssItem item)
        {
            //------------------------------------------------------------
            //	Validate parameters
            //------------------------------------------------------------
            Guard.ArgumentNotNull(item, "item");

            //------------------------------------------------------------
            //	Initialize generic item
            //------------------------------------------------------------
            if (!String.IsNullOrEmpty(item.Title))
            {
                itemTitle       = item.Title.Trim();
            }

            if (item.PublicationDate != DateTime.MinValue)
            {
                itemPublishedOn = item.PublicationDate;
            }

            if (!String.IsNullOrEmpty(item.Description))
            {
                itemSummary     = item.Description.Trim();
            }

            foreach (RssCategory category in item.Categories)
            {
                GenericSyndicationCategory genericCategory  = new GenericSyndicationCategory(category);
                itemCategories.Add(genericCategory);
            }
        }
Exemplo n.º 18
0
        /// <summary>
        /// Adds the supplied <see cref="RssItem"/> to the current instance's <see cref="Items"/> collection.
        /// </summary>
        /// <param name="item">The <see cref="RssItem"/> to be added.</param>
        /// <returns><b>true</b> if the <see cref="RssItem"/> was added to the <see cref="Items"/> collection, otherwise <b>false</b>.</returns>
        /// <exception cref="ArgumentNullException">The <paramref name="item"/> is a null reference (Nothing in Visual Basic).</exception>
        public bool AddItem(RssItem item)
        {
            //------------------------------------------------------------
            //	Local members
            //------------------------------------------------------------
            bool wasAdded   = false;

            //------------------------------------------------------------
            //	Validate parameter
            //------------------------------------------------------------
            Guard.ArgumentNotNull(item, "item");

            //------------------------------------------------------------
            //	Add item to collection
            //------------------------------------------------------------
            ((Collection<RssItem>)this.Items).Add(item);
            wasAdded    = true;

            return wasAdded;
        }
        /// <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);
        }
Exemplo n.º 20
0
        /// <summary>
        /// Removes the supplied <see cref="RssItem"/> from the current instance's <see cref="Items"/> collection.
        /// </summary>
        /// <param name="item">The <see cref="RssItem"/> to be removed.</param>
        /// <returns><b>true</b> if the <see cref="RssItem"/> was removed from the <see cref="Items"/> collection, otherwise <b>false</b>.</returns>
        /// <remarks>
        ///     If the <see cref="Items"/> collection of the current instance does not contain the specified <see cref="RssItem"/>, will return <b>false</b>.
        /// </remarks>
        /// <exception cref="ArgumentNullException">The <paramref name="item"/> is a null reference (Nothing in Visual Basic).</exception>
        public bool RemoveItem(RssItem item)
        {
            //------------------------------------------------------------
            //	Local members
            //------------------------------------------------------------
            bool wasRemoved = false;

            //------------------------------------------------------------
            //	Validate parameter
            //------------------------------------------------------------
            Guard.ArgumentNotNull(item, "item");

            //------------------------------------------------------------
            //	Remove item from collection
            //------------------------------------------------------------
            if (((Collection<RssItem>)this.Items).Contains(item))
            {
                ((Collection<RssItem>)this.Items).Remove(item);
                wasRemoved  = true;
            }

            return wasRemoved;
        }
Exemplo n.º 21
0
        /// <summary>
        /// Loads the collection elements of this <see cref="RssChannel"/> using the supplied <see cref="XPathNavigator"/>.
        /// </summary>
        /// <param name="source">The <see cref="XPathNavigator"/> to extract information from.</param>
        /// <param name="manager">The <see cref="XmlNamespaceManager"/> used to resolve namespace prefixes.</param>
        /// <param name="settings">The <see cref="SyndicationResourceLoadSettings"/> used to configure the load operation.</param>
        /// <returns><b>true</b> if the <see cref="RssChannel"/> was initialized using the supplied <paramref name="source"/>, otherwise <b>false</b>.</returns>
        /// <remarks>
        ///     <para>
        ///         This method expects the supplied <paramref name="source"/> to be positioned on the XML element that represents a <see cref="RssChannel"/>.
        ///     </para>
        ///     <para>
        ///         The number of <see cref="RssChannel.Items"/> that are loaded is limited based on the <see cref="SyndicationResourceLoadSettings.RetrievalLimit"/>.
        ///     </para>
        /// </remarks>
        /// <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 bool LoadCollections(XPathNavigator source, XmlNamespaceManager manager, SyndicationResourceLoadSettings settings)
        {
            //------------------------------------------------------------
            //	Local members
            //------------------------------------------------------------
            bool wasLoaded              = false;

            //------------------------------------------------------------
            //	Validate parameter
            //------------------------------------------------------------
            Guard.ArgumentNotNull(source, "source");
            Guard.ArgumentNotNull(manager, "manager");
            Guard.ArgumentNotNull(settings, "settings");

            //------------------------------------------------------------
            //	Attempt to extract syndication information
            //------------------------------------------------------------
            XPathNodeIterator categoryIterator  = source.Select("category", manager);
            XPathNodeIterator skipDaysIterator  = source.Select("skipDays/day", manager);
            XPathNodeIterator skipHoursIterator = source.Select("skipHours/hour", manager);
            XPathNodeIterator itemIterator      = source.Select("item", manager);

            if (categoryIterator != null && categoryIterator.Count > 0)
            {
                while (categoryIterator.MoveNext())
                {
                    RssCategory category    = new RssCategory();
                    if (category.Load(categoryIterator.Current, settings))
                    {
                        this.Categories.Add(category);
                        wasLoaded   = true;
                    }
                }
            }

            if (skipDaysIterator != null && skipDaysIterator.Count > 0)
            {
                while (skipDaysIterator.MoveNext())
                {
                    if (!String.IsNullOrEmpty(skipDaysIterator.Current.Value))
                    {
                        try
                        {
                            DayOfWeek day   = (DayOfWeek)Enum.Parse(typeof(DayOfWeek), skipDaysIterator.Current.Value, true);
                            if (!this.SkipDays.Contains(day))
                            {
                                this.SkipDays.Add(day);
                                wasLoaded   = true;
                            }
                        }
                        catch (ArgumentException)
                        {
                            System.Diagnostics.Trace.TraceWarning("RssChannel unable to determine DayOfWeek with a name of {0}.", skipDaysIterator.Current.Value);
                        }
                    }
                }
            }

            if (skipHoursIterator != null && skipHoursIterator.Count > 0)
            {
                while (skipHoursIterator.MoveNext())
                {
                    int hour;
                    if (Int32.TryParse(skipHoursIterator.Current.Value, NumberStyles.Integer, NumberFormatInfo.InvariantInfo, out hour))
                    {
                        if (!this.SkipHours.Contains(hour) && (hour >= 0 && hour <= 23))
                        {
                            this.SkipHours.Add(hour);
                            wasLoaded   = true;
                        }
                        else
                        {
                            System.Diagnostics.Trace.TraceWarning("RssChannel unable to add duplicate or out-of-range skip hour with a value of {0}.", hour);
                        }
                    }
                }
            }

            if (itemIterator != null && itemIterator.Count > 0)
            {
                int counter = 0;
                while (itemIterator.MoveNext())
                {
                    RssItem item    = new RssItem();
                    counter++;

                    if (item.Load(itemIterator.Current, settings))
                    {
                        if (settings.RetrievalLimit != 0 && counter > settings.RetrievalLimit)
                        {
                            break;
                        }

                        ((Collection<RssItem>)this.Items).Add(item);
                        wasLoaded   = true;
                    }
                }
            }

            return wasLoaded;
        }
Exemplo n.º 22
0
 private static IEnumerable<string> GetPodcastsFromEnclousures(RssItem item) {
     if (item.Enclosures.Any()) {
         return from e in item.Enclosures
                let url = e.Url.ToString()
                where ContainsPodcastExtension(url)
                select url;
     }
     return Enumerable.Empty<string>();
 }
Exemplo n.º 23
0
        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);

            }
        }
Exemplo n.º 24
0
 private static string GetRssContent(RssItem item)
 {
     var contentExtension = item.FindExtension<SiteSummaryContentSyndicationExtension>();
     return contentExtension != null ? contentExtension.Context.Encoded : item.Description;
 }
Exemplo n.º 25
0
 private string GetRssAuthors(RssItem item)
 {
     var dcExtension = item.FindExtension<DublinCoreElementSetSyndicationExtension>();
     return dcExtension != null ? dcExtension.Context.Creator : String.Empty;
 }
Exemplo n.º 26
0
        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 += "&nbsp;&nbsp;" + "<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>&#160;</p>"))
                    {
                        excerpt = excerpt
                            + config.ExcerptSuffix
                            + " <a href='"
                            + blogItemUrl + "'>" + config.MoreLinkText + "</a><div class='excerptspacer'>&nbsp;</div>";
                    }
                    else
                    {
                        excerpt = UIHelper.CreateExcerpt(dr["Description"].ToString(), config.ExcerptLength, config.ExcerptSuffix)
                            + " <a href='"
                            + blogItemUrl + "'>" + config.MoreLinkText + "</a><div class='excerptspacer'>&nbsp;</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 bool ReadFeedItem(RssItem i, Source source,bool? IsForTest)
        {

            //Check if there is another article with the same title

            NewsItem oldItem = Data.NewsItems.All().FirstOrDefault(n => n.Title.Trim().ToLower() == i.Title.Trim().ToLower());

            if (oldItem != null && new DateTime(oldItem.DatePublished).Date == i.PublicationDate.Date)
            {
                UpdateOldItem(i.Link.ToString(), source, oldItem);
                return false;
            }

            //Parse the article
            var article = ParseArticle(i.Link.ToString(), source.SourceWebsite.Name);

            if (article == null || string.IsNullOrEmpty(article.Content))
            {
                throw new Exception(string.Format("Connot Parse Article url : {0}", i.Link.ToString()));
            }

            if (string.IsNullOrEmpty(article.Href))
                article.Href = i.Link.ToString();

            //Check if there is already an article
            var oldArticle = this.Data.NewsItems.All().FirstOrDefault(s => s.Href == article.Href);

            //If its new one
            if (oldArticle == null)
            {
                article.Media = source.SourceWebsite.Name;

                if (string.IsNullOrEmpty(article.Header))
                {
                    article.Header = Regex.Replace(i.Title, @"<img\s[^>]*>(?:\s*?</img>)?", "", RegexOptions.IgnoreCase);
                }

                //newsitem.RealId = article.PartitionKey;
                article.Title = article.Header;
                article.CleanContent = BaseHelper.ScrubHtml(article.Content);
                article.DatePublished = (i.PublicationDate == DateTime.MinValue ? DateTime.Now : i.PublicationDate).Ticks;
                article.Categories.Add(this.Data.Categories.All().FirstOrDefault(s => s.Id == source.CategoryId));
                article.UsedForClassication = false;
                article.IsForTest = IsForTest.HasValue ? IsForTest.Value : false;
                this.Data.NewsItems.Add(article);
                this.Data.SaveChanges();

                return true;
            }
            //if we already have it
            else
            {

                if (!oldArticle.Categories.Any(c => c.Id == source.CategoryId))
                {
                    oldArticle.Categories.Add(this.Data.Categories.All().FirstOrDefault(s => s.Id == source.CategoryId));
                    this.Data.NewsItems.Update(article);
                    this.Data.SaveChanges();
                }

            }
            return false;
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="GenericSyndicationItem"/> class using the supplied <see cref="RssItem"/>.
 /// </summary>
 /// <param name="item">The <see cref="RssItem"/> to build an abstraction against.</param>
 /// <exception cref="ArgumentNullException">The <paramref name="item"/> is a null reference (Nothing in Visual Basic).</exception>
 public GenericSyndicationItem(RssItem item)
 {
     Guard.ArgumentNotNull(item, "item");
     this.LoadFrom(item);
 }
        /// <summary>
        /// Initializes the supplied <see cref="RssItem"/> using the specified <see cref="XPathNavigator"/> and <see cref="XmlNamespaceManager"/>.
        /// </summary>
        /// <param name="item">The <see cref="RssItem"/> to be filled.</param>
        /// <param name="navigator">The <see cref="XPathNavigator"/> used to navigate the item XML data.</param>
        /// <param name="manager">The <see cref="XmlNamespaceManager"/> used to resolve XML namespace prefixes.</param>
        /// <param name="settings">The <see cref="SyndicationResourceLoadSettings"/> object used to configure the load operation.</param>
        /// <exception cref="ArgumentNullException">The <paramref name="item"/> is a null reference (Nothing in Visual Basic).</exception>
        /// <exception cref="ArgumentNullException">The <paramref name="navigator"/> 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 FillItem(RssItem item, XPathNavigator navigator, XmlNamespaceManager manager, SyndicationResourceLoadSettings settings)
        {
            //------------------------------------------------------------
            //	Validate parameters
            //------------------------------------------------------------
            Guard.ArgumentNotNull(item, "item");
            Guard.ArgumentNotNull(navigator, "navigator");
            Guard.ArgumentNotNull(manager, "manager");
            Guard.ArgumentNotNull(settings, "settings");

            //------------------------------------------------------------
            //	Attempt to extract item information
            //------------------------------------------------------------
            XPathNavigator titleNavigator       = navigator.SelectSingleNode("title", manager);
            XPathNavigator linkNavigator        = navigator.SelectSingleNode("link", manager);
            XPathNavigator descriptionNavigator = navigator.SelectSingleNode("description", manager);
            XPathNavigator sourceNavigator      = navigator.SelectSingleNode("source", manager);
            XPathNodeIterator enclosureIterator = navigator.Select("enclosure", manager);
            XPathNodeIterator categoryIterator  = navigator.Select("category", manager);

            if (titleNavigator != null)
            {
                item.Title          = titleNavigator.Value;
            }

            if (descriptionNavigator != null)
            {
                item.Description    = descriptionNavigator.Value;
            }

            if (linkNavigator != null)
            {
                Uri link;
                if (Uri.TryCreate(linkNavigator.Value, UriKind.RelativeOrAbsolute, out link))
                {
                    item.Link       = link;
                }
            }

            if (sourceNavigator != null)
            {
                item.Source             = new RssSource();

                if (sourceNavigator.HasAttributes)
                {
                    string urlAttribute = sourceNavigator.GetAttribute("url", String.Empty);
                    Uri url;
                    if (Uri.TryCreate(urlAttribute, UriKind.RelativeOrAbsolute, out url))
                    {
                        item.Source.Url = url;
                    }
                }

                if(!String.IsNullOrEmpty(sourceNavigator.Value))
                {
                    item.Source.Title   = sourceNavigator.Value;
                }
            }

            if (enclosureIterator != null && enclosureIterator.Count > 0)
            {
                while (enclosureIterator.MoveNext())
                {
                    RssEnclosure enclosure  = new RssEnclosure();
                    Rss092SyndicationResourceAdapter.FillEnclosure(enclosure, enclosureIterator.Current, manager, settings);

                    item.Enclosures.Add(enclosure);
                }
            }

            if (categoryIterator != null && categoryIterator.Count > 0)
            {
                while (categoryIterator.MoveNext())
                {
                    RssCategory category    = new RssCategory();
                    Rss092SyndicationResourceAdapter.FillCategory(category, categoryIterator.Current, manager, settings);

                    item.Categories.Add(category);
                }
            }

            SyndicationExtensionAdapter adapter = new SyndicationExtensionAdapter(navigator, settings);
            adapter.Fill(item);
        }
Exemplo n.º 30
0
 private static IEnumerable<string> GetPodcastsFromExtensions(RssItem item) {
     if (item.HasExtensions) {
         var extension = item.FindExtension(YahooMediaSyndicationExtension.MatchByType) as YahooMediaSyndicationExtension;
         if (extension != null) {
             return from c in extension.Context.Contents
                    let url = GetPodcastUrl(c.Url)
                    where ContainsPodcastExtension(url)
                    select url;
         }
     }
     return Enumerable.Empty<string>();
 }
        /// <summary>
        /// Initializes the supplied <see cref="RssChannel"/> collection entities using the specified <see cref="XPathNavigator"/> and <see cref="XmlNamespaceManager"/>.
        /// </summary>
        /// <param name="channel">The <see cref="RssChannel"/> to be filled.</param>
        /// <param name="navigator">The <see cref="XPathNavigator"/> used to navigate the channel XML data.</param>
        /// <param name="manager">The <see cref="XmlNamespaceManager"/> used to resolve XML namespace prefixes.</param>
        /// <param name="settings">The <see cref="SyndicationResourceLoadSettings"/> object used to configure the load operation.</param>
        /// <exception cref="ArgumentNullException">The <paramref name="channel"/> is a null reference (Nothing in Visual Basic).</exception>
        /// <exception cref="ArgumentNullException">The <paramref name="navigator"/> 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 FillChannelCollections(RssChannel channel, XPathNavigator navigator, XmlNamespaceManager manager, SyndicationResourceLoadSettings settings)
        {
            //------------------------------------------------------------
            //	Validate parameters
            //------------------------------------------------------------
            Guard.ArgumentNotNull(channel, "channel");
            Guard.ArgumentNotNull(navigator, "navigator");
            Guard.ArgumentNotNull(manager, "manager");
            Guard.ArgumentNotNull(settings, "settings");

            //------------------------------------------------------------
            //	Extract channel collections information
            //------------------------------------------------------------
            XPathNodeIterator skipDaysIterator  = navigator.Select("skipDays/day", manager);
            XPathNodeIterator skipHoursIterator = navigator.Select("skipHours/hour", manager);
            XPathNodeIterator itemIterator      = navigator.Select("item", manager);

            if (skipDaysIterator != null && skipDaysIterator.Count > 0)
            {
                while (skipDaysIterator.MoveNext())
                {
                    if (!String.IsNullOrEmpty(skipDaysIterator.Current.Value))
                    {
                        try
                        {
                            DayOfWeek day = (DayOfWeek)Enum.Parse(typeof(DayOfWeek), skipDaysIterator.Current.Value, true);
                            if (!channel.SkipDays.Contains(day))
                            {
                                channel.SkipDays.Add(day);
                            }
                        }
                        catch (ArgumentException)
                        {
                            System.Diagnostics.Trace.TraceWarning("Rss091SyndicationResourceAdapter unable to determine DayOfWeek with a name of {0}.", skipDaysIterator.Current.Value);
                        }
                    }
                }
            }

            if (skipHoursIterator != null && skipHoursIterator.Count > 0)
            {
                while (skipHoursIterator.MoveNext())
                {
                    int hour;
                    if (Int32.TryParse(skipHoursIterator.Current.Value, NumberStyles.Integer, NumberFormatInfo.InvariantInfo, out hour))
                    {
                        hour    = hour - 1; // Convert to zero-based range

                        if (!channel.SkipHours.Contains(hour) && (hour >= 0 && hour <= 23))
                        {
                            channel.SkipHours.Add(hour);
                        }
                        else
                        {
                            System.Diagnostics.Trace.TraceWarning("Rss091SyndicationResourceAdapter unable to add duplicate or out-of-range skip hour with a value of {0}.", hour);
                        }
                    }
                }
            }

            if (itemIterator != null && itemIterator.Count > 0)
            {
                int counter = 0;
                while (itemIterator.MoveNext())
                {
                    RssItem item = new RssItem();
                    counter++;

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

                    XPathNavigator titleNavigator       = itemIterator.Current.SelectSingleNode("title", manager);
                    XPathNavigator linkNavigator        = itemIterator.Current.SelectSingleNode("link", manager);
                    XPathNavigator descriptionNavigator = itemIterator.Current.SelectSingleNode("description", manager);

                    if (titleNavigator != null)
                    {
                        item.Title          = titleNavigator.Value;
                    }

                    if (descriptionNavigator != null)
                    {
                        item.Description    = descriptionNavigator.Value;
                    }

                    if (linkNavigator != null)
                    {
                        Uri link;
                        if (Uri.TryCreate(linkNavigator.Value, UriKind.RelativeOrAbsolute, out link))
                        {
                            item.Link       = link;
                        }
                    }

                    SyndicationExtensionAdapter adapter = new SyndicationExtensionAdapter(itemIterator.Current, settings);
                    adapter.Fill(item);

                    ((Collection<RssItem>)channel.Items).Add(item);
                }
            }
        }
Exemplo n.º 32
0
        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);

            }
        }