示例#1
0
        public override T ConvertToObject <T>(String xml)
        {
            StringReader        sr     = new StringReader(xml);
            XmlReader           reader = XmlReader.Create(sr);
            Atom10FeedFormatter atom   = new Atom10FeedFormatter();

            if (!atom.CanRead(reader))
            {
                throw new Exception("Mallformed Atom xml");
            }

            SyndicationFeedFormatter formatter = atom;

            formatter.ReadFrom(reader);
            SyndicationFeed feed = formatter.Feed;

            StringBuilder sb     = new StringBuilder();
            XmlWriter     writer = XmlWriter.Create(sb);
            XmlDocument   doc    = new XmlDocument();
            XmlElement    ele    = doc.CreateElement("entry");

            ele.WriteTo(writer);
            foreach (var entry in feed.Items)
            {
                SyndicationContent content = entry.Content;
                if (writer != null)
                {
                    content.WriteTo(writer, "entry", "");
                }
            }

            doc.LoadXml(sb.ToString());

            /*
             * switch (typeof(T).Name)
             * {
             *  case "Activity":
             *      return ConvertActivities(doc);
             *  case "DataCollection":
             *      return ConvertAppData(doc);
             *  case "Message":
             *      return ConvertMessages(doc);
             *  case "Person":
             *      return ConvertPeople(doc);
             * }
             * */
            throw new NotImplementedException();
            return(default(T));
        }
示例#2
0
        public virtual ActionResult Feed()
        {
            var settings = Settings.GetSettings <FunnelWebSettings>();

            var entries = Repository.Find(new GetFullEntriesQuery(entryStatus: EntryStatus.PublicBlog), 0, 20);

            var baseUri = Request.GetOriginalUrl();

            var items =
                from e in entries
                let itemUri = new Uri(baseUri, Url.Action("Page", "Wiki", new { page = e.Name }))
                              let viaFeedUri = new Uri(baseUri, "/via-feed" + Url.Action("Page", "Wiki", new { page = e.Name }))
                                               orderby e.Published descending
                                               let content = SyndicationContent.CreateHtmlContent(BuildFeedItemBody(itemUri, viaFeedUri, e))
                                                             select new
            {
                Item = new SyndicationItem
                {
                    Id              = itemUri.ToString(),
                    Title           = SyndicationContent.CreatePlaintextContent(e.Title),
                    Summary         = content,
                    Content         = content,
                    LastUpdatedTime = TimeZoneInfo.ConvertTimeFromUtc(e.Revised, TimeZoneInfo.Local),
                    PublishDate     = e.Published,
                    Links           =
                    {
                        new SyndicationLink(itemUri)
                    },
                    Authors =
                    {
                        new SyndicationPerson {
                            Name = settings.Author
                        }
                    },
                },
                Keywords = e.TagsCommaSeparated.Split(',')
            };

            return(FeedResult(items.Select(i =>
            {
                var item = i.Item;
                foreach (var k in i.Keywords)
                {
                    item.Categories.Add(new SyndicationCategory(k.Trim()));
                }

                return item;
            }).ToList()));
        }
示例#3
0
        public void TestGetLastPublishDate_withLastUpdatedTime()
        {
            SyndicationContent content = SyndicationContent.CreatePlaintextContent("Test News");

            System.Uri uri = new System.Uri("https://test.rss.feed");

            DateTimeOffset publishDate     = default(DateTimeOffset);
            DateTimeOffset lastUpdatedTime = DateTimeOffset.Now.AddDays(-7);

            SyndicationItem item = new SyndicationItem("Test Title", content, uri, "1", lastUpdatedTime);

            item.PublishDate = publishDate;

            Assert.AreEqual(lastUpdatedTime, Program.GetLastPublishDate(item));
        }
示例#4
0
        /// <summary>
        /// Creates an RSS news feed for Issues By Type
        /// </summary>
        /// <param name="feed">The feed.</param>
        private void TypeFeed(ref SyndicationFeed feed)
        {
            var al = IssueManager.GetTypeCountByProjectId(_projectId);
            var p  = ProjectManager.GetById(_projectId);

            var feedItems = CreateSyndicationItemsFromIssueCountList(al, "t");

            feed.Title =
                SyndicationContent.CreatePlaintextContent(
                    string.Format(GetLocalResourceObject("IssuesByIssueTypeTitle").ToString(), p.Name));
            feed.Description =
                SyndicationContent.CreatePlaintextContent(
                    string.Format(GetLocalResourceObject("IssuesByIssueTypeDescription").ToString(), p.Name));
            feed.Items = feedItems;
        }
示例#5
0
        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 this.GetItems(cancellationToken),
            };

            return(feed);
        }
示例#6
0
        /// <summary>
        /// Assigneds the feed.
        /// </summary>
        /// <param name="feed">The feed.</param>
        private void AssignedFeed(ref SyndicationFeed feed)
        {
            var issues    = IssueManager.GetByAssignedUserName(_projectId, User.Identity.Name);
            var p         = ProjectManager.GetById(_projectId);
            var feedItems = CreateSyndicationItemsFromIssueList(issues);

            feed.Title =
                SyndicationContent.CreatePlaintextContent(
                    string.Format(GetLocalResourceObject("AssignedIssuesTitle").ToString(), p.Name));
            feed.Description =
                SyndicationContent.CreatePlaintextContent(
                    string.Format(GetLocalResourceObject("AssignedIssuesDescription").ToString(),
                                  Security.GetDisplayName()));
            feed.Items = feedItems;
        }
        public void CreateXmlContent_XmlSerializer_ReturnsExpected(XmlSerializer serializer)
        {
            XmlSyndicationContent content = SyndicationContent.CreateXmlContent(new ExtensionObject {
                Value = 10
            }, serializer);

            Assert.Empty(content.AttributeExtensions);
            Assert.Equal("text/xml", content.Type);
            Assert.Equal(10, content.Extension.GetObject <ExtensionObject>(new XmlSerializer(typeof(ExtensionObject))).Value);
            Assert.Equal(10, content.ReadContent <ExtensionObject>().Value);
            Assert.Equal(10, content.ReadContent <ExtensionObject>(new DataContractSerializer(typeof(ExtensionObject))).Value);
            Assert.Equal(10, content.ReadContent <ExtensionObject>((XmlObjectSerializer)null).Value);
            Assert.Equal(10, content.ReadContent <ExtensionObject>(new XmlSerializer(typeof(ExtensionObject))).Value);
            Assert.Equal(10, content.ReadContent <ExtensionObject>((XmlSerializer)null).Value);
        }
 private static List<SyndicationItem> MapToSyndicationItem(IEnumerable<FeedItemViewModel> rssItems)
 {
     var results = new List<SyndicationItem>();
     foreach (var item in rssItems)
     {
         var uri = new Uri(item.Url);
         var feedItem = new SyndicationItem(item.Title.CorrectRtl(),
             SyndicationContent.CreateHtmlContent(item.Content.CorrectRtlBody()), uri, item.Url.SHA1(),
             item.LastUpdatedTime
             ) { PublishDate = item.PublishDate };
         feedItem.Authors.Add(new SyndicationPerson(item.AuthorName, item.AuthorName, uri.Host));
         results.Add(feedItem);
     }
     return results;
 }
        public SyndicationFeed CreateFeed(IPortalContext portal, HttpContext context, string selfRouteName, int maximumItems)
        {
            if (portal == null)
            {
                throw new ArgumentNullException("portal");
            }

            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            var blog = _dataAdapter.Select();

            if (blog == null)
            {
                throw new InvalidOperationException("Blog not found.");
            }

            var posts = _dataAdapter.SelectPosts(0, maximumItems).ToArray();

            var feedLastUpdatedTime = posts.Any() ? new DateTimeOffset(posts.First().PublishDate) : DateTimeOffset.UtcNow;
            var blogHtmlUri         = new Uri(context.Request.Url, blog.ApplicationPath.AbsolutePath);

            var feed = new SyndicationFeed(posts.Select(p => GetFeedItem(p, context)))
            {
                Id              = "uuid:{0};{1}".FormatWith(blog.Id, feedLastUpdatedTime.Ticks),
                Title           = SyndicationContent.CreatePlaintextContent(blog.Title),
                Description     = SyndicationContent.CreateHtmlContent(blog.Summary.ToString()),
                LastUpdatedTime = feedLastUpdatedTime,
                BaseUri         = new Uri(context.Request.Url, "/")
            };

            var selfPath = RouteTable.Routes.GetVirtualPath(context.Request.RequestContext, selfRouteName, new RouteValueDictionary
            {
                { "__portalScopeId__", portal.Website.Id },
                { "id", blog.Id }
            });

            if (selfPath != null)
            {
                feed.Links.Add(SyndicationLink.CreateSelfLink(new Uri(context.Request.Url, ApplicationPath.FromPartialPath(selfPath.VirtualPath).AbsolutePath), "application/atom+xml"));
            }

            feed.Links.Add(SyndicationLink.CreateAlternateLink(blogHtmlUri, "text/html"));

            return(feed);
        }
示例#10
0
        public static SyndicationFeed GetFeed(Node node)
        {
            var lastUpdatedTime = node.ModificationDate.ToUniversalTime();

            return(new SyndicationFeed
            {
                Title = SyndicationContent.CreatePlaintextContent(node.Name),
                Description = SyndicationContent.CreatePlaintextContent("{Feed desription}"),
                Copyright = SyndicationContent.CreatePlaintextContent("DMIS"),
                //Language = "hu-HU",
                //ImageUrl = new Uri(imageUrl),
                //Generator = "",
                LastUpdatedTime = lastUpdatedTime,
                Items = GetItems(node as IFolder)
            });
        }
        public virtual Task WriteSkipDays(IEnumerable <DayOfWeek> days)
        {
            if (days == null)
            {
                throw new ArgumentNullException(nameof(days));
            }

            var skipDays = new SyndicationContent(RssElementNames.SkipDays);

            foreach (var d in days)
            {
                skipDays.AddField(new SyndicationContent("day", Formatter.FormatValue(d)));
            }

            return(Write(skipDays));
        }
示例#12
0
        /// <summary>
        /// Gets feed for open issues.
        /// </summary>
        private void OpenIssueFeed(ref SyndicationFeed feed)
        {
            var openissueList = IssueManager.GetOpenIssues(_projectId);
            var feedItems     = CreateSyndicationItemsFromIssueList(openissueList);
            var p             = ProjectManager.GetById(_projectId);

            feed.Title =
                SyndicationContent.CreatePlaintextContent(
                    string.Format(GetLocalResourceObject("OpenIssuesTitle").ToString(), p.Name));

            feed.Description =
                SyndicationContent.CreatePlaintextContent(
                    string.Format(GetLocalResourceObject("OpenIssuesDescription").ToString(), p.Name));

            feed.Items = feedItems;
        }
示例#13
0
        private static SyndicationContent GetContent(string name, CacheItemDetail detail, CacheItemTelemetry telemetry, object value, Uri removeLink, bool expanded)
        {
            var defaultProps = new[]
            {
                new XElement("name", name),
                new XElement("type", value.GetType().ToString()),
                new XElement("remove", new XAttribute("href", removeLink))
            };

            var properties = defaultProps.Concat(GetContent(detail, telemetry)).Concat(GetContentValues(value, expanded));

            var content = new XElement("properties", properties);

            var sc = SyndicationContent.CreateXmlContent(content);

            return(sc);
        }
示例#14
0
        public FeedItem ParseFeedItem(SyndicationItem item)
        {
            FeedItem feedItem = new FeedItem();

            feedItem.Id    = item.Id;
            feedItem.Title = WebUtility.HtmlDecode(item.Title.Text);

            SyndicationContent content = item.Content ?? item.Summary;

            if (!(content is TextSyndicationContent))
            {
                feedItem.ContentText = string.Empty;
            }

            TextSyndicationContent textContent = (TextSyndicationContent)content;

            if (textContent.Type.ToLower() == "html")
            {
                HtmlDocument doc = new HtmlDocument();
                doc.LoadHtml(textContent.Text);
                feedItem.ContentText = doc.DocumentNode.InnerText;
            }
            else
            {
                try
                {
                    HtmlDocument doc = new HtmlDocument();
                    doc.LoadHtml(textContent.Text);
                    feedItem.ContentText = doc.DocumentNode.InnerText;
                }
                catch
                {
                    feedItem.ContentText = textContent.Text;
                }
            }

            feedItem.ContentText = WebUtility.HtmlDecode(feedItem.ContentText.Replace("\n", " "));

            feedItem.Tags = new List <string>();
            foreach (var cat in item.Categories)
            {
                feedItem.Tags.Add(cat.Name);
            }

            return(feedItem);
        }
示例#15
0
        /// <summary>
        /// Build the feed using the IPublishable items.
        /// </summary>
        /// <param name="feedAuthor">The author of the feed.</param>
        /// <param name="feedTitle">The title of the feed</param>
        /// <param name="feedDescription">The description of the feed.</param>
        /// <param name="feedUrl">The url of the feed</param>
        /// <param name="posts">The feed entries.</param>
        public static SyndicationFeed Build(string feedAuthor, string feedTitle, string feedDescription, string feedUrl, IList <IPublishable> posts)
        {
            Uri             feedUri = new Uri(feedUrl);
            SyndicationFeed feed    = new SyndicationFeed(feedTitle, feedDescription, feedUri, feedTitle, DateTime.Now);

            feed.Authors.Add(new SyndicationPerson(string.Empty, feedAuthor, string.Empty));
            IList <SyndicationItem> items = new List <SyndicationItem>();

            foreach (var post in posts)
            {
                SyndicationItem item = new SyndicationItem(post.Title, SyndicationContent.CreateHtmlContent(post.Description), null, post.GuidId, post.UpdateDate);
                item.Authors.Add(new SyndicationPerson(string.Empty, post.Author, string.Empty));
                items.Add(item);
            }
            feed.Items = items;
            return(feed);
        }
示例#16
0
    public static async Task WriteCustomItem()
    {
        const string ExampleNs = "http://contoso.com/syndication/feed/examples";
        var          sw        = new StringWriterWithEncoding(Encoding.UTF8);

        using (XmlWriter xmlWriter = XmlWriter.Create(sw, new XmlWriterSettings()
        {
            Async = true, Indent = true
        }))
        {
            var attributes = new List <SyndicationAttribute>()
            {
                new SyndicationAttribute("xmlns:example", ExampleNs)
            };

            var formatter = new RssFormatter(attributes, xmlWriter.Settings);
            var writer    = new RssFeedWriter(xmlWriter, attributes, formatter);

            // Create item
            var item = new SyndicationItem()
            {
                Title       = "Rss Writer Available",
                Description = "The new RSS Writer is now available as a NuGet package!",
                Id          = "https://www.nuget.org/packages/Microsoft.SyndicationFeed",
                Published   = DateTimeOffset.UtcNow
            };

            item.AddCategory(new SyndicationCategory("Technology"));
            item.AddContributor(new SyndicationPerson("test", "*****@*****.**"));

            //
            // Format the item as SyndicationContent
            var content = new SyndicationContent(formatter.CreateContent(item));

            // Add custom fields/attributes
            content.AddField(new SyndicationContent("customElement", ExampleNs, "Custom Value"));

            // Write
            await writer.Write(content);

            // Done
            xmlWriter.Flush();
        }

        Console.WriteLine(sw.ToString());
    }
示例#17
0
        public void TestGetLastPublishDate_withNoDates()
        {
            SyndicationContent content = SyndicationContent.CreatePlaintextContent("Test News");

            System.Uri uri = new System.Uri("https://test.rss.feed");

            DateTimeOffset publishDate     = default(DateTimeOffset);
            DateTimeOffset lastUpdatedTime = default(DateTimeOffset);

            SyndicationItem item = new SyndicationItem("Test Title", content, uri, "1", lastUpdatedTime);

            item.PublishDate = publishDate;

            DateTimeOffset?result = Program.GetLastPublishDate(item);

            Assert.IsNull(result);
        }
示例#18
0
        //public ActionResult TestRssFeed()
        //{
        //	var items = new List<SyndicationItem>();
        //	for (int i = 0; i < 20; i++)
        //	{
        //		var item = new SyndicationItem()
        //		{
        //			Id = Guid.NewGuid().ToString(),
        //			Title = SyndicationContent.CreatePlaintextContent(String.Format("My Title {0}", Guid.NewGuid())),
        //			Content = SyndicationContent.CreateHtmlContent("Content The stuff."),
        //			PublishDate = DateTime.Now
        //		};
        //		item.Links.Add(SyndicationLink.CreateAlternateLink(new Uri("http://www.google.com")));//Nothing alternate about it. It is the MAIN link for the item.
        //		items.Add(item);
        //	}


        //	return new RssFeed(title: "Test rss",
        //					   items: items,
        //					   contentType: "application/rss+xml",
        //					   description: String.Format("rss de test  {0}", Guid.NewGuid()));

        //}

        public ActionResult RssFeed()
        {
            var fundInvestments = InvestmentStream.GetNewFundInvestmentList();
            var news            = new List <SyndicationItem>();

            foreach (var fundInvestment in fundInvestments)
            {
                foreach (var investment in fundInvestment.Investments)
                {
                    SyndicationItem newInvestment = new SyndicationItem()
                    {
                        Title       = SyndicationContent.CreatePlaintextContent(string.Format("{0} {1} {2}", fundInvestment.Fund.Name, Constants.INVEST_IN, investment.Startup.Name)),
                        Content     = SyndicationContent.CreateHtmlContent(investment.Description),
                        PublishDate = DateTime.Parse(investment.DateActivityFeed),
                    };
                    newInvestment.Links.Add(SyndicationLink.CreateAlternateLink(new Uri(investment.Startup.Url)));
                    news.Add(newInvestment);
                }
            }

            var fundIncubations = IncubationStream.GetNewFundIncubationList();

            foreach (var fundIncubation in fundIncubations)
            {
                foreach (var incubation in fundIncubation.Incubations)
                {
                    SyndicationItem newInvestment = new SyndicationItem()
                    {
                        Title       = SyndicationContent.CreatePlaintextContent(string.Format("{0} {1} {2}", fundIncubation.Fund.Name, Constants.INCUBATE, incubation.Startup.Name)),
                        PublishDate = DateTime.Parse(incubation.DateActivityFeed),
                    };
                    newInvestment.Links.Add(SyndicationLink.CreateAlternateLink(new Uri(incubation.Startup.Url)));
                    news.Add(newInvestment);
                }
            }

            ExecutionUpdater.UpdateRss();

            Log.Info("RssFeed", "refresh new feeds");

            return(new RssFeed(title: "Angel list feed",
                               items: news,
                               contentType: "application/rss+xml",
                               description: String.Format("Thibaut Cantet Angel list  {0}", Guid.NewGuid())));
        }
示例#19
0
        public static void SaveBugReport(string title, string content)
        {
            SyndicationFeed feed = Load();

            feed.Items = new List <SyndicationItem>(feed.Items.Take(29))
            {
                new SyndicationItem()
                {
                    PublishDate = DateTime.Now,
                    Title       = new TextSyndicationContent(title),
                    Summary     = new TextSyndicationContent("bugreport"),
                    Content     = SyndicationContent.CreatePlaintextContent(content)
                }
            };

            using (XmlWriter writer = XmlWriter.Create(FILE_NAME_BUGREPORT))
                feed.SaveAsRss20(writer);
        }
示例#20
0
        private static SyndicationItem GetSyndicationItem(OrganizationServiceContext serviceContext, Entity newsItemPage)
        {
            var displayDate = newsItemPage.GetAttributeValue <DateTime?>("adx_displaydate");

            var item = new SyndicationItem(
                newsItemPage.GetAttributeValue <string>("adx_title") ?? newsItemPage.GetAttributeValue <string>("adx_name"),
                SyndicationContent.CreateHtmlContent(newsItemPage.GetAttributeValue <string>("adx_copy") ?? string.Empty),
                new Uri(new UrlBuilder(serviceContext.GetUrl(newsItemPage))),
                "uuid:{0}".FormatWith(newsItemPage.Id),
                displayDate.GetValueOrDefault(newsItemPage.GetAttributeValue <DateTime?>("modifiedon").GetValueOrDefault(DateTime.UtcNow)));

            if (displayDate != null)
            {
                item.PublishDate = displayDate.Value;
            }

            return(item);
        }
示例#21
0
        public async Task <ActionResult> GetFeed()
        {
            SyndicationFeed   feed   = new SyndicationFeed(BlogSettings.Name, BlogSettings.Description, new Uri(BaseAddress));
            SyndicationPerson author = new SyndicationPerson("", BlogSettings.Onwer, BaseAddress);

            feed.Authors.Add(author);
            Dictionary <string, SyndicationCategory> categoryMap = new Dictionary <string, SyndicationCategory>();
            {
                var cates = await BlogService.CategoryService.GetCategories(await BlogService.CategoryService.All());

                foreach (var p in cates)
                {
                    var cate = new SyndicationCategory(p.Name);
                    categoryMap.Add(p.Id, cate);
                    feed.Categories.Add(cate);
                }
            }
            {
                var posts = await BlogService.PostService.GetPosts(await BlogService.PostService.All());

                List <SyndicationItem> items = new List <SyndicationItem>();
                foreach (var p in posts)
                {
                    var s = new SyndicationItem(p.Title,
                                                SyndicationContent.CreateHtmlContent(Markdown.ToHtml(p.Content.Raw, Pipeline)),
                                                new Uri($"{BaseAddress}/posts/{p.Id}"), p.Id, p.ModificationTime);
                    s.Authors.Add(author);
                    string summary = Markdown.ToPlainText(p.Content.Raw, Pipeline);
                    s.Summary = SyndicationContent.CreatePlaintextContent(summary.Length <= 100 ? summary : summary.Substring(0, 100));
                    if (categoryMap.TryGetValue(p.CategoryId, out var cate))
                    {
                        s.Categories.Add(cate);
                    }
                    s.PublishDate = p.CreationTime;
                    items.Add(s);
                }
                feed.Items = items.AsEnumerable();
            }
            StringBuilder sb = new StringBuilder();

            using (var writer = XmlWriter.Create(sb))
                feed.GetAtom10Formatter().WriteTo(writer);
            return(Content(sb.ToString(), "text/xml"));
        }
示例#22
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);
        }
        private static SyndicationContent GetSyndicationContent(IPublication publication)
        {
            if (string.IsNullOrEmpty(publication.Content))
            {
                return(SyndicationContent.CreatePlaintextContent(string.Empty));
            }
            switch (publication.ContentType)
            {
            case PublicationContentTypes.Text:
                return(SyndicationContent.CreatePlaintextContent(publication.Content));

            case PublicationContentTypes.HTML:
                return(SyndicationContent.CreateHtmlContent(publication.Content));

            default:
                Throw.NotSupported(string.Format("{0} is not a supported content type.", publication.ContentType));
                return(null);
            }
        }
示例#24
0
        private ISyndicationContent CreateFromContentLink(ISyndicationLink link)
        {
            //
            // content
            var result = new SyndicationContent(AtomElementNames.Content);

            //
            // src
            result.AddAttribute(new SyndicationAttribute(AtomConstants.Source, FormatValue(link.Uri)));

            //
            // type
            if (!string.IsNullOrEmpty(link.MediaType))
            {
                result.AddAttribute(new SyndicationAttribute(AtomConstants.Type, link.MediaType));
            }

            return(result);
        }
        public void CreateXmlContent_Reader_NoAttributes()
        {
            XmlSyndicationContent content = SyndicationContent.CreateXmlContent(
                new XElement("ParentObject",
                             new XElement("ExtensionObject",
                                          new XElement("Value", 10)
                                          )
                             ).CreateReader()
                );

            Assert.Empty(content.AttributeExtensions);
            Assert.Equal("text/xml", content.Type);
            Assert.Null(content.Extension);
            Assert.Equal(0, content.ReadContent <ExtensionObject>().Value);
            Assert.Equal(0, content.ReadContent <ExtensionObject>(new DataContractSerializer(typeof(ExtensionObject))).Value);
            Assert.Equal(0, content.ReadContent <ExtensionObject>((XmlObjectSerializer)null).Value);
            Assert.Equal(10, content.ReadContent <ExtensionObject>(new XmlSerializer(typeof(ExtensionObject))).Value);
            Assert.Equal(10, content.ReadContent <ExtensionObject>((XmlSerializer)null).Value);
        }
示例#26
0
        public virtual ISyndicationContent CreateContent(ISyndicationPerson person)
        {
            if (person == null)
            {
                throw new ArgumentNullException(nameof(person));
            }

            if (string.IsNullOrEmpty(person.Name))
            {
                throw new ArgumentNullException("Name");
            }

            string contributorType = person.RelationshipType ?? AtomContributorTypes.Author;

            if (contributorType != AtomContributorTypes.Author &&
                contributorType != AtomContributorTypes.Contributor)
            {
                throw new ArgumentException("RelationshipType");
            }

            var result = new SyndicationContent(contributorType);

            //
            // name
            result.AddField(new SyndicationContent(AtomElementNames.Name, person.Name));

            //
            // email
            if (!string.IsNullOrEmpty(person.Email))
            {
                result.AddField(new SyndicationContent(AtomElementNames.Email, person.Email));
            }

            //
            // uri
            if (person.Uri != null)
            {
                result.AddField(new SyndicationContent(AtomElementNames.Uri, FormatValue(person.Uri)));
            }

            return(result);
        }
示例#27
0
        public async Task <IActionResult> RssAsync()
        {
            var objGeneralSettings = await _GeneralSettingsService.GetGeneralSettingsAsync();

            var feed = new SyndicationFeed(objGeneralSettings.ApplicationName, objGeneralSettings.ApplicationName, new Uri(GetBaseUrl()), "RSSUrl", DateTime.Now);

            feed.Copyright = new TextSyndicationContent($"{DateTime.Now.Year} {objGeneralSettings.ApplicationName}");
            var items = new List <SyndicationItem>();

            var postings = _BlazorBlogsContext.Blogs.OrderByDescending(x => x.BlogDate);

            foreach (var item in postings)
            {
                string BlogURL     = $"{GetBaseUrl()}/ViewBlogPost/{item.BlogId}";
                var    postUrl     = Url.Action("Article", "Blog", new { id = BlogURL }, HttpContext.Request.Scheme);
                var    title       = item.BlogTitle;
                var    description = SyndicationContent.CreateHtmlContent(item.BlogSummary.Replace("  ", " "));
                items.Add(new SyndicationItem(title, description, new Uri(BlogURL), item.BlogId.ToString(), item.BlogDate));
            }

            feed.Items = items;

            var settings = new XmlWriterSettings
            {
                Encoding            = Encoding.UTF8,
                NewLineHandling     = NewLineHandling.Entitize,
                NewLineOnAttributes = true,
                Indent = true
            };

            using (var stream = new MemoryStream())
            {
                using (var xmlWriter = XmlWriter.Create(stream, settings))
                {
                    var rssFormatter = new Rss20FeedFormatter(feed, false);
                    rssFormatter.WriteTo(xmlWriter);
                    xmlWriter.Flush();
                }

                return(File(stream.ToArray(), "application/rss+xml; charset=utf-8"));
            }
        }
示例#28
0
        private void ClosedFeed(ref SyndicationFeed feed)
        {
            var queryClauses = new List <QueryClause>();

            queryClauses.Add(new QueryClause("AND", "iv.[Disabled]", "=", "0", SqlDbType.Int));
            queryClauses.Add(new QueryClause("AND", "iv.[IsClosed]", "=", "1", SqlDbType.Int));

            var issueList = IssueManager.PerformQuery(queryClauses, null, _projectId);
            var feedItems = CreateSyndicationItemsFromIssueList(issueList);

            var p = ProjectManager.GetById(_projectId);

            feed.Title =
                SyndicationContent.CreatePlaintextContent(
                    string.Format(GetLocalResourceObject("FilteredIssuesTitle").ToString(), p.Name));
            feed.Description =
                SyndicationContent.CreatePlaintextContent(
                    string.Format(GetLocalResourceObject("FilteredIssuesDescription").ToString(), p.Name));
            feed.Items = feedItems;
        }
示例#29
0
        public static SyndicationItem Syndicate(this IPublicationMedia publicationMedia)
        {
            var item = new SyndicationItem {
                Id              = publicationMedia.Id,
                Title           = new TextSyndicationContent(publicationMedia.Title, TextSyndicationContentKind.Plaintext),
                LastUpdatedTime = publicationMedia.LastUpdated,
                Summary         = new TextSyndicationContent(publicationMedia.Summary, TextSyndicationContentKind.Plaintext),
                Content         = SyndicationContent.CreateUrlContent(publicationMedia.ImageUrl, publicationMedia.ContentType),
            };

            foreach (var link in publicationMedia.Links)
            {
                item.Links.Add(new SyndicationLink(new Uri(link.Href))
                {
                    RelationshipType = link.Rel, Title = link.Title
                });
            }

            return(item);
        }
示例#30
0
        public async Task FormatterWriterWithNamespaces()
        {
            const string ExampleNs = "http://contoso.com/syndication/feed/examples";
            var          sw        = new StringWriter();

            using (var xmlWriter = XmlWriter.Create(sw))
            {
                var attributes = new SyndicationAttribute[] { new SyndicationAttribute("xmlns:example", ExampleNs) };

                var formatter = new RssFormatter(attributes, xmlWriter.Settings);
                var writer    = new RssFeedWriter(xmlWriter, attributes, formatter);

                // Create item
                var item = new SyndicationItem()
                {
                    Title       = "Rss Writer Available",
                    Description = "The new RSS Writer is now open source!",
                    Id          = "https://github.com/dotnet/wcf/tree/lab/lab/src/Microsoft.SyndicationFeed/src",
                    Published   = DateTimeOffset.UtcNow
                };

                item.AddCategory(new SyndicationCategory("Technology"));
                item.AddContributor(new SyndicationPerson(null, "*****@*****.**"));

                //
                // Format the item as SyndicationContent
                var content = new SyndicationContent(formatter.CreateContent(item));

                // Add custom fields/attributes
                content.AddField(new SyndicationContent("customElement", ExampleNs, "Custom Value"));

                // Write
                await writer.Write(content);

                await writer.Write(content);

                await writer.Flush();
            }

            string res = sw.ToString();
        }