public static async Task WriteAddress( this ISyndicationFeedWriter writer, IOptions <ResponseOptions> responseOptions, AtomFormatter formatter, string category, AddressSyndicationQueryResult address) { var item = new SyndicationItem { Id = address.Position.ToString(CultureInfo.InvariantCulture), Title = $"{address.ChangeType}-{address.Position}", Published = address.RecordCreatedAt.ToBelgianDateTimeOffset(), LastUpdated = address.LastChangedOn.ToBelgianDateTimeOffset(), Description = BuildDescription(address, responseOptions.Value.Naamruimte) }; if (address.PersistentLocalId.HasValue) { // TODO: Hier moet prolly version nog ergens in item.AddLink( new SyndicationLink( new Uri($"{responseOptions.Value.Naamruimte}/{address.PersistentLocalId}"), AtomLinkTypes.Related)); item.AddLink( new SyndicationLink( new Uri(string.Format(responseOptions.Value.DetailUrl, address.PersistentLocalId)), AtomLinkTypes.Self)); item.AddLink( new SyndicationLink( new Uri(string.Format($"{responseOptions.Value.DetailUrl}.xml", address.PersistentLocalId)), AtomLinkTypes.Alternate) { MediaType = MediaTypeNames.Application.Xml }); item.AddLink( new SyndicationLink( new Uri(string.Format($"{responseOptions.Value.DetailUrl}.json", address.PersistentLocalId)), AtomLinkTypes.Alternate) { MediaType = MediaTypeNames.Application.Json }); } item.AddCategory( new SyndicationCategory(category)); item.AddContributor( new SyndicationPerson( "agentschap Informatie Vlaanderen", "*****@*****.**", AtomContributorTypes.Author)); await writer.Write(item); }
public static async Task WritePostalInfo( this ISyndicationFeedWriter writer, IOptions <ResponseOptions> responseOptions, AtomFormatter formatter, string category, PostalInformationSyndicationQueryResult postalInformation) { var item = new SyndicationItem { Id = postalInformation.Position.ToString(CultureInfo.InvariantCulture), Title = $"{postalInformation.ChangeType}-{postalInformation.Position}", Published = postalInformation.RecordCreatedAt.ToBelgianDateTimeOffset(), LastUpdated = postalInformation.LastChangedOn.ToBelgianDateTimeOffset(), Description = BuildDescription(postalInformation, responseOptions.Value.Naamruimte) }; if (!string.IsNullOrWhiteSpace(postalInformation.PostalCode)) { item.AddLink( new SyndicationLink( new Uri($"{responseOptions.Value.Naamruimte}/{postalInformation.PostalCode}"), AtomLinkTypes.Related)); item.AddLink( new SyndicationLink( new Uri(string.Format(responseOptions.Value.DetailUrl, postalInformation.PostalCode)), AtomLinkTypes.Self)); item.AddLink( new SyndicationLink( new Uri(string.Format($"{responseOptions.Value.DetailUrl}.xml", postalInformation.PostalCode)), AtomLinkTypes.Alternate) { MediaType = MediaTypeNames.Application.Xml }); item.AddLink( new SyndicationLink( new Uri(string.Format($"{responseOptions.Value.DetailUrl}.json", postalInformation.PostalCode)), AtomLinkTypes.Alternate) { MediaType = MediaTypeNames.Application.Json }); } item.AddCategory( new SyndicationCategory(category)); item.AddContributor( new SyndicationPerson( "agentschap Informatie Vlaanderen", "*****@*****.**", AtomContributorTypes.Author)); await writer.Write(item); }
public async Task WriteItem() { var url = new Uri("https://contoso.com/"); // // Construct item var item = new SyndicationItem() { Id = "https://contoso.com/28af09b3-86c7-4dd6-b56f-58aaa17cff62", Title = "First item on ItemWriter", Description = "Brief description of an item", Published = DateTimeOffset.UtcNow }; item.AddLink(new SyndicationLink(url)); item.AddLink(new SyndicationLink(url, RssLinkTypes.Enclosure) { Title = "https://contoso.com/", Length = 4123, MediaType = "audio/mpeg" }); item.AddLink(new SyndicationLink(url, RssLinkTypes.Comments)); item.AddLink(new SyndicationLink(url, RssLinkTypes.Source) { Title = "Anonymous Blog" }); item.AddLink(new SyndicationLink(new Uri(item.Id), RssLinkTypes.Guid)); item.AddContributor(new SyndicationPerson("John Doe", "*****@*****.**")); item.AddCategory(new SyndicationCategory("Test Category")); // // Write var sw = new StringWriterWithEncoding(Encoding.UTF8); using (var xmlWriter = XmlWriter.Create(sw)) { var writer = new RssFeedWriter(xmlWriter); await writer.Write(item); await writer.Flush(); } string res = sw.ToString(); Assert.True(res == $"<?xml version=\"1.0\" encoding=\"utf-8\"?><rss version=\"2.0\"><channel><item><title>First item on ItemWriter</title><link>{url}</link><enclosure url=\"{url}\" length=\"4123\" type=\"audio/mpeg\" /><comments>{url}</comments><source url=\"{url}\">Anonymous Blog</source><guid>{item.Id}</guid><description>Brief description of an item</description><author>[email protected] (John Doe)</author><category>Test Category</category><pubDate>{item.Published.ToRfc1123()}</pubDate></item></channel></rss>", res); }
public async Task Podcast() { Response.ContentType = "application/rss+xml"; List <SyndicationItem> items = new List <SyndicationItem>(); List <Podcast.Models.Podcast> podcasts = _dbContext.Podcasts.Where(p => p.Published).OrderByDescending(p => p.Episode).ToList(); if (podcasts != null) { foreach (Podcast.Models.Podcast podcast in podcasts) { SyndicationItem item = new SyndicationItem() { Id = podcast.Episode.ToString(), Title = podcast.Title, Description = MarkdownHelper.Markdown(podcast.Description).Value, Published = podcast.DatePublished }; item.AddLink(new SyndicationLink(new Uri(Url.SubRouteUrl("podcast", "Podcast.View", new { episode = podcast.Episode })))); foreach (Podcast.Models.PodcastFile file in podcast.Files) { SyndicationLink enclosure = new SyndicationLink(new Uri(Url.SubRouteUrl("podcast", "Podcast.Download", new { episode = podcast.Episode, fileName = file.FileName }))); item.AddLink(enclosure); } items.Add(item); } } using (var xmlWriter = CreateXmlWriter()) { var feedWriter = new RssFeedWriter(xmlWriter); await feedWriter.WriteTitle(_config.PodcastConfig.Title); await feedWriter.WriteDescription(_config.PodcastConfig.Description); await feedWriter.Write(new SyndicationLink(new Uri(Url.SubRouteUrl("podcast", "Podcast.Index")))); foreach (SyndicationItem item in items) { await feedWriter.Write(item); } await xmlWriter.FlushAsync(); } }
private static IEnumerable <SyndicationItem> GetItemCollection(IEnumerable <FeedEntry> itemCollection) { var synItemCollection = new List <SyndicationItem>(); foreach (var item in itemCollection) { // create rss item var sItem = new SyndicationItem { Id = item.Id, Title = item.Title, Description = item.Description, LastUpdated = item.PubDateUtc.ToUniversalTime(), Published = item.PubDateUtc.ToUniversalTime() }; sItem.AddLink(new SyndicationLink(new Uri(item.Link))); // add author if (!string.IsNullOrWhiteSpace(item.Author) && !string.IsNullOrWhiteSpace(item.AuthorEmail)) { sItem.AddContributor(new SyndicationPerson(item.Author, item.AuthorEmail)); } // add categories if (item.Categories is not null and { Length: > 0 })
public async Task StatusFeed() { var item = new SyndicationItem { Title = "status" }; item.AddLink(new SyndicationLink(new Uri("http://www.w3.org/2005/Atom"))); using (var writer = new StringWriter()) { using (var xmlWriter = XmlWriter.Create(writer, new XmlWriterSettings() { Async = true, Indent = true, Encoding = Encoding.UTF8 })) { var rssWriter = new RssFeedWriter(xmlWriter); await rssWriter.WriteTitle("This is the title"); await rssWriter.WriteDescription("description"); await rssWriter.Write(item); } var text = writer.ToString(); } }
private IEnumerable <SyndicationItem> getSyndicationItems() { foreach (var item in _feedChannel.RssItems) { var uri = new Uri(QueryHelpers.AddQueryString(item.Url, new Dictionary <string, string> { { "utm_source", "feed" }, { "utm_medium", "rss" }, { "utm_campaign", "featured" }, { "utm_updated", getUpdatedStamp(item) } })); var syndicationItem = new SyndicationItem { Title = item.Title.ApplyRle().RemoveHexadecimalSymbols(), Id = uri.ToString(), Description = item.Content.WrapInDirectionalDiv().RemoveHexadecimalSymbols(), Published = item.PublishDate, LastUpdated = item.LastUpdatedTime }; syndicationItem.AddLink(new SyndicationLink(uri)); syndicationItem.AddContributor(new SyndicationPerson(item.AuthorName, item.AuthorName)); foreach (var category in item.Categories) { syndicationItem.AddCategory(new SyndicationCategory(category)); } yield return(syndicationItem); } }
public static ISyndicationItem ToSyndicationItem(this RSSItem rssItem) { if (rssItem == null) { throw new ArgumentException(nameof(rssItem)); } //Should probably have an item title if (string.IsNullOrEmpty(rssItem.Title)) { throw new ArgumentNullException(nameof(rssItem.Title)); } //And some content if (string.IsNullOrEmpty(rssItem.Content)) { throw new ArgumentNullException(nameof(rssItem.Content)); } var syndicationItem = new SyndicationItem { Title = rssItem.Title, Description = rssItem.Content }; if (rssItem.PermaLink != null) { syndicationItem.AddLink(new SyndicationLink(rssItem.PermaLink, RssLinkTypes.Guid)); } if (rssItem.LinkUri != null) { syndicationItem.AddLink(new SyndicationLink(rssItem.LinkUri)); } if (rssItem.CommentsUri != null) { syndicationItem.AddLink(new SyndicationLink(rssItem.CommentsUri, RssLinkTypes.Comments)); } rssItem.Authors.ForEach(author => syndicationItem.AddContributor(new SyndicationPerson(null, author))); rssItem.Categories.ForEach(category => syndicationItem.AddCategory(new SyndicationCategory(category))); syndicationItem.Published = rssItem.PublishDate; return(syndicationItem); }
private void SaveItem(Uri feedUri, string title, DateTimeOffset publicationDate, Uri link) { var item = new SyndicationItem() { Title = title, Published = publicationDate }; item.AddLink(new SyndicationLink(link)); _repository.Save(item, string.Empty, feedUri); }
public static async Task WriteMunicipality( this ISyndicationFeedWriter writer, IOptions <ResponseOptions> responseOptions, AtomFormatter formatter, string category, MunicipalitySyndicationQueryResult municipality) { var item = new SyndicationItem { Id = municipality.Position.ToString(CultureInfo.InvariantCulture), Title = $"{municipality.ChangeType}-{municipality.Position}", Published = municipality.RecordCreatedAt.ToBelgianDateTimeOffset(), LastUpdated = municipality.LastChangedOn.ToBelgianDateTimeOffset(), Description = BuildDescription(municipality, responseOptions.Value.Naamruimte) }; if (!string.IsNullOrWhiteSpace(municipality.NisCode)) { item.AddLink( new SyndicationLink( new Uri($"{responseOptions.Value.Naamruimte}/{municipality.NisCode}"), AtomLinkTypes.Related)); //item.AddLink( // new SyndicationLink( // new Uri(string.Format(responseOptions.Value.DetailUrl, municipality.NisCode)), // AtomLinkTypes.Self)); //item.AddLink( // new SyndicationLink( // new Uri(string.Format($"{responseOptions.Value.DetailUrl}.xml", municipality.NisCode)), // AtomLinkTypes.Alternate) // { MediaType = MediaTypeNames.Application.Xml }); //item.AddLink( // new SyndicationLink( // new Uri(string.Format($"{responseOptions.Value.DetailUrl}.json", municipality.NisCode)), // AtomLinkTypes.Alternate) // { MediaType = MediaTypeNames.Application.Json }); } item.AddCategory( new SyndicationCategory(category)); item.AddContributor( new SyndicationPerson( municipality.Organisation == null ? Organisation.Unknown.ToName() : municipality.Organisation.Value.ToName(), string.Empty, AtomContributorTypes.Author)); await writer.Write(item); }
public static async Task WriteAddress( this ISyndicationFeedWriter writer, IOptions <ResponseOptions> responseOptions, AtomFormatter formatter, string category, AddressSyndicationQueryResult address) { var item = new SyndicationItem { Id = address.Position.ToString(CultureInfo.InvariantCulture), Title = $"{address.ChangeType}-{address.Position}", Published = address.RecordCreatedAt.ToBelgianDateTimeOffset(), LastUpdated = address.LastChangedOn.ToBelgianDateTimeOffset(), Description = BuildDescription(address, responseOptions.Value.Naamruimte) }; if (address.PersistentLocalId.HasValue) { item.AddLink( new SyndicationLink( new Uri($"{responseOptions.Value.Naamruimte}/{address.PersistentLocalId}"), AtomLinkTypes.Related)); //item.AddLink( // new SyndicationLink( // new Uri(string.Format(responseOptions.Value.DetailUrl, address.PersistentLocalId)), // AtomLinkTypes.Self)); //item.AddLink( // new SyndicationLink( // new Uri(string.Format($"{responseOptions.Value.DetailUrl}.xml", address.PersistentLocalId)), AtomLinkTypes.Alternate) // { MediaType = MediaTypeNames.Application.Xml }); //item.AddLink( // new SyndicationLink( // new Uri(string.Format($"{responseOptions.Value.DetailUrl}.json", // address.PersistentLocalId)), // AtomLinkTypes.Alternate) // { MediaType = MediaTypeNames.Application.Json }); } item.AddCategory( new SyndicationCategory(category)); item.AddContributor( new SyndicationPerson( address.Organisation == null ? Organisation.Unknown.ToName() : address.Organisation.Value.ToName(), string.Empty, AtomContributorTypes.Author)); await writer.Write(item); }
public virtual ActionResult Feed(string feedType, int feedCount = PageSizes.NewsFeed) { FeedType ft; if (!Enum.TryParse(feedType, true, out ft)) { throw new ArgumentException("Unknown feed type"); } if (feedCount <= 0) { throw new ArgumentException("Invalid feed count"); } var items = new List <SyndicationItem>(); var client = GetNewsClient(); { var feeds = client.GetNewsSyndicationItems(0, feedCount, NewsTypeEnumContract.Web, PortalTypeValue); foreach (var feed in feeds.List) { var syndicationItem = new SyndicationItem { Id = feed.Id.ToString(), Title = feed.Title, Description = feed.Text, Published = feed.CreateTime, LastUpdated = feed.CreateTime, }; var person = new SyndicationPerson($"{feed.CreatedByUser.FirstName} {feed.CreatedByUser.LastName}", feed.CreatedByUser.Email); var url = new SyndicationLink(new Uri(feed.Url)); syndicationItem.AddContributor(person); syndicationItem.AddLink(url); items.Add(syndicationItem); } } var requestUrl = new Uri(Request.GetDisplayUrl()); switch (ft) { case FeedType.Rss: return(new RssResult("Vokabular feed", items, requestUrl)); default: return(new AtomResult("Vokabular feed", items, requestUrl)); } }
public static ISyndicationItem ToSyndicationItem(this RSSItem rssItem) { if (rssItem == null) { throw new ArgumentException(nameof(rssItem)); } var syndicationItem = new SyndicationItem { Title = rssItem.Title, Description = rssItem.Content }; if (rssItem.PermaLink != null) { syndicationItem.AddLink(new SyndicationLink(rssItem.PermaLink, RssLinkTypes.Guid)); } if (rssItem.LinkUri != null) { syndicationItem.AddLink(new SyndicationLink(rssItem.LinkUri)); } if (rssItem.CommentsUri != null) { syndicationItem.AddLink(new SyndicationLink(rssItem.CommentsUri, RssLinkTypes.Comments)); } if (rssItem.Authors != null) { rssItem.Authors.ForEach(author => syndicationItem.AddContributor(new SyndicationPerson(null, author))); } if (rssItem.Categories != null) { rssItem.Categories.ForEach(category => syndicationItem.AddCategory(new SyndicationCategory(category))); } syndicationItem.Published = rssItem.PublishDate; return(syndicationItem); }
private static SyndicationItem ToSyndicationItem(this Page p) { var post = new SyndicationItem { Id = p.FullURL, Title = p.Title, Description = p.Description, Published = p.Timestamp.ToLocalTime(), LastUpdated = p.Timestamp.ToLocalTime() }; post.AddLink(new SyndicationLink(new Uri(p.FullURL))); post.AddContributor(new SyndicationPerson(Settings.Title, Settings.EmailFromAndTo)); return(post); }
private async Task <string> FormatGamerskyFeed(IEnumerable <GamerskyEntry> entries) { var sw = new StringWriterWithEncoding(Encoding.UTF8); using (XmlWriter xmlWriter = XmlWriter.Create(sw, new XmlWriterSettings() { Async = true, Indent = true })) { var writer = new RssFeedWriter(xmlWriter); await writer.WriteTitle("Gamersky RSS feed"); await writer.WriteDescription("Gamersky RSS feed"); await writer.Write(new SyndicationLink(new Uri("https://www.gamersky.com/"))); await writer.WritePubDate(DateTimeOffset.UtcNow); foreach (var e in entries) { try { var item = new SyndicationItem() { Id = e.Link, Title = e.Title, Published = e.PubDate, Description = e.Content, }; item.AddLink(new SyndicationLink(new Uri(e.Link))); await writer.Write(item); } catch (Exception ex) { Console.WriteLine($"Issue happens during generating rss for {e.Link}"); Console.WriteLine(e.Title); Console.WriteLine(e.Content); Console.WriteLine(e.PubDate); Console.WriteLine(ex.ToString()); } } xmlWriter.Flush(); } return(sw.ToString()); }
static void WriteRss(IEnumerable <dynamic> items) { var streamWritter = File.CreateText($"../{FeedPath}"); using (var xmlWriter = XmlWriter.Create(streamWritter, new XmlWriterSettings { Indent = true })) { var writer = new RssFeedWriter(xmlWriter); writer.WriteTitle(FullName); writer.WriteDescription(FeedDescription); writer.WriteValue("link", Link); var markdown = new Markdown(); foreach (var item in items) { var itemPath = string.Format(ItemFilenamePathFormat, item.MarkdownFilename); var markdownText = File.ReadAllText($"../{itemPath}"); var permalink = $"{Link}/#/{item.MarkdownFilename}"; var syndicationItem = new SyndicationItem { Title = item.Title, Description = markdown.Transform(markdownText), Published = item.Date }; syndicationItem.AddContributor(new SyndicationPerson(FullName, $"{Email} ({FullName})")); syndicationItem.AddLink(new SyndicationLink(new Uri(permalink), "guid")); string category = item.Category; if (!string.IsNullOrWhiteSpace(category)) { syndicationItem.AddCategory(new SyndicationCategory(category)); } writer.Write(syndicationItem); } xmlWriter.Flush(); } }
private IList <SyndicationItem> GetFeed() { IList <SyndicationItem> result = new List <SyndicationItem>(); foreach (var post in _blogPostsConfig.Blogs.Where(x => x.Published)) { var item = new SyndicationItem() { Title = post.Title, Description = post.Description, Id = post.Slug, Published = post.CreateDate.Date, LastUpdated = post.CreateDate.Date }; post.Categories.ForEach(x => item.AddCategory(new SyndicationCategory(x))); item.AddLink(new SyndicationLink(new System.Uri(_siteSettings.SiteURL + "/" + post.UrlTail))); item.AddContributor(new SyndicationPerson(post.Author, _siteSettings.Email)); result.Add(item); } return(result); }
private static IEnumerable <SyndicationItem> GetSyndicationItemCollection(IEnumerable <SimpleFeedItem> itemCollection) { var synItemCollection = new List <SyndicationItem>(); foreach (var item in itemCollection) { // create rss item var sItem = new SyndicationItem { Id = item.Id, Title = item.Title, Description = item.Description, LastUpdated = item.PubDateUtc.ToUniversalTime(), Published = item.PubDateUtc.ToUniversalTime() }; sItem.AddLink(new SyndicationLink(new Uri(item.Link))); // add author if (!string.IsNullOrWhiteSpace(item.Author) && !string.IsNullOrWhiteSpace(item.AuthorEmail)) { sItem.AddContributor(new SyndicationPerson(item.Author, item.AuthorEmail)); } // add categories if (null != item.Categories && item.Categories.Any()) { foreach (var itemCategory in item.Categories) { sItem.AddCategory(new SyndicationCategory(itemCategory)); } } synItemCollection.Add(sItem); } return(synItemCollection); }
public async Task <ActionResult> Feed() { var entries = await this.unitOfWork.BlogEntries .Include(b => b.Author) .Include(b => b.Tags) .ThenInclude(t => t.Tag) .AsNoTracking() .Where(b => b.Visible && b.PublishDate <= DateTimeOffset.UtcNow) .OrderByDescending(b => b.PublishDate) .ToListAsync(); string baseUrl = $"{this.Request.Scheme}://{this.Request.Host}{this.Request.PathBase}"; using (var sw = new StringWriterWithEncoding(Encoding.UTF8)) { using (XmlWriter xmlWriter = XmlWriter.Create(sw, new XmlWriterSettings() { Async = true, Indent = true })) { var writer = new RssFeedWriter(xmlWriter); await writer.WriteTitle(this.blogSettings.BlogName); await writer.WriteDescription(this.blogSettings.BlogDescription); await writer.Write(new SyndicationLink(new Uri(baseUrl))); await writer.WriteRaw($"<atom:link href=\"{baseUrl}/Blog/{nameof(this.Feed)}\" rel=\"self\" type=\"application/rss+xml\" xmlns:atom=\"http://www.w3.org/2005/Atom\" />"); await writer.Write(new SyndicationImage(new Uri($"{baseUrl}/apple-touch-icon_192.png")) { Title = this.blogSettings.BlogName, Description = this.blogSettings.BlogDescription, Link = new SyndicationLink(new Uri(baseUrl)) }); if (entries.Count > 0) { await writer.WritePubDate(entries[0].PublishDate); } var pipeline = new MarkdownPipelineBuilder() .UseAdvancedExtensions() .Build(); foreach (var blogEntry in entries) { var syndicationItem = new SyndicationItem() { Id = blogEntry.Id.ToString(), Title = blogEntry.Header, Published = blogEntry.PublishDate, LastUpdated = blogEntry.PublishDate > blogEntry.UpdateDate ? blogEntry.PublishDate : blogEntry.UpdateDate, Description = $"{Markdown.ToHtml(blogEntry.ShortContent, pipeline)}{Markdown.ToHtml(blogEntry.Content, pipeline)}" }; syndicationItem.AddLink(new SyndicationLink(new Uri($"{baseUrl}/Blog/{blogEntry.Url}"))); syndicationItem.AddContributor(new SyndicationPerson(blogEntry.Author.UserName, blogEntry.Author.Email)); foreach (var tag in blogEntry.Tags) { syndicationItem.AddCategory(new SyndicationCategory(tag.Tag.Name)); } await writer.Write(syndicationItem); } xmlWriter.Flush(); } return(this.Content(sw.ToString(), "application/rss+xml")); } }
/// <summary> /// Returns the rss xml string for the blog or a blog category. The result is cached for 1 hour. /// The rss feed always returns first page with 10 results. /// </summary> /// <param name="cat"></param> /// <returns></returns> private async Task <string> GetFeed(Category cat = null) { var key = cat == null ? "RssFeed" : $"RssFeed_{cat.Slug}"; return(await _cache.GetAsync(key, new TimeSpan(1, 0, 0), async() => { var sw = new StringWriter(); using (XmlWriter xmlWriter = XmlWriter.Create(sw, new XmlWriterSettings() { Async = true, Indent = true })) { var postList = cat == null ? await _blogSvc.GetPostsAsync(1, 10) : await _blogSvc.GetPostsForCategoryAsync(cat.Slug, 1); var coreSettings = await _settingSvc.GetSettingsAsync <CoreSettings>(); var blogSettings = await _settingSvc.GetSettingsAsync <BlogSettings>(); var vm = new BlogPostListViewModel(postList, blogSettings, Request); var channelTitle = cat == null ? "Fanray" : $"{cat.Title} - Fanray"; var channelDescription = coreSettings.Tagline; var channelLink = $"{Request.Scheme}://{Request.Host}"; var channelLastPubDate = postList.Posts.Count <= 0 ? DateTimeOffset.UtcNow : postList.Posts[0].CreatedOn; var writer = new RssFeedWriter(xmlWriter); await writer.WriteTitle(channelTitle); await writer.WriteDescription(channelDescription); await writer.Write(new SyndicationLink(new Uri(channelLink))); await writer.WritePubDate(channelLastPubDate); await writer.WriteGenerator("https://www.fanray.com"); foreach (var postVM in vm.BlogPostViewModels) { var post = postVM; var item = new SyndicationItem() { Id = postVM.Permalink, // guid https://www.w3schools.com/xml/rss_tag_guid.asp Title = post.Title, Description = blogSettings.FeedShowExcerpt ? post.Excerpt : post.Body, Published = post.CreatedOn, }; // link to the post item.AddLink(new SyndicationLink(new Uri(postVM.CanonicalUrl))); // category takes in both cats and tags item.AddCategory(new SyndicationCategory(post.Category.Title)); foreach (var tag in post.Tags) { item.AddCategory(new SyndicationCategory(tag.Title)); } // https://www.w3schools.com/xml/rss_tag_author.asp // the author tag exposes email //item.AddContributor(new SyndicationPerson(post.User.DisplayName, post.User.Email)); await writer.Write(item); } xmlWriter.Flush(); } return sw.ToString(); })); }
public async Task Blog(string username) { Response.ContentType = "application/rss+xml"; // If empty, grab the main blog List <BlogPost> posts = new List <BlogPost>(); string blogUrl = Url.SubRouteUrl("blog", "Blog.Blog"); string title = string.Empty; string description = string.Empty; bool isSystem = string.IsNullOrEmpty(username); bool userExists = false; if (isSystem) { posts = _dbContext.BlogPosts.Where(p => (p.System && p.Published)).ToList(); blogUrl = Url.SubRouteUrl("blog", "Blog.Blog"); } else { Blog.Models.Blog blog = _dbContext.Blogs.Where(p => p.User.Username == username && p.BlogId != _config.BlogConfig.ServerBlogId).FirstOrDefault(); posts = _dbContext.BlogPosts.Where(p => (p.BlogId == blog.BlogId && !p.System) && p.Published).ToList(); blogUrl = Url.SubRouteUrl("blog", "Blog.Blog", new { username = username }); } if (posts.Any()) { if (isSystem) { userExists = true; title = _config.BlogConfig.Title; description = _config.BlogConfig.Description; } else { Users.Models.User user = UserHelper.GetUser(_dbContext, username); if (user != null) { userExists = true; title = user.BlogSettings.Title; description = user.BlogSettings.Description; } else { userExists = false; title = "No Blog Available"; description = "The specified user does not exist"; } } List <SyndicationItem> items = new List <SyndicationItem>(); if (userExists) { foreach (BlogPost post in posts.OrderByDescending(p => p.BlogPostId)) { if (post.Published && post.System == isSystem) { SyndicationItem item = new SyndicationItem() { Id = post.BlogPostId.ToString(), Title = post.Title, Description = MarkdownHelper.Markdown(post.Article).Value, Published = post.DatePublished }; item.AddLink(new SyndicationLink(new Uri(Url.SubRouteUrl("blog", "Blog.Post", new { username = post.Blog.User.Username, id = post.BlogPostId })))); item.AddContributor(new SyndicationPerson(post.Blog.User.Username, UserHelper.GetUserEmailAddress(_config, post.Blog.User.Username))); items.Add(item); } } } using (var xmlWriter = CreateXmlWriter()) { var feedWriter = new RssFeedWriter(xmlWriter); await feedWriter.WriteTitle(title); await feedWriter.WriteDescription(description); await feedWriter.Write(new SyndicationLink(new Uri(blogUrl))); foreach (SyndicationItem item in items) { await feedWriter.Write(item); } await xmlWriter.FlushAsync(); } } else { using (var xmlWriter = CreateXmlWriter()) { var feedWriter = new RssFeedWriter(xmlWriter); await feedWriter.WriteTitle("No Blog Available"); await feedWriter.WriteDescription("The specified blog does not exist"); await feedWriter.Write(new SyndicationLink(new Uri(blogUrl))); await xmlWriter.FlushAsync(); } } }
public async static Task <string> GetFeedAsync(IEnumerable <Post> posts) { var sw = new StringWriterWithEncoding(Encoding.UTF8); const string ExampleNs = "https://feed.lucasteles.net"; using (var xmlWriter = XmlWriter.Create(sw, new XmlWriterSettings { Async = true, Indent = true })) { var attributes = new List <SyndicationAttribute> { new SyndicationAttribute("xmlns:feed", ExampleNs) }; var formatter = new RssFormatter(attributes, xmlWriter.Settings); var writer = new RssFeedWriter(xmlWriter, null, new RssFormatter() { UseCDATA = true }); // // Add Title await writer.WriteTitle("Lucas Teles - Blog"); // // Add Description await writer.WriteDescription("Tecnologia e inovação"); // // Add Link await writer.Write(new SyndicationLink(new Uri("https://lucasteles.net"))); // // Add managing editor await writer.Write(new SyndicationPerson("lucasteles", "*****@*****.**", RssContributorTypes.ManagingEditor)); // // Add publish date await writer.WritePubDate(DateTimeOffset.UtcNow); // // Add Items foreach (var post in posts) { var item = new SyndicationItem { Id = $"https://lucasteles.net/p={post.Id}", Title = post.Title, Description = post.Description, Published = post.Date, }; item.AddLink(new SyndicationLink(new Uri($"https://lucasteles.net/{post.Path}"))); item.AddCategory(new SyndicationCategory("Technology")); item.AddContributor(new SyndicationPerson("Lucas Teles", "*****@*****.**")); // Format the item as SyndicationContent var content = new SyndicationContent(formatter.CreateContent(item)); content.AddField(new SyndicationContent("content:encoded", string.Empty, post.Content)); // Write await writer.Write(content); } // // Done xmlWriter.Flush(); } return(sw.ToString()); }
public static async Task WriteFeed() { var sw = new StringWriterWithEncoding(Encoding.UTF8); using (XmlWriter xmlWriter = XmlWriter.Create(sw, new XmlWriterSettings() { Async = true, Indent = true })) { var writer = new RssFeedWriter(xmlWriter); // // Add Title await writer.WriteTitle("Example of RssFeedWriter"); // // Add Description await writer.WriteDescription("Hello World, RSS 2.0!"); // // Add Link await writer.Write(new SyndicationLink(new Uri("https://github.com/dotnet/SyndicationFeedReaderWriter"))); // // Add managing editor await writer.Write(new SyndicationPerson("managingeditor", "*****@*****.**", RssContributorTypes.ManagingEditor)); // // Add publish date await writer.WritePubDate(DateTimeOffset.UtcNow); // // Add custom element var customElement = new SyndicationContent("customElement"); customElement.AddAttribute(new SyndicationAttribute("attr1", "true")); customElement.AddField(new SyndicationContent("Company", "Contoso")); await writer.Write(customElement); // // Add Items for (int i = 0; i < 5; ++i) { var item = new SyndicationItem() { Id = "https://www.nuget.org/packages/Microsoft.SyndicationFeed.ReaderWriter", Title = $"Item #{i + 1}", Description = "The new Microsoft.SyndicationFeed.ReaderWriter is now available as a NuGet package!", Published = DateTimeOffset.UtcNow }; item.AddLink(new SyndicationLink(new Uri("https://github.com/dotnet/SyndicationFeedReaderWriter"))); item.AddCategory(new SyndicationCategory("Technology")); item.AddContributor(new SyndicationPerson("user", "*****@*****.**")); await writer.Write(item); } // // Done xmlWriter.Flush(); } // // Ouput the feed Console.WriteLine(sw.ToString()); }
public async Task Get(int id) { try { var series = await new Bonanza(_httpClient).GetSeries(id); Response.ContentType = "application/rss+xml"; using (var xmlWriter = XmlWriter.Create(Response.Body, new XmlWriterSettings() { Async = true, Encoding = Encoding.UTF8 })) { var attributes = new List <SyndicationAttribute>() { new SyndicationAttribute("xmlns:itunes", _itunesNs), }; var formatter = new RssFormatter(attributes, xmlWriter.Settings); var feedWriter = new RssFeedWriter(xmlWriter, attributes, formatter); await WriteFeedPreamble(feedWriter); await feedWriter.WriteTitle(series.Title); await feedWriter.Write(new SyndicationContent("subtitle", _itunesNs, series.SubTitle)); await feedWriter.Write(new SyndicationLink(new Uri(series.Url))); await feedWriter.Write(new SyndicationContent("author", _itunesNs, series.Author)); await feedWriter.Write(new SyndicationContent("summary", _itunesNs, series.Description)); foreach (var x in series.Episodes.OrderBy(x => x.Published) .Select((value, i) => new { i, value })) { var episode = x.value; var item = new SyndicationItem { Title = episode.Title, Description = episode.Description, Published = episode.Published, Id = $"{episode.WebUri}", }; item.AddLink(new SyndicationLink(episode.MediaUri, RssLinkTypes.Enclosure) { MediaType = episode.MediaType, Length = episode.FileLength, }); item.AddLink(new SyndicationLink(episode.WebUri)); var content = new SyndicationContent(formatter.CreateContent(item)); content.AddField(new SyndicationContent("summary", _itunesNs, episode.Description)); content.AddField(new SyndicationContent("author", _itunesNs, string.Join(", ", episode.Authors))); content.AddField(new SyndicationContent("duration", _itunesNs, episode.Duration.ToString(@"hh\:mm\:ss"))); content.AddField(new SyndicationContent("explicit", _itunesNs, "no")); content.AddField(new SyndicationContent("episode", _itunesNs, $"{x.i + 1}")); content.AddField(new SyndicationContent("language", _itunesNs, $"{_daCulture}")); await feedWriter.Write(content); } } } catch (SeriesNotFoundException) { Response.StatusCode = 404; return; } }
public async Task <IActionResult> GetRssAsync() { var result = await Mediator.Send(new GetMaterialListQuery.Request { CurrentPage = 1, PageSize = 10 }); var host = Request.Scheme + "://" + Request.Host + "/"; var sw = new StringWriter(); var settings = new XmlWriterSettings { Async = true, Indent = true }; using (var xmlWriter = XmlWriter.Create(sw, settings)) { var attributes = new List <SyndicationAttribute> { new SyndicationAttribute("xmlns:link", host) }; var writer = new RssFeedWriter(xmlWriter); await writer.WriteTitle("MyLFC.ru - новостная лента"); var formatter = new RssFormatter(attributes, xmlWriter.Settings); foreach (var material in result.Results) { var item = new SyndicationItem { Title = material.Title, Description = $"<img src='{material.PhotoPreview}' /><br/>{material.Brief}", Id = material.Id.ToString(), Published = material.AdditionTime, LastUpdated = material.AdditionTime, }; item.AddCategory(new SyndicationCategory(material.CategoryName)); item.AddContributor(new SyndicationPerson(material.UserName, material.UserName)); item.AddLink(new SyndicationLink(new Uri(host + material.TypeName + "/" + material.Id))); //item.AddLink(new SyndicationLink(new Uri(host + material.TypeName + "/" + material.Id))); // Format the item as SyndicationContent var content = new SyndicationContent(formatter.CreateContent(item)); // Add custom fields/attributes //content.AddAttribute(new SyndicationAttribute("img", host + material.Photo)); //content.AddField(new SyndicationContent("customElement", "321321", "Custom Value")); await writer.Write(content); } xmlWriter.Flush(); } var xml = new XmlDocument(); xml.LoadXml(sw.ToString()); return(Content(xml.InnerXml, "application/xml")); // return Ok(xml.InnerXml); }
public async Task ShouldGenerateBlogRss() { var projectInfo = this.TestContext.ShouldGetProjectDirectoryInfo(this.GetType()); #region test properties: var blobContainerName = this.TestContext.Properties["blobContainerName"].ToString(); var blobContainerNameClassic = this.TestContext.Properties["blobContainerNameClassic"].ToString(); var rssPath = this.TestContext.Properties["rssPath"].ToString(); rssPath = projectInfo.ToCombinedPath(rssPath); this.TestContext.ShouldFindFile(rssPath); #endregion var containerClassic = cloudStorageAccountClassic.CreateCloudBlobClient().GetContainerReference(blobContainerNameClassic); var keys = new AzureBlobKeys(); keys.Add <BlogEntry>(i => i.Slug); var repository = new BlogRepository(keys, containerClassic); var data = await(repository as IBlogEntryIndex).GetIndexAsync(); Assert.IsTrue(data.Any(), "The expected data are not here."); var feed = data .OrderByDescending(i => i.InceptDate) .Take(10); var builder = new StringBuilder(); var settings = new XmlWriterSettings { Async = true, CloseOutput = true, Encoding = Encoding.UTF8, Indent = true, OmitXmlDeclaration = true }; var person = new SyndicationPerson("Bryan Wilhite", "*****@*****.**"); using (var writer = XmlWriter.Create(builder, settings)) { var feedWriter = new RssFeedWriter(writer); await feedWriter.WritePubDate(DateTime.Now); await feedWriter.WriteTitle($">DayPath_"); await feedWriter.WriteDescription($"The technical journey of @BryanWilhite."); await feedWriter.WriteCopyright($"Bryan Wilhite, Songhay System {DateTime.Now.Year}"); await feedWriter.Write(new SyndicationLink(new Uri("http://songhayblog.azurewebsites.net", UriKind.Absolute))); var tasks = feed.Select(async entry => { var item = new SyndicationItem { Description = entry.Content, Id = entry.Slug, LastUpdated = entry.ModificationDate, Published = entry.InceptDate, Title = entry.Title }; item.AddContributor(person); item.AddLink(new SyndicationLink(new Uri($"http://songhayblog.azurewebsites.net/blog/entry/{entry.Slug}", UriKind.Absolute))); await feedWriter.Write(item); }); await Task.WhenAll(tasks); await writer.FlushAsync(); } File.WriteAllText(rssPath, builder.ToString()); var container = cloudStorageAccount.CreateCloudBlobClient().GetContainerReference(blobContainerName); await container.UploadBlobAsync(rssPath, string.Empty); }
private async Task <string> GetSyndicationItems(string id) { // See if we already have the items in the cache if (_cache.TryGetValue($"{id}_items", out string s)) { Log.Information("CACHE HIT: Returning {bytes} bytes", s.Length); return(s); } Log.Information("CACHE MISS: Loading feed items for {id}", id); var sb = new StringBuilder(); var stringWriter = new StringWriterWithEncoding(sb, Encoding.UTF8); int days = 5; var feed = GetFeed(id); using (XmlWriter xmlWriter = XmlWriter.Create(stringWriter, new XmlWriterSettings() { Async = true, Indent = true, Encoding = Encoding.UTF8 })) { var rssWriter = new AtomFeedWriter(xmlWriter); await rssWriter.WriteTitle(feed.title); await rssWriter.Write(new SyndicationLink(new Uri(feed.url))); await rssWriter.WriteUpdated(DateTimeOffset.UtcNow); // Add Items foreach (var item in await GetFeedItems(id.ToLowerInvariant(), days)) { try { var si = new SyndicationItem() { Id = item.Id, Title = item.Title.Replace("\u0008", "").Replace("\u0003", "").Replace("\u0010", "").Replace("\u0012", "").Replace("\u0002", "").Replace("\u001f", ""), Description = item.ArticleText.Replace("\u0008", "").Replace("\u0003", "").Replace("\u0010", "").Replace("\u0012", "").Replace("\u0002", "").Replace("\u001f", ""), Published = item.DateAdded, LastUpdated = item.DateAdded }; si.AddLink(new SyndicationLink(new Uri(item.Url))); si.AddContributor(new SyndicationPerson(string.IsNullOrWhiteSpace(item.SiteName) ? item.HostName : item.SiteName, feed.authoremail, AtomContributorTypes.Author)); await rssWriter.Write(si); } catch (Exception ex) { Log.Error(ex, "Error building item {urlHash}:{url}", item.UrlHash, item.Url); } } xmlWriter.Flush(); } // Add the items to the cache before returning s = stringWriter.ToString(); _cache.Set <string>($"{id}_items", s, TimeSpan.FromMinutes(60)); Log.Information("CACHE SET: Storing feed items for {id} for {minutes} minutes", id, 60); return(s); }
public virtual ISyndicationItem CreateItem(ISyndicationContent content) { if (content == null) { throw new ArgumentNullException(nameof(content)); } var item = new SyndicationItem(); foreach (var field in content.Fields) { if (field.Namespace != RssConstants.Rss20Namespace) { continue; } switch (field.Name) { // // Title case RssElementNames.Title: item.Title = field.Value; break; // // Link case RssElementNames.Link: item.AddLink(CreateLink(field)); break; // Description case RssElementNames.Description: item.Description = field.Value; break; // // Author case RssElementNames.Author: item.AddContributor(CreatePerson(field)); break; // // Category case RssElementNames.Category: item.AddCategory(CreateCategory(field)); break; // // Links case RssElementNames.Comments: case RssElementNames.Enclosure: case RssElementNames.Source: item.AddLink(CreateLink(field)); break; // // Guid case RssElementNames.Guid: item.Id = field.Value; // isPermaLink string isPermaLinkAttr = field.Attributes.GetRss(RssConstants.IsPermaLink); if ((isPermaLinkAttr == null || (TryParseValue(isPermaLinkAttr, out bool isPermalink) && isPermalink)) && TryParseValue(field.Value, out Uri permaLink)) { item.AddLink(new SyndicationLink(permaLink, RssLinkTypes.Guid)); } break; // // PubDate case RssElementNames.PubDate: if (TryParseValue(field.Value, out DateTimeOffset dt)) { item.Published = dt; } break; default: break; } } return(item); }
public async Task <ActionResult> BlogRssFeed(string blogName) { var blog = WorkContext.Blogs.FirstOrDefault(); if (!string.IsNullOrEmpty(blogName)) { WorkContext.CurrentBlog = WorkContext.Blogs.FirstOrDefault(x => x.Name.EqualsInvariant(blogName)); } if (blog == null) { return(NotFound()); } var feedItems = new List <SyndicationItem>(); foreach (var article in blog.Articles.OrderByDescending(a => a.PublishedDate)) { if (!string.IsNullOrEmpty(article.Url)) { var urlString = UriHelper.GetDisplayUrl(Request); var requestUri = new Uri(urlString); var baseUri = new Uri(requestUri.Scheme + Uri.SchemeDelimiter + requestUri.Host); var fullUrl = new Uri(baseUri, UrlBuilder.ToAppAbsolute(article.Url, WorkContext.CurrentStore, WorkContext.CurrentLanguage)); var syndicationItem = new SyndicationItem() { Title = article.Title, Description = article.Excerpt, Published = article.PublishedDate.HasValue ? new DateTimeOffset(article.PublishedDate.Value) : new DateTimeOffset() }; syndicationItem.AddLink(new SyndicationLink(fullUrl)); feedItems.Add(syndicationItem); } } var sw = new StringWriter(); using (var xmlWriter = XmlWriter.Create(sw, new XmlWriterSettings() { Async = true, Indent = true })) { var writer = new RssFeedWriter(xmlWriter); await writer.WriteTitle(blog.Title); await writer.WriteDescription(blog.Title); await writer.Write(new SyndicationLink(new Uri(blog.Url, UriKind.Relative))); foreach (var item in feedItems) { await writer.Write(item); } xmlWriter.Flush(); } return(Content(sw.ToString(), "text/xml")); }
public async Task <IActionResult> Export() { var project = await _projectResolver.GetCurrentProjectSettings(CancellationToken.None); var articles = await _blogService.GetPosts(true); var baseUrl = string.Concat(HttpContext.Request.Scheme, "://", HttpContext.Request.Host.ToUriComponent()); var feedUrl = baseUrl + "api/rss"; var sb = new StringBuilder(); using (XmlWriter xmlWriter = XmlWriter.Create(sb, new XmlWriterSettings() { Async = true, Indent = true })) { var writer = new RssFeedWriter(xmlWriter); await writer.WriteTitle(project.Title); await writer.WriteDescription(".NET Foundation Blog"); if (!string.IsNullOrEmpty(project.LanguageCode)) { await writer.WriteLanguage(new CultureInfo(project.LanguageCode)); } foreach (var a in articles) { var postUrl = await _blogService.ResolvePostUrl(a); var item = new SyndicationItem() { Title = a.Title, Description = a.Content, Id = baseUrl + postUrl, Published = a.PubDate, LastUpdated = a.LastModified }; foreach (var c in a.Categories) { item.AddCategory(new SyndicationCategory(c)); } item.AddLink(new SyndicationLink(new Uri(baseUrl + postUrl))); //item.AddContributor(new SyndicationPerson("test", "*****@*****.**")); await writer.Write(item); } xmlWriter.Flush(); } var result = new ContentResult { ContentType = "application/xml", Content = sb.ToString(), StatusCode = 200 }; return(result); }