Beispiel #1
0
        protected virtual SyndicationFeed ParseHeaders(XElement channel)
        {
            SyndicationFeed feed = new SyndicationFeed
            {
                Title = channel.Element("title").Value,
                Description = channel.Element("description").Value,
            };

            if (channel.Element("lastBuildDate") != null)
                feed.LastBuildDate = ParseDate(channel.Element("lastBuildDate").Value);

            if (channel.Element("pubDate") != null)
                feed.PublishDate = ParseDate(channel.Element("pubDate").Value);

            return feed;
        }
Beispiel #2
0
        /// <summary>
        /// Gets the feed containing meta data about the feed and the feed entries.
        /// </summary>
        /// <param name="cancellationToken">A <see cref="CancellationToken"/> signifying if the request is cancelled.</param>
        /// <returns>A <see cref="SyndicationFeed"/>.</returns>
        public async Task<SyndicationFeed> GetFeed(CancellationToken cancellationToken)
        {
            SyndicationFeed feed = new SyndicationFeed()
            {
                // id (Required) - The feed universally unique identifier.
                Id = FeedId,
                // title (Required) - Contains a human readable title for the feed. Often the same as the title of the 
                //                    associated website. This value should not be blank.
                Title = SyndicationContent.CreatePlaintextContent("Моє місто - про Київ цікаво"),
                // items (Required) - The items to add to the feed.
                Items = await GetItems(cancellationToken),
                // subtitle (Recommended) - Contains a human-readable description or subtitle for the feed.
                Description = SyndicationContent.CreatePlaintextContent("Київські новини та аналітика, повна афіша Києва, сервіси для киян"),
                // updated (Optional) - Indicates the last time the feed was modified in a significant way.
                LastUpdatedTime = DateTimeOffset.Now,
                Language = "uk-UA",
            };

            // self link (Required) - The URL for the syndication feed.
            feed.Links.Add(SyndicationLink.CreateSelfLink(new Uri(FeedUrl), "Rss"));

            // alternate link (Recommended) - The URL for the web page showing the same data as the syndication feed.
            //feed.Links.Add(SyndicationLink.CreateAlternateLink(new Uri(SiteUrl), "Html"));

            // hub link (Recommended) - The URL for the PubSubHubbub hub. Used to push new entries to subscribers 
            //                          instead of making them poll the feed. See feed updated method below.
            feed.Links.Add(new SyndicationLink(new Uri(PubSubHubbubHubUrl), "hub", null, null, 0));


            // author (Recommended) - Names one author of the feed. A feed may have multiple author elements. A feed 
            //                        must contain at least one author element unless all of the entry elements contain 
            //                        at least one author element.
            feed.Authors.Add(GetPerson());

            // category (Optional) - Specifies a category that the feed belongs to. A feed may have multiple category 
            //                       elements.
            feed.Categories.Add(new SyndicationCategory("Новини"));

            // contributor (Optional) - Names one contributor to the feed. An feed may have multiple contributor 
            //                          elements.
            feed.Contributors.Add(GetPerson());

            return feed;
        }
Beispiel #3
0
        public void ReadFrom_SyndicationFeed()
        {
            SyndicationFeed f = SyndicationFeed.Load(CreateReader("<rss version='2.0'><channel><title>test</title></channel></rss>"));

            Assert.IsNotNull(f.Title);
        }
Beispiel #4
0
        private void LoadRssIntoTempFile()
        {
            try
            {
                using (XmlReader reader = XmlReader.Create(Settings.Default.LibraryPath + @"\" + this._mediaid + ".xml"))
                {
                    SyndicationFeed feed = SyndicationFeed.Load(reader);
                    int             num  = 0;
                    int             num2 = 0;
                    using (IEnumerator <SyndicationItem> enumerator = feed.Items.GetEnumerator())
                    {
                        while (enumerator.MoveNext())
                        {
                            SyndicationItem current = enumerator.Current;
                            num++;
                        }
                    }
                    if (this._numItems == 0)
                    {
                        this._numItems = num;
                    }
                    if (this._numItems > num)
                    {
                        this._numItems = num;
                    }
                    foreach (SyndicationItem item in feed.Items)
                    {
                        string str2;
                        string text;
                        num2++;
                        if (this._takeItemsFrom == "end")
                        {
                            if (num2 >= this._numItems)
                            {
                                goto Label_00D3;
                            }
                            continue;
                        }
                        if (num2 > this._numItems)
                        {
                            continue;
                        }
Label_00D3:
                        str2 = this._documentTemplate.Replace("[Title]", item.Title.Text.ToString());
                        if (item.Summary == null)
                        {
                            text = item.ElementExtensions.ReadElementExtensions <string>("encoded", "http://purl.org/rss/1.0/modules/content/")[0].ToString();
                        }
                        else
                        {
                            text = item.Summary.Text;
                        }
                        str2 = str2.Replace("[Description]", text).Replace("[Date]", item.PublishDate.ToString("F"));
                        if (item.Links.Count > 0)
                        {
                            str2 = str2.Replace("[Link]", item.Links[0].Uri.ToString());
                        }
                        if ((this._direction == "left") || (this._direction == "right"))
                        {
                            str2 = str2.Replace("<p>", "").Replace("</p>", "");
                            this._documentText = this._documentText + string.Format("<span class='article' style='padding-left:4px;'>{0}</span>", str2);
                            continue;
                        }
                        this._documentText = this._documentText + string.Format("<div class='RssItem' style='display:block;padding:4px;Width:{1}'>{0}</div>", str2, base.Width - 10.0);
                    }
                    this._documentText = this._documentText + this.CopyrightNotice;
                    if (this._direction == "none")
                    {
                        this._bodyText = this._documentText;
                    }
                    else
                    {
                        string str4 = "";
                        string str5 = "";
                        if ((this._direction == "left") || (this._direction == "right"))
                        {
                            str5 = "white-space: nowrap";
                            this._documentText = string.Format("<nobr>{0}</nobr>", this._documentText);
                        }
                        else
                        {
                            str5 = string.Format("Width: {0}px;", base.Width - 50.0);
                        }
                        if (this._direction == "single")
                        {
                            str4 = str4 + string.Format("<div id='text'>{0}</div>", this._documentText);
                        }
                        else
                        {
                            string str6 = "left";
                            if (this._direction == "right")
                            {
                                str6 = "right";
                            }
                            str4 = str4 + string.Format("<div id='text' style='position:relative;overflow:hidden;Width:{0}px; Height:{1}px;'>", base.Width - 10.0, base.Height) + string.Format("<div id='innerText' style='position:absolute; {2}: 0px; top: 0px; {0}'>{1}</div></div>", str5, this._documentText, str6);
                        }
                        this._bodyText = str4;
                    }
                    this._tempHtml.BodyContent = this._bodyText;
                }
            }
            catch (Exception exception)
            {
                Trace.WriteLine(string.Format("[*]ScheduleID:{1},LayoutID:{2},MediaID:{3},Message:{0}", new object[] { exception.Message, this._scheduleId, this._layoutId, this._mediaid }));
                this._bodyText             = "<h1>Unable to load feed</h1>";
                this._tempHtml.BodyContent = this._bodyText;
                System.IO.File.Delete(Settings.Default.LibraryPath + @"\" + this._mediaid + ".xml");
            }
        }
Beispiel #5
0
 public void Close()
 {
     this._rssFeed      = null;
     this._errorMessage = string.Empty;
 }
Beispiel #6
0
        /// <summary>
        /// Gets the feed containing meta data about the feed and the feed entries.
        /// </summary>
        /// <param name="cancellationToken">A <see cref="CancellationToken"/> signifying if the request is cancelled.</param>
        /// <returns>A <see cref="SyndicationFeed"/>.</returns>
        public async Task <SyndicationFeed> GetFeed(CancellationToken cancellationToken)
        {
            SyndicationFeed feed = new SyndicationFeed()
            {
                // id (Required) - The feed universally unique identifier.
                Id = FeedId,
                // title (Required) - Contains a human readable title for the feed. Often the same as the title of the
                //                    associated website. This value should not be blank.
                Title = SyndicationContent.CreatePlaintextContent("Boilerplate"),
                // items (Required) - The items to add to the feed.
                Items = await this.GetItems(cancellationToken),
                // subtitle (Recommended) - Contains a human-readable description or subtitle for the feed.
                Description = SyndicationContent.CreatePlaintextContent(
                    "This is the Boilerplate feed description."),
                // updated (Optional) - Indicates the last time the feed was modified in a significant way.
                LastUpdatedTime = DateTimeOffset.Now,
                // logo (Optional) - Identifies a larger image which provides visual identification for the feed.
                //                   Images should be twice as wide as they are tall.
                ImageUrl = new Uri(this.urlHelper.AbsoluteContent("~/content/icons/atom-logo-96x48.png")),
                // rights (Optional) - Conveys information about rights, e.g. copyrights, held in and over the feed.
                Copyright = SyndicationContent.CreatePlaintextContent(
                    string.Format("© {0} - {1}", DateTime.Now.Year, Application.Name)),
                // lang (Optional) - The language of the feed.
                Language = "en-GB",
                // generator (Optional) - Identifies the software used to generate the feed, for debugging and other
                //                        purposes. Do not put in anything that identifies the technology you are using.
                // Generator = "Sample Code",
                // base (Buggy) - Add the full base URL to the site so that all other links can be relative. This is
                //                great, except some feed readers are buggy with it, INCLUDING FIREFOX!!!
                //                (See https://bugzilla.mozilla.org/show_bug.cgi?id=480600).
                // BaseUri = new Uri(this.urlHelper.AbsoluteRouteUrl(HomeControllerRoute.GetIndex))
            };

            // self link (Required) - The URL for the syndication feed.
            feed.Links.Add(SyndicationLink.CreateSelfLink(
                               new Uri(this.urlHelper.AbsoluteRouteUrl(HomeControllerRoute.GetFeed)),
                               ContentType.Atom));

            // alternate link (Recommended) - The URL for the web page showing the same data as the syndication feed.
            feed.Links.Add(SyndicationLink.CreateAlternateLink(
                               new Uri(this.urlHelper.AbsoluteRouteUrl(HomeControllerRoute.GetIndex)),
                               ContentType.Html));

            // hub link (Recommended) - The URL for the PubSubHubbub hub. Used to push new entries to subscribers
            //                          instead of making them poll the feed. See feed updated method below.
            feed.Links.Add(new SyndicationLink(new Uri(PubSubHubbubHubUrl), "hub", null, null, 0));

            // first, last, next previous (Optional) - Atom 1.0 supports paging of your feed. This is good if your feed
            //                                         becomes very large and needs splitting up into pages. To add
            //                                         paging, you must add links to the first, last, next and previous
            //                                         feed pages.
            // feed.Links.Add(new SyndicationLink(new Uri("http://example.com/feed"), "first", null, null, 0));
            // feed.Links.Add(new SyndicationLink(new Uri("http://example.com/feed?page=10"), "last", null, null, 0));
            // if ([HAS_PREVIOUS_PAGE])
            //     feed.Links.Add(new SyndicationLink(new Uri("http://example.com/feed?page=1")), "previous", null, null, 0));
            // if ([HAS_NEXT_PAGE])
            //     feed.Links.Add(new SyndicationLink(new Uri("http://example.com/feed?page=3"), "next", null, null, 0));

            // author (Recommended) - Names one author of the feed. A feed may have multiple author elements. A feed
            //                        must contain at least one author element unless all of the entry elements contain
            //                        at least one author element.
            feed.Authors.Add(this.GetPerson());

            // category (Optional) - Specifies a category that the feed belongs to. A feed may have multiple category
            //                       elements.
            feed.Categories.Add(new SyndicationCategory("CategoryName"));

            // contributor (Optional) - Names one contributor to the feed. An feed may have multiple contributor
            //                          elements.
            feed.Contributors.Add(this.GetPerson());

            // icon (Optional) - Identifies a small image which provides iconic visual identification for the feed.
            //                   Icons should be square.
            feed.SetIcon(this.urlHelper.AbsoluteContent("~/content/icons/atom-icon-48x48.png"));

            // Add the Yahoo Media namespace (xmlns:media="http://search.yahoo.com/mrss/") to the Atom feed.
            // This gives us extra abilities, like the ability to give thumbnail images to entries.
            // See http://www.rssboard.org/media-rss for more information.
            feed.AddYahooMediaNamespace();

            return(feed);
        }
Beispiel #7
0
        /// <summary>
        /// Create and set props for this object; sets up the latest item in this feed ONLY;
        /// multiple feed items are not currently supported
        /// </summary>
        public void Initialize()
        {
            string strError = string.Empty;

            try
            {
                new Uri(FeedUri);
            }
            catch (Exception e)
            {
                throw new ApplicationException(string.Format("FeedUri {0} is not a valid URI. Exception message: {1}", FeedUri, e.ToString()), e);
            }

            try
            {
                using (XmlReader Reader = XmlReader.Create(FeedUri))
                {
                    if ((!Reader.EOF) && !System.Diagnostics.Debugger.IsAttached)
                    {
                        _feed = SyndicationFeed.Load(Reader);

                        foreach (var Item in _feed.Items)
                        {
                            if (Item.Title != null && !string.IsNullOrEmpty(Item.Title.Text))
                            {
                                FeedTitle = Item.Title.Text;
                            }

                            try
                            {
                                FeedPublishDate = Item.PublishDate.LocalDateTime;
                            }
                            catch (Exception)
                            {
                                FeedPublishDate = DateTime.Now;
                            }

                            if (Item.Summary != null && !string.IsNullOrEmpty(Item.Summary.Text))
                            {
                                FeedContent = Item.Summary.Text;
                            }

                            if (Item.Links != null && Item.Links.Count > 0)
                            {
                                try
                                {
                                    FeedHref = Item.Links[0].GetAbsoluteUri().ToString();
                                }
                                catch (Exception)
                                {
                                    FeedHref = FeedUri;
                                }
                            }

                            return;                             //just do the first (latest one) for now, since this is how comm server is doing things
                        }
                    }
                }
            } catch (Exception e) {
                Errors.Add(e.Message);
            }
        }
        public void SetItemsNull()
        {
            SyndicationFeed feed = new SyndicationFeed();

            feed.Items = null;
        }
Beispiel #9
0
 public AtomActionResult(SyndicationFeed feed)
 {
     this.feed = feed;
 }
Beispiel #10
0
 public AtomFeed(SyndicationFeed feed)
     : base(feed, false)
 {
     items = feed.Items.Select(i => new AtomItem(i)).ToList();
     base.LastUpdatedTime = DateTime.UtcNow;
 }
 public Message CreateAtom10Response(SyndicationFeed feed)
 {
     return(CreateAtom10Response <Atom10FeedFormatter> (new Atom10FeedFormatter(feed), ref feed_serializer));
 }
        public void Import(string rssPath, Guid pageId)
        {
            using (var conn = new DataConnection(PublicationScope.Unpublished))
            {
                var mapLinks = new Dictionary <string, string>();

                var       client = new WebClient();
                XmlReader reader = new SyndicationFeedXmlReader(client.OpenRead(rssPath));


                var feed = SyndicationFeed.Load(reader);
                reader.Close();

                var links         = feed.Links.Select(d => d.Uri.ToString()).ToList();
                var defaultAuthor = DataFacade.GetData <Authors>().Select(d => d.Name).TheOneOrDefault() ?? "Anonymous";
                var blogAuthor    = feed.Authors.Select(d => d.Name).FirstOrDefault()
                                    ?? feed.ElementExtensions.ReadElementExtensions <string>("creator", "http://purl.org/dc/elements/1.1/").FirstOrDefault();;


                foreach (var item in feed.Items)
                {
                    using (new DataScope(PublicationScope.Published))
                    {
                        var itemDate = item.PublishDate == DateTimeOffset.MinValue ? DateTime.Now : item.PublishDate.DateTime;
                        foreach (var itemLink in item.Links)
                        {
                            mapLinks[itemLink.Uri.OriginalString] = BlogFacade.GetBlogInternalPageUrl(itemDate, item.Title.Text, pageId);
                        }
                    }
                }

                foreach (var item in feed.Items)
                {
                    try
                    {
                        var    content  = new XDocument();
                        string text     = null;
                        var    itemDate = item.PublishDate == DateTimeOffset.MinValue ? DateTime.Now : item.PublishDate.DateTime;



                        if (text == null && item.Content != null)
                        {
                            var syndicationContent = item.Content as TextSyndicationContent;
                            if (syndicationContent != null)
                            {
                                text = syndicationContent.Text;
                            }
                        }
                        if (text == null)
                        {
                            text = item.ElementExtensions.ReadElementExtensions <string>("encoded", "http://purl.org/rss/1.0/modules/content/")
                                   .FirstOrDefault();
                        }
                        if (text == null && item.Summary != null)
                        {
                            text = item.Summary.Text;
                        }

                        content = MarkupTransformationServices.TidyHtml(text).Output;

                        //somewhere empty <title></title> created
                        foreach (var title in content.Descendants(Namespaces.Xhtml + "title").ToList())
                        {
                            if (string.IsNullOrWhiteSpace(title.Value))
                            {
                                title.Remove();
                            }
                        }


                        foreach (var img in content.Descendants(Namespaces.Xhtml + "img"))
                        {
                            var src = img.GetAttributeValue("src");
                            if (!string.IsNullOrEmpty(src))
                            {
                                foreach (var link in links)
                                {
                                    if (src.StartsWith(link))
                                    {
                                        var newImage = ImportMedia(src, string.Format(FolderFormat, itemDate, item.Title.Text));
                                        if (newImage != null)
                                        {
                                            img.SetAttributeValue("src", MediaUrlHelper.GetUrl(newImage, true));
                                        }
                                        break;
                                    }
                                }
                            }
                        }

                        foreach (var a in content.Descendants(Namespaces.Xhtml + "a"))
                        {
                            var href = a.GetAttributeValue("href");
                            if (!string.IsNullOrEmpty(href))
                            {
                                foreach (var link in links)
                                {
                                    if (href.StartsWith(link))
                                    {
                                        if (mapLinks.ContainsKey(href))
                                        {
                                            a.SetAttributeValue("href", mapLinks[href]);
                                        }
                                        else
                                        {
                                            var extension = Path.GetExtension(href).ToLower();
                                            switch (extension)
                                            {
                                            case ".jpg":
                                            case ".png":
                                            case ".gif":
                                            case ".pdf":
                                            case ".doc":
                                            case ".docx":
                                                var newMedia = ImportMedia(href, string.Format(FolderFormat, itemDate, item.Title.Text));
                                                a.SetAttributeValue("href", MediaUrlHelper.GetUrl(newMedia, true));
                                                break;

                                            default:
                                                a.SetAttributeValue("href", new Uri(href).PathAndQuery);
                                                break;
                                            }
                                        }
                                        break;
                                    }
                                }
                            }
                        }

                        var blogItem = DataFacade.BuildNew <Entries>();

                        var match = Regex.Match(item.Id, @"\b[A-F0-9]{8}(?:-[A-F0-9]{4}){3}-[A-F0-9]{12}\b", RegexOptions.IgnoreCase);
                        if (match.Success)
                        {
                            var id = Guid.Empty;
                            Guid.TryParse(match.Groups[0].Value, out id);
                            if (id != Guid.Empty && !DataFacade.GetData <Entries>(d => d.Id == id).Any())
                            {
                                blogItem.Id = id;
                            }
                        }

                        blogItem.Title  = item.Title.Text;
                        blogItem.PageId = pageId;
                        blogItem.Teaser = string.Empty;

                        var blogItemAuthor = item.Authors.Select(d => d.Name ?? d.Email).FirstOrDefault() ??
                                             item.ElementExtensions.ReadElementExtensions <string>("creator",
                                                                                                   "http://purl.org/dc/elements/1.1/").FirstOrDefault();


                        blogItem.Author = ImportAuthor(blogItemAuthor ?? blogAuthor ?? defaultAuthor);

                        foreach (var tag in item.Categories)
                        {
                            ImportTag(tag.Name);
                        }
                        blogItem.Tags = string.Join(",", item.Categories.Select(d => d.Name));

                        blogItem.Content = content.ToString();
                        blogItem.Date    = itemDate;

                        blogItem.PublicationStatus = GenericPublishProcessController.Draft;
                        blogItem = DataFacade.AddNew(blogItem);
                        blogItem.PublicationStatus = GenericPublishProcessController.Published;
                        DataFacade.Update(blogItem);



                        //break;
                    }
                    catch (Exception ex)
                    {
                        Log.LogError("Import Blog", ex);
                    }
                }

                //1st redirect
                var mapLinks2 = new Dictionary <string, string>();
                foreach (var maplink in mapLinks.ToList())
                {
                    var request = (HttpWebRequest)WebRequest.Create(maplink.Key);
                    request.AllowAutoRedirect = false;
                    var response = (HttpWebResponse)request.GetResponse();
                    var location = response.Headers["Location"];
                    if (!string.IsNullOrWhiteSpace(location))
                    {
                        location = new Uri(new Uri(maplink.Key), location).OriginalString;
                        foreach (var link in links)
                        {
                            if (location.StartsWith(link))
                            {
                                if (!mapLinks.ContainsKey(location))
                                {
                                    mapLinks[location]  = maplink.Value;
                                    mapLinks2[location] = maplink.Value;
                                }
                            }
                        }
                    }
                }
                //2nd redirect
                foreach (var maplink in mapLinks2.ToList())
                {
                    var request = (HttpWebRequest)WebRequest.Create(maplink.Key);
                    request.AllowAutoRedirect = false;
                    var response = (HttpWebResponse)request.GetResponse();
                    var location = response.Headers["Location"];
                    if (!string.IsNullOrWhiteSpace(location))
                    {
                        location = new Uri(new Uri(maplink.Key), location).OriginalString;
                        foreach (var link in links)
                        {
                            if (location.StartsWith(link))
                            {
                                if (!mapLinks.ContainsKey(location))
                                {
                                    mapLinks[location] = maplink.Value;
                                }
                            }
                        }
                    }
                }


                var mapFile = PathUtil.Resolve(@"~\App_Data\RequestUrlRemappings.xml");
                var map     = new XElement("RequestUrlRemappings");
                if (File.Exists(mapFile))
                {
                    map = XElement.Load(mapFile);
                }

                map.Add(new XComment(" Imported Blog " + DateTime.Now));
                map.Add(
                    mapLinks.Select(d => new XElement("Remapping",
                                                      new XAttribute("requestPath", new Uri(d.Key).PathAndQuery),
                                                      new XAttribute("rewritePath", d.Value)
                                                      ))

                    );
                map.Add(new XComment(" "));

                map.Save(mapFile);
            }
        }
Beispiel #13
0
        /// <summary>
        /// Gets the syndication feed.
        /// </summary>
        /// <param name="feed">The feed.</param>
        /// <param name="functionName">Name of the function.</param>
        /// <param name="resourceOfType">Type of resource.</param>
        /// <param name="feedParameterType">Type of the feed parameter.</param>
        /// <param name="isFeedForContact">Value indicating if its a feed for a contact.</param>
        /// <param name="id">The id.</param>
        /// <param name="name">The name.</param>
        /// <param name="lastName">The last name.</param>
        /// <param name="email">The email.</param>
        /// <param name="numberOfFeeds">The number of feeds.</param>
        /// <param name="date">The date.</param>
        /// <returns>The <see cref="SyndicationFeed"/>.</returns>
        private static SyndicationFeed GetSyndicationFeed(
            Feed feed,
            string functionName,
            Type resourceOfType,
            FeedParameterType feedParameterType,
            bool isFeedForContact,
            Guid id,
            string name,
            string lastName,
            string email,
            ushort numberOfFeeds, DateTime date)
        {
            if (string.IsNullOrEmpty(functionName))
            {
                return(null);
            }

            MethodInfo      getFeedMethod   = null;
            SyndicationFeed syndicationFeed = null;
            List <Type>     types           = new List <Type>();
            List <object>   parameters      = new List <object>();

            switch (feedParameterType)
            {
            case FeedParameterType.Id:
                types = new List <Type> {
                    id.GetType(), numberOfFeeds.GetType()
                };
                parameters = new List <object> {
                    id, numberOfFeeds
                };
                break;

            case FeedParameterType.Email:
                types = new List <Type> {
                    email.GetType(), numberOfFeeds.GetType()
                };
                parameters = new List <object> {
                    email, numberOfFeeds
                };
                break;

            case FeedParameterType.Name:
                types      = Utility.GetParameterTypeList(isFeedForContact, name, lastName, numberOfFeeds);
                parameters = Utility.GetParameterList(isFeedForContact, name, lastName, numberOfFeeds);
                break;

            case FeedParameterType.Date:
                types = new List <Type>()
                {
                    numberOfFeeds.GetType(), date.GetType()
                };
                parameters = new List <object> {
                    numberOfFeeds, date
                };
                break;
            }
            //GetFeedByDateAdded

            getFeedMethod = feed.GetType().GetMethod(
                functionName,
                BindingFlags.Public | BindingFlags.Instance,
                null,
                CallingConventions.Any,
                types.ToArray(), null
                );

            if (null != getFeedMethod)
            {
                syndicationFeed = (SyndicationFeed)getFeedMethod.MakeGenericMethod(resourceOfType).Invoke(feed, parameters.ToArray());
            }

            return(syndicationFeed);
        }
Beispiel #14
0
        /// <summary>
        /// Retrieves the SyndicationFeed object based on the parameters passed.
        /// </summary>
        /// <param name="resourceType">Requested resource type.</param>
        /// <param name="feedsOfType">Resource Type for the Feeds.</param>
        /// <param name="feedParameterType">Parameter type for the feed.</param>
        /// <param name="id">Parameter id for the feed.</param>
        /// <param name="name">Parameter name for the feed.</param>
        /// <param name="lastName">Parameter lastName for the feed.</param>
        /// <param name="email">Parameter email for the feed.</param>
        /// <param name="numberOfFeeds">Parameter noOfFeeds which indicate number of feeds that are to be retrieved.</param>
        /// <param name="date">Parameter date indicates date on which resources have been added or modified</param>
        /// <param name="connectionString">Data storage connection string.</param>
        /// <returns>Syndication Feed object.</returns>
        internal static SyndicationFeed GetSyndicationFeed(
            string resourceType,
            FeedsOfType feedsOfType,
            FeedParameterType feedParameterType,
            Guid id,
            string name,
            string lastName,
            string email,
            ushort numberOfFeeds,
            DateTime date,
            string connectionString)
        {
            if (string.IsNullOrEmpty(resourceType))
            {
                throw new ArgumentNullException("resourceType");
            }

            try
            {
                Feed feed = Utility.Feed(connectionString);

                Type resourceOfType = null;
                resourceOfType = Zentity.Platform.Feed.GetResourceType(resourceType);
                if (null == resourceOfType)
                {
                    throw new ArgumentException(Properties.Resources.SYNDICATION_EXCEPTION_ARGUMENTINVALID, "resourceType");
                }

                SyndicationFeed syndicationFeed = null;
                //make generic call
                switch (feedsOfType)
                {
                case FeedsOfType.Author:
                    if (!feed.IsResourceTypeIsOfTypeScholarlyWork(resourceType))
                    {
                        throw new ArgumentException(Properties.Resources.SYNDICATION_EXCEPTION_ARGUMENTINVALID, "resourceType");
                    }

                    syndicationFeed = Utility.GetSyndicationFeed(
                        feed,
                        "GetFeedByAuthor",
                        resourceOfType,
                        feedParameterType,
                        true,
                        id,
                        name,
                        lastName,
                        email,
                        numberOfFeeds, DateTime.MinValue);
                    break;

                case FeedsOfType.Tag:
                    syndicationFeed = Utility.GetSyndicationFeed(
                        feed,
                        "GetFeedByTag",
                        resourceOfType,
                        feedParameterType,
                        false,
                        id,
                        name,
                        lastName,
                        email,
                        numberOfFeeds, DateTime.MinValue);
                    break;

                case FeedsOfType.Category:
                    syndicationFeed = Utility.GetSyndicationFeed(
                        feed,
                        "GetFeedByCategory",
                        resourceOfType,
                        feedParameterType,
                        false,
                        id,
                        name,
                        lastName,
                        email,
                        numberOfFeeds, DateTime.MinValue);
                    break;

                case FeedsOfType.Contributor:
                    if (!feed.IsResourceTypeIsOfTypeScholarlyWork(resourceType))
                    {
                        throw new ArgumentException(Properties.Resources.SYNDICATION_EXCEPTION_ARGUMENTINVALID, "resourceType");
                    }

                    syndicationFeed = Utility.GetSyndicationFeed(
                        feed,
                        "GetFeedByContributor",
                        resourceOfType,
                        feedParameterType,
                        true,
                        id,
                        name,
                        lastName,
                        email,
                        numberOfFeeds, DateTime.MinValue);
                    break;

                case FeedsOfType.DateAdded:
                    syndicationFeed = Utility.GetSyndicationFeed(
                        feed,
                        "GetFeedByDateAdded",
                        resourceOfType,
                        feedParameterType,
                        false,
                        id,
                        name,
                        lastName,
                        email,
                        numberOfFeeds, date);
                    break;

                case FeedsOfType.DateModified:
                    syndicationFeed = Utility.GetSyndicationFeed(
                        feed,
                        "GetFeedByDateModified",
                        resourceOfType,
                        feedParameterType,
                        false,
                        id,
                        name,
                        lastName,
                        email,
                        numberOfFeeds, date);
                    break;
                }

                return(syndicationFeed);
            }
            catch (TargetInvocationException ex)
            {
                if (null != ex.InnerException)
                {
                    throw ex.InnerException;
                }
                throw;
            }
            catch (ArgumentNullException)
            {
                throw;
            }
            catch (ArgumentException)
            {
                throw;
            }
        }
        /// <summary>
        /// Gets the feed containing meta data about the feed and the feed entries.
        /// </summary>
        /// <returns>A <see cref="SyndicationFeed"/>.</returns>
        public SyndicationFeed GetFeed()
        {
            SyndicationFeed feed = new SyndicationFeed()
            {
                // id (Required) - The feed universally unique identifier.
                Id = FeedId,
                // title (Required) - Contains a human readable title for the feed. Often the same as the title of the 
                //                    associated website. This value should not be blank.
                Title = SyndicationContent.CreatePlaintextContent("ASP.NET MVC Boilerplate"),
                // items (Required) - The items to add to the feed.
                Items = this.GetItems(),
                // subtitle (Recommended) - Contains a human-readable description or subtitle for the feed.
                Description = SyndicationContent.CreatePlaintextContent(
                    "This is the ASP.NET MVC Boilerplate feed description."),
                // updated (Optional) - Indicates the last time the feed was modified in a significant way.
                LastUpdatedTime = DateTimeOffset.Now,
                // logo (Optional) - Identifies a larger image which provides visual identification for the feed. 
                //                   Images should be twice as wide as they are tall.
                ImageUrl = new Uri(this.urlHelper.AbsoluteContent("~/content/icons/atom-logo-96x48.png")),
                // rights (Optional) - Conveys information about rights, e.g. copyrights, held in and over the feed.
                Copyright = SyndicationContent.CreatePlaintextContent(
                    string.Format("© {0} - {1}", DateTime.Now.Year, Application.Name)),
                // lang (Optional) - The language of the feed.
                Language = "en-GB",
                // generator (Optional) - Identifies the software used to generate the feed, for debugging and other 
                //                        purposes. Do not put in anything that identifies the technology you are using.
                // Generator = "Sample Code",
                // base (Buggy) - Add the full base URL to the site so that all other links can be relative. This is 
                //                great, except some feed readers are buggy with it, INCLUDING FIREFOX!!! 
                //                (See https://bugzilla.mozilla.org/show_bug.cgi?id=480600).
                // BaseUri = new Uri(this.urlHelper.AbsoluteRouteUrl(HomeControllerRoute.GetIndex))
            };

            // self link (Required) - The URL for the syndication feed.
            feed.Links.Add(SyndicationLink.CreateSelfLink(
                new Uri(this.urlHelper.AbsoluteRouteUrl(HomeControllerRoute.GetFeed)),
                ContentType.Atom));

            // alternate link (Recommended) - The URL for the web page showing the same data as the syndication feed.
            feed.Links.Add(SyndicationLink.CreateAlternateLink(
                new Uri(this.urlHelper.AbsoluteRouteUrl(HomeControllerRoute.GetIndex)),
                ContentType.Html));

            // hub link (Recommended) - The URL for the PubSubHubbub hub. Used to push new entries to subscribers 
            //                          instead of making them poll the feed. See feed updated method below.
            feed.Links.Add(new SyndicationLink(new Uri(PubSubHubbubHubUrl), "hub", null, null, 0));
        
            // first, last, next previous (Optional) - Atom 1.0 supports paging of your feed. This is good if your feed
            //                                         becomes very large and needs splitting up into pages. To add
            //                                         paging, you must add links to the first, last, next and previous
            //                                         feed pages.
            // feed.Links.Add(new SyndicationLink(new Uri("http://example.com/feed"), "first", null, null, 0));
            // feed.Links.Add(new SyndicationLink(new Uri("http://example.com/feed?page=10"), "last", null, null, 0));
            // if ([HAS_PREVIOUS_PAGE])
            //     feed.Links.Add(new SyndicationLink(new Uri("http://example.com/feed?page=1")), "previous", null, null, 0));
            // if ([HAS_NEXT_PAGE])
            //     feed.Links.Add(new SyndicationLink(new Uri("http://example.com/feed?page=3"), "next", null, null, 0));

            // author (Recommended) - Names one author of the feed. A feed may have multiple author elements. A feed 
            //                        must contain at least one author element unless all of the entry elements contain 
            //                        at least one author element.
            feed.Authors.Add(this.GetPerson());

            // category (Optional) - Specifies a category that the feed belongs to. A feed may have multiple category 
            //                       elements.
            feed.Categories.Add(new SyndicationCategory("CategoryName"));

            // contributor (Optional) - Names one contributor to the feed. An feed may have multiple contributor 
            //                          elements.
            feed.Contributors.Add(this.GetPerson());

            // icon (Optional) - Identifies a small image which provides iconic visual identification for the feed. 
            //                   Icons should be square.
            feed.SetIcon(this.urlHelper.AbsoluteContent("~/content/icons/atom-icon-48x48.png"));

            // Add the Yahoo Media namespace (xmlns:media="http://search.yahoo.com/mrss/") to the Atom feed. 
            // This gives us extra abilities, like the ability to give thumbnail images to entries. 
            // See http://www.rssboard.org/media-rss for more information.
            feed.AddYahooMediaNamespace();

            return feed;
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="RssActionResult"/> class.
 /// </summary>
 /// <param name="syndicationFeed">The Atom 1.0 <see cref="SyndicationFeed" />.</param>
 public RssActionResult(SyndicationFeed syndicationFeed)
 {
     _syndicationFeed = syndicationFeed;
 }
        public static string GetReleaseYear(this SyndicationFeed feed)
        {
            XElement releaseDateElement = GetElement(feed, "releaseDate");

            return(GetReleaseDateFromElement(releaseDateElement));
        }
Beispiel #18
0
        public RemoteContentResponse ReadRemoteSource(LocalFeedInfo feedInfo)
        {
            _log.Debug("Trying to read remote source '{0}' (etag: {1}, last fetch: {2})", feedInfo.Url, feedInfo.Etag, feedInfo.LastFetch);

            try
            {
                if (feedInfo.LastFetch.HasValue && _configProvider.ProvideConfig().PrefetchHeadRequest)
                {
                    var head_request = _httpRequestFactory.CreateRequest(feedInfo.Url);
                    head_request.Method = "HEAD";
                    using (var head_response = (HttpWebResponse)head_request.GetResponseEx())
                    {
                        DateTime last_modified = head_response.LastModified.ToUniversalTime();
                        DateTime last_fetch    = feedInfo.LastFetch.Value.ToUniversalTime();
                        if (last_modified < last_fetch)
                        {
                            _log.Debug("HEAD request indicates that there is no new content available (last_modified={0}, last_fetch={1}), returning NotModified.", last_modified, last_fetch);
                            return(RemoteContentResponse.NotModified(head_response.StatusCode));
                        }
                    }
                }

                var get_request = _httpRequestFactory.CreateRequest(feedInfo.Url);
                if (feedInfo.LastFetch != null)
                {
                    get_request.IfModifiedSince = feedInfo.LastFetch.Value;
                }

                if (string.IsNullOrWhiteSpace(feedInfo.Etag) == false)
                {
                    get_request.Headers[HttpRequestHeader.IfNoneMatch] = feedInfo.Etag;
                }

                using (var response = (HttpWebResponse)get_request.GetResponseEx())
                {
                    if (response.StatusCode == HttpStatusCode.OK)
                    {
                        string etag = response.Headers[HttpResponseHeader.ETag];

                        Stream responseStream = response.GetResponseStream();
                        using (var streamReader = new StreamReader(responseStream))
                        {
                            string responseText = streamReader.ReadToEnd();

                            responseText = _contentPreProcessor.PreProcess(responseText);

                            using (var stringReader = new StringReader(responseText))
                            {
                                using (var reader = XmlReader.Create(stringReader))
                                {
                                    var feed = SyndicationFeed.Load(reader);

                                    _log.Info("Returning new content for remote source '{0}' with {1} items", feedInfo.Url, feed.Items.Count());

                                    return(new RemoteContentResponse(true, etag, feed, response.StatusCode));
                                }
                            }
                        }
                    }
                    else
                    {
                        string message = string.Format("No new content for remote source '{0}', response status is {1}", feedInfo.Url, response.StatusCode);

                        if (response.StatusCode == HttpStatusCode.NotModified)
                        {
                            _log.Debug(message);
                        }
                        else
                        {
                            _log.Warn(message);
                        }

                        return(RemoteContentResponse.NotModified(response.StatusCode));
                    }
                }
            }
            catch (Exception exc)
            {
                _log.ErrorException(string.Format("Failed to read remote source '{0}'", feedInfo.Url), exc);

                throw new CannotReachRemoteSourceException(feedInfo.Url, exc);
            }
        }
        public FeatureCollectionResult ImportFeed(SyndicationFeed feed)
        {
            if (feed == null)
                throw new ArgumentNullException("feed");

            FeatureCollectionResult fc = new FeatureCollectionResult();

            NameValueCollection namespaces = null;
            XmlNamespaceManager xnsm = null;
            string prefix = "";

            if (options.KeepNamespaces) {

                // Initialize namespaces
                namespaces = new NameValueCollection();
                namespaces.Set("", "http://geojson.org/ns#");
                namespaces.Set("atom", "http://www.w3.org/2005/Atom");
                XmlReader reader = feed.ElementExtensions.GetReaderAtElementExtensions();
                xnsm = new XmlNamespaceManager(reader.NameTable);
                foreach (var names in xnsm.GetNamespacesInScope(XmlNamespaceScope.All)) {
                    namespaces.Set(names.Key, names.Value);
                }
                fc.Properties.Add("@namespaces", namespaces);
                prefix = "atom:";
            }

            // Import Feed
            if (feed != null) {
                if ((feed.Authors != null) && (feed.Authors.Count > 0)) {
                    object[] authors = new object[feed.Authors.Count];
                    fc.Properties.Add(prefix + "authors", authors);
                    for (int i = 0; i < feed.Authors.Count; i++) {
                        Dictionary<string,object> author = new Dictionary<string, object>();
                        author.Add(prefix + "name", feed.Authors[i].Name);
                        author.Add(prefix + "email", feed.Authors[i].Email);
                        author.Add(prefix + "uri", feed.Authors[i].Uri);
                        author = author.Concat(util.ImportAttributeExtensions(feed.Authors[i].AttributeExtensions, namespaces, xnsm)).ToDictionary(x => x.Key, x => x.Value);
                        author = author.Concat(util.ImportElementExtensions(feed.Authors[i].ElementExtensions, namespaces)).ToDictionary(x => x.Key, x => x.Value);
                        authors[i] = author;
                    }
                }
                if (feed.BaseUri != null) {
                    fc.Properties.Add(prefix + "uri", feed.BaseUri.ToString());
                }
                if ((feed.Categories != null) && (feed.Categories.Count > 0)) {
                    object[] categories = new object[feed.Categories.Count];
                    fc.Properties.Add(prefix + "categories", categories);
                    for (int i = 0; i < feed.Categories.Count; i++) {
                        Dictionary<string,object> category = new Dictionary<string, object>();
                        category.Add(prefix + "name", feed.Categories[i].Name);
                        category.Add(prefix + "label", feed.Categories[i].Label);
                        category.Add(prefix + "scheme", feed.Categories[i].Scheme);
                        category = category.Union(util.ImportAttributeExtensions(feed.Categories[i].AttributeExtensions, namespaces, xnsm)).ToDictionary(x => x.Key, x => x.Value);
                        category = category.Union(util.ImportElementExtensions(feed.Categories[i].ElementExtensions, namespaces)).ToDictionary(x => x.Key, x => x.Value);
                        categories[i] = category;
                    }
                }
                if ((feed.Contributors != null) && (feed.Contributors.Count > 0)) {
                    object[] contributors = new object[feed.Contributors.Count];
                    fc.Properties.Add(prefix + "categories", contributors);
                    for (int i = 0; i < feed.Contributors.Count; i++) {
                        Dictionary<string,object> contributor = new Dictionary<string, object>();
                        contributor.Add(prefix + "name", feed.Contributors[i].Name);
                        contributor.Add(prefix + "email", feed.Contributors[i].Email);
                        contributor.Add(prefix + "uri", feed.Contributors[i].Uri);
                        contributor = contributor.Union(util.ImportAttributeExtensions(feed.Contributors[i].AttributeExtensions, namespaces, xnsm)).ToDictionary(x => x.Key, x => x.Value);
                        contributor = contributor.Union(util.ImportElementExtensions(feed.Contributors[i].ElementExtensions, namespaces)).ToDictionary(x => x.Key, x => x.Value);
                        contributors[i] = contributor;
                    }
                }
                if (feed.Copyright != null) {
                    fc.Properties.Add(prefix + "rights", feed.Copyright.Text);
                }
                if (feed.Description != null) {
                    fc.Properties.Add(prefix + "content", feed.Description.Text);
                }
                if (feed.Generator != null) {
                    fc.Properties.Add(prefix + "generator", feed.Generator);
                }
                fc.Properties.Add(prefix + "id", feed.Id);
                if (feed.ImageUrl != null)
                    fc.Properties.Add(prefix + "logo", feed.ImageUrl.ToString());
                if (feed.Language != null)
                    fc.Properties.Add(prefix + "language", feed.Language);
                if (feed.LastUpdatedTime != null)
                    fc.Properties.Add(prefix + "updated", feed.LastUpdatedTime);
                if ((feed.Links != null) && (feed.Links.Count > 0)) {
                    fc.Links = feed.Links;
                }
                if (feed.Title != null)
                    fc.Properties.Add(prefix + "title", feed.Title);

                if (feed.Items != null) {
                    foreach (var item in feed.Items) {
                        fc.FeatureResults.Add(ImportItem(item));
                    }
                }

                return fc;

            }
            return null;
        }
        public static string GetGenre(this SyndicationFeed item)
        {
            XElement primaryGenreElement = GetElement(item, "primaryGenre");

            return(primaryGenreElement != null?primaryGenreElement.Elements().Last().Value : null);
        }
Beispiel #21
0
        /// <summary>
        ///     Returns the xml rss string
        /// </summary>
        /// <returns></returns>
        public string GetSearchRssXml()
        {
            Item            currentItem = Sitecore.Context.Item;
            I_Base_Rss_Feed rssFeedItem = currentItem.GlassCast <I_Base_Rss_Feed>(inferType: false);

            SyndicationFeed feed          = null;
            Stopwatch       sw            = Stopwatch.StartNew();
            var             feedGenerator = _RssFeedGeneration;

            StringExtensions.WriteSitecoreLogs("Time taken to Create Feedgenerator", sw, "feedGenerator");
            if (feedGenerator == null)
            {
                Log.Error("Could Not Create RSS Feed Geneartor " + rssFeedItem.Rss_Feed_Generation, this);
                return(string.Empty);
            }
            sw   = Stopwatch.StartNew();
            feed = feedGenerator.GetRssFeed(rssFeedItem, _sitecoreContext, _itemReferences);
            StringExtensions.WriteSitecoreLogs("Time taken to Create GetRssFeed", sw, "GetRssFeed");

            if (feed == null)
            {
                Log.Error("Could Not Create RSS Feed With " + rssFeedItem.Rss_Feed_Generation, this);
                return(string.Empty);
            }

            var formatter = new Rss20FeedFormatter(feed);

            formatter.SerializeExtensionsAsAtom = false;
            sw = Stopwatch.StartNew();
            var itemRetriever = _RssSitecoreItemRetrieval;

            StringExtensions.WriteSitecoreLogs("Time taken to Create itemRetriever", sw, "itemRetriever");
            if (itemRetriever == null)
            {
                Log.Error("Could Not Create Item Retriever With " + rssFeedItem.Sitecore_Item_Retrieval, this);
                return(string.Empty);
            }

            var rssItemGenerator = _RssItemGeneration;

            if (rssItemGenerator == null)
            {
                Log.Error("Could Not Create Item Generator With " + rssFeedItem.Rss_Item_Generation, this);
                return(string.Empty);
            }
            sw = Stopwatch.StartNew();
            var sitecoreItems = itemRetriever.GetSitecoreItems(currentItem);

            StringExtensions.WriteSitecoreLogs("Time taken to Create sitecoreItems", sw, "GetSitecoreItems");
            List <SyndicationItem> syndicationItems = new List <SyndicationItem>();

            foreach (Item sitecoreItem in sitecoreItems)
            {
                var syndicationItem = rssItemGenerator.GetSyndicationItemFromSitecore(_sitecoreContext, sitecoreItem);
                if (syndicationItem == null)
                {
                    continue;
                }

                syndicationItems.Add(syndicationItem);
            }

            feed.Items = syndicationItems;


            var output = new StringBuilder();

            using (var writer = XmlWriter.Create(output, new XmlWriterSettings {
                Indent = true
            }))
            {
                feed.SaveAsRss20(writer);
                writer.Flush();
                writer.Close();
                string rs = output.ToString().Replace("utf-16", "utf-8");
                rs = RemoveInvalidXmlChars(rs);
                return(rs);
            }
        }
Beispiel #22
0
        private static IEnumerable <NewsInfo> GetNewsInfo(string feedurl)
        {
            var feed = DbUtil.Db.RssFeeds.FirstOrDefault(r => r.Url == feedurl);

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

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

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

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

            try
            {
                var resp = req.GetHttpResponse();
                if (resp == null)
                {
                    return(new List <NewsInfo>());
                }

                if (resp.StatusCode != HttpStatusCode.NotModified)
                {
                    feed.LastModified = resp.LastModified;
                    var rs = resp.GetResponseStream();
                    if (rs == null)
                    {
                        return(new List <NewsInfo>());
                    }

                    var sr = new StreamReader(rs);
                    feed.Data = sr.ReadToEnd();
                    sr.Close();
                    DbUtil.Db.SubmitChanges();
                }
            }
            catch
            {
                return(new List <NewsInfo>());
            }
            if (feed.Data == null)
            {
                return(new List <NewsInfo>());
            }

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

                var posts = from item in f.Items
                            select new NewsInfo
                {
                    Title     = item.Title.Text,
                    Published = item.PublishDate.DateTime,
                    Url       = item.Links.Single(i => i.RelationshipType == "alternate")?.GetAbsoluteUri()?.AbsoluteUri
                };
                return(posts);
            }
            catch
            {
                return(new List <NewsInfo>());
            }
        }
Beispiel #23
0
 public SyndicationItemEventArgs(SyndicationItem item, SyndicationFeed feed, T source)
 {
     SyndicationItem = item;
     SyndicationFeed = feed;
     Source          = source;
 }
 public void LoadEntry()
 {
     // entry is not allowed.
     SyndicationFeed.Load(XmlReader.Create(new StringReader("<entry xmlns=\"http://www.w3.org/2005/Atom\"></entry>")));
 }
Beispiel #25
0
 static public void LoadRazorAssemblies()
 {
     if (!_loadDone)
     {
         try
         {
             //Force the load of the assemblies
             if (dummy == null)
             {
                 dummy = new HtmlString("");
             }
             if (dummy2 == null)
             {
                 dummy2 = new DataTable();
             }
             if (dummy3 == null)
             {
                 dummy3 = new OleDbConnection();
             }
             if (dummy4 == null)
             {
                 dummy4 = new LdapConnection("");
             }
             if (dummy5 == null)
             {
                 dummy5 = new SyndicationFeed();
             }
             if (dummy6 == null)
             {
                 dummy6 = new XDocument();
             }
             if (dummy7 == null)
             {
                 dummy7 = new Control();                 //!NETCore
             }
             if (dummy8 == null)
             {
                 dummy8 = new PrincipalContext(ContextType.Machine);
             }
             if (dummy9 == null)
             {
                 dummy9 = JWT.DefaultSettings;                 //!NETCore
             }
             if (dummy10 == null)
             {
                 dummy10 = JObject.Parse("{}");
             }
             if (dummy11 == null)
             {
                 dummy11 = new ZipFile();                  //!NETCore
             }
             if (dummy12 == null)
             {
                 dummy12 = new OdbcConnection();
             }
             if (dummy13 == null)
             {
                 dummy13 = new SqlConnection();
             }
         }
         catch (Exception ex)
         {
             Console.WriteLine(ex.Message);
         }
         _loadDone = true;
     }
 }
 public void LoadFeed()
 {
     SyndicationFeed.Load(XmlReader.Create(new StringReader("<feed xmlns=\"http://www.w3.org/2005/Atom\"></feed>")));
 }
 public GalleriesModel(String galleriesIndexHttpPath, IList <Gallery> galleries, SyndicationFeed feed)
 {
     GalleriesIndexHttpPath = galleriesIndexHttpPath;
     Galleries = new ReadOnlyCollection <Gallery>(galleries);
     Feed      = feed;
 }
Beispiel #28
0
        // GET: rss/{subverseName}
        public ActionResult Rss(string subverseName)
        {
            var submissions = new List <Message>();

            if (subverseName != null && subverseName != "all")
            {
                // return only frontpage submissions from a given subverse
                var subverse = _db.Subverses.Find(subverseName);
                if (subverse != null)
                {
                    submissions = (from message in _db.Messages
                                   where message.Name != "deleted" && message.Subverse == subverse.name
                                   select message)
                                  .OrderByDescending(s => s.Rank)
                                  .Take(25)
                                  .ToList();
                }
            }
            else if (subverseName == "all")
            {
                // return submissions from all subs
                submissions = (from message in _db.Messages
                               join subverse in _db.Subverses on message.Subverse equals subverse.name
                               where message.Name != "deleted" && subverse.private_subverse != true && message.Rank > 0.00009
                               where !(from bu in _db.Bannedusers select bu.Username).Contains(message.Name)
                               select message).OrderByDescending(s => s.Rank).ThenByDescending(s => s.Date).Take(25).ToList();
            }
            else
            {
                // return site-wide frontpage submissions
                submissions = (from message in _db.Messages
                               where message.Name != "deleted"
                               join defaultsubverse in _db.Defaultsubverses on message.Subverse equals defaultsubverse.name
                               select message)
                              .OrderByDescending(s => s.Rank)
                              .Take(25)
                              .ToList();
            }

            var feed = new SyndicationFeed("Voat", "Have your say", new Uri("http://www.voat.co"))
            {
                Language = "en-US",
                ImageUrl =
                    new Uri("http://" + System.Web.HttpContext.Current.Request.Url.Authority +
                            "/Graphics/voat-logo.png")
            };

            var feedItems = new List <SyndicationItem>();

            foreach (var submission in submissions)
            {
                var commentsUrl = new Uri("http://" + System.Web.HttpContext.Current.Request.Url.Authority + "/v/" + submission.Subverse + "/comments/" + submission.Id);
                var subverseUrl = new Uri("http://" + System.Web.HttpContext.Current.Request.Url.Authority + "/v/" + submission.Subverse);

                var authorName = submission.Name;

                if (submission.Type == 1)
                {
                    // message type submission
                    if (submission.Anonymized || submission.Subverses.anonymized_mode)
                    {
                        authorName = submission.Id.ToString(CultureInfo.InvariantCulture);
                    }

                    var item = new SyndicationItem(
                        submission.Title,
                        submission.MessageContent + "</br>" + "Submitted by " + "<a href='u/" + authorName + "'>" + authorName + "</a> to <a href='" + subverseUrl + "'>" + submission.Subverse + "</a> | <a href='" + commentsUrl + "'>" + submission.Comments.Count() + " comments",
                        commentsUrl,
                        "Item ID",
                        submission.Date);
                    feedItems.Add(item);
                }
                else
                {
                    // link type submission
                    var linkUrl = new Uri(submission.MessageContent);
                    authorName = submission.Name;

                    if (submission.Anonymized || submission.Subverses.anonymized_mode)
                    {
                        authorName = submission.Id.ToString(CultureInfo.InvariantCulture);
                    }

                    // add a thumbnail if submission has one
                    if (submission.Thumbnail != null)
                    {
                        var thumbnailUrl = new Uri("http://" + System.Web.HttpContext.Current.Request.Url.Authority + "/Thumbs/" + submission.Thumbnail).ToString();
                        var item         = new SyndicationItem(
                            submission.Linkdescription,
                            "<a xmlns='http://www.w3.org/1999/xhtml' href='" + commentsUrl + "'><img title='" + submission.Linkdescription + "' alt='" + submission.Linkdescription + "' src='" + thumbnailUrl + "' /></a>" +
                            "</br>" +
                            "Submitted by " + "<a href='u/" + authorName + "'>" + authorName + "</a> to <a href='" + subverseUrl + "'>" + submission.Subverse + "</a> | <a href='" + commentsUrl + "'>" + submission.Comments.Count() + " comments</a>" +
                            " | <a href='" + linkUrl + "'>link</a>",
                            commentsUrl,
                            "Item ID",
                            submission.Date);

                        feedItems.Add(item);
                    }
                    else
                    {
                        var item = new SyndicationItem(
                            submission.Linkdescription,
                            "Submitted by " + "<a href='u/" + authorName + "'>" + authorName + "</a> to <a href='" + subverseUrl + "'>" + submission.Subverse + "</a> | <a href='" + commentsUrl + "'>" + submission.Comments.Count() + " comments",
                            commentsUrl,
                            "Item ID",
                            submission.Date);
                        feedItems.Add(item);
                    }
                }
            }

            feed.Items = feedItems;
            return(new FeedResult(new Rss20FeedFormatter(feed)));
        }
Beispiel #29
0
 /// <summary>
 /// Creates a new instance of an <see cref="SyndicationFeedFormatter"/> class with the specified
 /// <see cref="SyndicationFeed"/> instance.
 /// </summary>
 /// <param name="feedToWrite">The <see cref="SyndicationFeed"/> to serialize.</param>
 /// <returns>
 /// A new instance of the <see cref="SyndicationFeedFormatter"/> class with the specified
 /// <see cref="SyndicationFeed"/> instance.
 /// </returns>
 internal abstract SyndicationFeedFormatter CreateSyndicationFeedFormatter(SyndicationFeed feedToWrite);
Beispiel #30
0
        public void WriteToNull()
        {
            SyndicationFeed feed = new SyndicationFeed();

            new Rss20FeedFormatter(feed).WriteTo(null);
        }
Beispiel #31
0
 public static void SetNamespace(SyndicationFeed feed, string prefix, XNamespace nsUri)
 {
     feed.AttributeExtensions.Add(new XmlQualifiedName(prefix,
                                                       "http://www.w3.org/2000/xmlns/"), nsUri.ToString());
 }
Beispiel #32
0
        public void ProcessRequest(HttpContext context)
        {
            if (!ProcessAuthorization(context))
            {
                AccessDenied(context);
                return;
            }

            var productId    = ParseGuid(context.Request[ProductParam]);
            var product      = WebItemManager.Instance[productId.GetValueOrDefault()];
            var products     = WebItemManager.Instance.GetItemsAll <IProduct>().ToDictionary(p => p.GetSysName());
            var lastModified = GetLastModified(context);

            var feeds = FeedAggregateDataProvider.GetFeeds(new FeedApiFilter
            {
                Product = product != null ? product.GetSysName() : null,
                From    = lastModified ?? DateTime.UtcNow.AddDays(-14),
                To      = DateTime.UtcNow,
                OnlyNew = true
            })
                        .OrderByDescending(f => f.CreatedDate)
                        .Take(100)
                        .Select(f => f.ToFeedMin())
                        .ToList();

            if (lastModified != null && feeds.Count == 0)
            {
                context.Response.StatusCode        = (int)HttpStatusCode.NotModified;
                context.Response.StatusDescription = "Not Modified";
            }

            var feedItems = feeds.Select(f =>
            {
                var item = new SyndicationItem(
                    HttpUtility.HtmlDecode((products.ContainsKey(f.Product) ? products[f.Product].Name + ": " : string.Empty) + f.Title),
                    string.Empty,
                    new Uri(CommonLinkUtility.GetFullAbsolutePath(f.ItemUrl)),
                    f.Id,
                    new DateTimeOffset(TenantUtil.DateTimeToUtc(f.CreatedDate)))
                {
                    PublishDate = f.CreatedDate,
                };
                if (f.Author != null && f.Author.UserInfo != null)
                {
                    var u = f.Author.UserInfo;
                    item.Authors.Add(new SyndicationPerson(u.Email, u.DisplayUserName(false), CommonLinkUtility.GetUserProfile(u.ID)));
                }
                return(item);
            });

            var lastUpdate = DateTime.UtcNow;

            if (feeds.Count > 0)
            {
                lastUpdate = feeds.Max(x => x.ModifiedDate);
            }

            var feed = new SyndicationFeed(
                CoreContext.TenantManager.GetCurrentTenant().Name,
                string.Empty,
                new Uri(context.Request.GetUrlRewriter(), VirtualPathUtility.ToAbsolute("~/feed.aspx")),
                TenantProvider.CurrentTenantID.ToString(),
                new DateTimeOffset(lastUpdate),
                feedItems);

            var rssFormatter = new Atom10FeedFormatter(feed);
            var settings     = new XmlWriterSettings
            {
                CheckCharacters  = false,
                ConformanceLevel = ConformanceLevel.Document,
                Encoding         = Encoding.UTF8,
                Indent           = true,
            };

            using (var writer = XmlWriter.Create(context.Response.Output, settings))
            {
                rssFormatter.WriteTo(writer);
            }
            context.Response.Charset     = Encoding.UTF8.WebName;
            context.Response.ContentType = "application/atom+xml";
            context.Response.AddHeader("ETag", DateTime.UtcNow.ToString("yyyyMMddHHmmss"));
            context.Response.AddHeader("Last-Modified", DateTime.UtcNow.ToString("R"));
        }
 private void AddItem(SyndicationFeed feed, int item, int version)
 {
     (feed.Items as List <SyndicationItem>) !.Add(Item(item, version));
 }
Beispiel #34
0
 public static void Snippet4()
 {
     // <Snippet4>
     SyndicationFeed feed = new SyndicationFeed("My Data Feed", "This is a sample feed", new Uri("http://localhost/MyDataService"));
     // </Snippet4>
 }
Beispiel #35
0
        /// <summary>
        /// Returns and rss or atom feed
        /// </summary>
        /// <param name="instance"></param>
        /// <returns></returns>
        protected internal ActionResult GetFeed(object instance)
        {
            try
            {
                string title  = "CodePaste.NET";
                string action = RouteData.Values["listAction"] as string;
                if (string.IsNullOrEmpty(action))
                {
                    action = RouteData.Values["Action"] as string ?? string.Empty;
                }
                action = action.ToLower();

                if (action == "recent")
                {
                    title = "CodePaste.NET Recent Snippets";
                }
                else if (action == "mysnippets")
                {
                    title = "CodePaste.NET - My Snippets";
                }

                SyndicationFeed feed = new SyndicationFeed(title, "Paste and Link .NET Code", new Uri(Request.Url.AbsoluteUri));

                feed.BaseUri         = new Uri("http://codepaste.net/recent");
                feed.LastUpdatedTime = DateTime.Now;

                List <SyndicationItem> feedItems = new List <SyndicationItem>();
                foreach (CodeSnippetListItem item in (IEnumerable)instance)
                {
                    // remove lower ascii characters (< 32 exclude 9,10,13)
                    string code = Regex.Replace(item.Code, @"[\u0000-\u0008,\u000B,\u000C,\u000E-\u001F]", "");

                    SyndicationItem rssItem = new SyndicationItem()
                    {
                        Id      = item.Id,
                        Title   = SyndicationContent.CreateHtmlContent(item.Title),
                        Content = SyndicationContent.CreateHtmlContent(
                            //"<link href=\"" + WebUtils.ResolveServerUrl("~/css/csharp.css") + "\" rel=\"stylesheet\" type=\"text/css\">\r\n <style type='text/css'>.kwrd { color: blue; font-weight: bold }</style>\r\n" +
                            "<pre>\r\n" +
                            HtmlUtils.HtmlEncode(code) +
                            //snippet.GetFormattedCode(item.Code, item.Language, item.ShowLineNumbers) +
                            "</pre>"),
                        PublishDate = item.Entered,
                    };

                    if (!string.IsNullOrEmpty(item.Author))
                    {
                        rssItem.Authors.Add(new SyndicationPerson("", item.Author, null));
                    }

                    rssItem.Links.Add(new SyndicationLink(new Uri(WebUtils.GetFullApplicationPath() + "/" + item.Id),
                                                          "alternate", item.Title, "text/html", 1000));

                    feedItems.Add(rssItem);
                }

                feed.Items = feedItems;

                MemoryStream ms       = new MemoryStream();
                var          settings = new XmlWriterSettings()
                {
                    CheckCharacters = false
                };
                XmlWriter writer = XmlWriter.Create(ms, settings);
                if (Format == "rss")
                {
                    Rss20FeedFormatter rssFormatter = new Rss20FeedFormatter(feed);
                    rssFormatter.WriteTo(writer);
                }
                else
                {
                    Atom10FeedFormatter atomFormatter = new Atom10FeedFormatter(feed);
                    atomFormatter.WriteTo(writer);
                }
                writer.Flush();

                ms.Position = 0;

                return(Content(Encoding.UTF8.GetString(ms.ToArray()), "application/xml"));
            }
            catch (Exception ex)
            {
                Response.Write(HtmlUtils.DisplayMemo("Error: " + ex.GetBaseException().Message + "\r\n" + ex.StackTrace));
                Response.End();
                return(null);
            }

            return(null);
        }
Beispiel #36
0
        public PreviewViewModel(SyndicationFeed feed, IAmACommunityMember[] authors)
        {
            bool MatchesAuthorUrls(IAmACommunityMember author, IEnumerable <Uri> urls, SyndicationItem item)
            {
                var authorHosts       = author.FeedUris.Select(au => au.Host.ToLowerInvariant()).Concat(new[] { author.WebSite.Host.ToLowerInvariant() }).ToArray();
                var feedBurnerAuthors = author.FeedUris.Where(au => au.Host.Contains("feeds.feedburner")).ToList();
                var mediumAuthors     = author.FeedUris.Where(au => au.Host.Contains("medium.com")).ToList();
                var youtubeAuthors    = author.FeedUris.Where(au => au.Host.Contains("youtube.com")).ToList();

                foreach (var itemUrl in urls)
                {
                    var host = itemUrl.Host.ToLowerInvariant();

                    if (host.Contains("medium.com"))
                    {
                        if (itemUrl.Segments.Count() >= 3)
                        {
                            var mediumId = itemUrl.Segments[1].Trim('/');
                            return(mediumAuthors.Any(fba => fba.AbsoluteUri.Contains(mediumId)));
                        }
                    }

                    if (host.Contains("feedproxy.google"))                     //  feed burner is messed up :(
                    {
                        // url will look like:
                        // feedproxy.google.com/~r/<feedburnerId>/~3/bgJNuDXwkU0/O
                        if (itemUrl.Segments.Count() >= 5)
                        {
                            var feedBurnerId = itemUrl.Segments[2].Trim('/');
                            return(feedBurnerAuthors.Any(fba => fba.AbsoluteUri.Contains(feedBurnerId)));
                        }
                    }

                    if (host.Contains("youtube.com"))                    //need to match youtube channel
                    {
                        var channel = item?.Authors?.FirstOrDefault()?.Uri;
                        if (channel == null)
                        {
                            return(false);
                        }

                        var id = channel.Replace("https://www.youtube.com/channel/", string.Empty);

                        return(youtubeAuthors.Any(yt => yt.AbsoluteUri.Contains(id)));
                    }

                    if (authorHosts.Contains(host))
                    {
                        return(true);
                    }

                    if (authorHosts.Contains(host.Replace("www.", "")))
                    {
                        return(true);
                    }

                    if (authorHosts.Contains(host.Insert(0, "www.")))
                    {
                        return(true);
                    }
                }

                return(false);
            }

            var items = new List <PreviewModelItem>();

            foreach (var item in feed.Items)
            {
                var author = authors.FirstOrDefault(a => MatchesAuthorUrls(a, item.Links.Select(l => l.Uri), item));

                string authorName;

                if (author != null)
                {
                    authorName = $"{author.FirstName} {author.LastName}".Trim();
                }
                // If no author was matched, extract the name from the RSS feed, something is better than nothing right?!
                else
                {
                    var creator = item.ElementExtensions.FirstOrDefault(x => x.OuterName == "creator" && x.OuterNamespace == "http://purl.org/dc/elements/1.1/");
                    if (creator != null)
                    {
                        authorName = creator.GetObject <XmlElement>().Value ?? string.Empty;
                    }
                    else
                    {
                        authorName = string.Join(", ", item.Authors.Select(a => $"{a.Name} {a.Email}".Trim()));
                    }
                }

                var link = item.Links.FirstOrDefault()?.Uri.ToString() ?? string.Empty;
                var html = item.Content?.ToHtml() ?? item.Summary?.ToHtml() ?? string.Empty;

                var previewItem = new PreviewModelItem
                {
                    AuthorName  = authorName,
                    Gravatar    = author?.GravatarImage(),
                    Title       = item.Title.Text,
                    Link        = link,
                    Body        = html.Sanitize(),
                    PublishDate = item.PublishDate.Humanize()
                };

                items.Add(previewItem);
            }

            Items = items;
        }
        public static string GetArtworkUrl(this SyndicationFeed feed)
        {
            XElement imageElement = GetElement(feed, "image");

            return(GetImageUrlFromElement(imageElement));
        }
Beispiel #38
0
        /// <summary>
        /// Generate and return RSS feed.
        /// </summary>
        /// <returns></returns>
        public ActionResult Feed()
        {
            var blogTitle = ConfigurationManager.AppSettings["BlogTitle"];
            var blogDescription = ConfigurationManager.AppSettings["BlogDescription"];
            var blogUrl = ConfigurationManager.AppSettings["BlogUrl"];

            var posts = _blogRepository.Posts(0, 25).Select
            (
                p => new SyndicationItem
                    (
                        p.Title,
                        p.Description,
                        new Uri(string.Concat(blogUrl, p.Href(Url)))
                    )
            );

            var feed = new SyndicationFeed(blogTitle, blogDescription, new Uri(blogUrl), posts)
            {
                Copyright = new TextSyndicationContent(String.Format("Copyright © {0}", blogTitle)),
                Language = "en-US"
            };

            return new FeedResult(new Rss20FeedFormatter(feed));
        }
Beispiel #39
0
        SyndicationFeed GetAtomFeed(AtompubViewModel vm)
        {
            var posts = vm.Posts.ToArray();
              var feed = new SyndicationFeed() {
            Authors = { new SyndicationPerson(vm.ContactEmail, vm.ContactName, vm.ContactUrl) },
            ImageUrl = vm.ImageUrl,
            Copyright = new TextSyndicationContent(vm.CopyrightNotice),
            Description = new TextSyndicationContent(vm.About),
            Id = vm.FeedId,
            //Language = "en-us", // TODO: make this work
            LastUpdatedTime = posts.Length == 0 ? DateTime.Now : posts[0].CreationDate,
            Title = new TextSyndicationContent(vm.FeedTitle),
            Items = posts.Select(p => GetAtomItem(vm, p)),
              };

              foreach (var cat in vm.PostCategories) {
            feed.Categories.Add(new SyndicationCategory(cat.Name, vm.CategoryScheme, cat.DisplayName));
              }

              return feed;
        }