Ejemplo n.º 1
0
        public async Task <ActionResult> Rss()
        {
            var sw = new StringWriter();

            using (XmlWriter xmlWriter = XmlWriter.Create(sw, new XmlWriterSettings()
            {
                Async = true, Indent = true
            }))
            {
                var writer = new RssFeedWriter(xmlWriter);

                foreach (var art in BlogArticle.Queryable())
                {
                    // Create item
                    var item = new SyndicationItem()
                    {
                        Title       = art.Title,
                        Description = art.TextPreview,
                        Id          = $"https://matteofabbri.org/read/{art.Link}",
                        Published   = new DateTimeOffset(art.DateTime)
                    };

                    item.AddCategory(new SyndicationCategory(art.Category));
                    item.AddContributor(new SyndicationPerson("Matteo Fabbri", "*****@*****.**"));

                    await writer.Write(item);
                }

                xmlWriter.Flush();
            }
            return(Content(sw.ToString(), "application/rss+xml"));
        }
Ejemplo n.º 2
0
        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(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
                })
Ejemplo n.º 3
0
 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);
     }
 }
Ejemplo n.º 4
0
        public async Task <IActionResult> Execute()
        {
            var feedItems = await _feedRepository.GetAll();

            var sw = new StringWriterWithEncoding(Encoding.UTF8);

            using (var xmlWriter = XmlWriter.Create(sw, new XmlWriterSettings {
                Async = true, Indent = true
            }))
            {
                var writer = new RssFeedWriter(xmlWriter);
                foreach (var feedItem in feedItems)
                {
                    var item = new SyndicationItem
                    {
                        Title       = feedItem.Title,
                        Description = feedItem.Description,
                        Id          = feedItem.Id,
                        Published   = feedItem.CreateDateTime
                    };
                    item.AddContributor(new SyndicationPerson(feedItem.Author, "*****@*****.**"));
                    await writer.Write(item);
                }

                xmlWriter.Flush();
            }

            return(new ObjectResult(sw.ToString()));
        }
        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);
        }
Ejemplo n.º 6
0
        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 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 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);
        }
Ejemplo n.º 9
0
        public async Task <string> GenerateFeed(IEnumerable <ReleaseViewModel> releases)
        {
            const string title   = "Changelog Feed";
            var          id      = new UniqueId();
            var          updated = DateTimeOffset.UtcNow;

            var sw = new StringWriterWithEncoding(Encoding.UTF8);

            using (var xmlWriter = XmlWriter.Create(sw, new XmlWriterSettings()
            {
                Async = true, Indent = true
            }))
            {
                var writer = new AtomFeedWriter(xmlWriter);

                await writer.WriteTitle(title);

                await writer.WriteId(id.ToString());

                await writer.WriteUpdated(updated);

                foreach (var release in releases)
                {
                    var item = new SyndicationItem()
                    {
                        Title       = release.ReleaseVersion,
                        Id          = new UniqueId(release.ReleaseId).ToString(),
                        LastUpdated = release.ReleaseDate
                    };

                    release.Authors.ForEach(x =>
                                            item.AddContributor(new SyndicationPerson(x, $"{x}@test.com"))
                                            );

                    var sb = new StringBuilder();
                    foreach (var workItemViewModel in release.WorkItems)
                    {
                        sb.Append(workItemViewModel.WorkItemTypeString)
                        .Append(": ")
                        .AppendLine(workItemViewModel.Description)
                        ;
                    }
                    item.Description = sb.ToString();

                    await writer.Write(item);
                }

                xmlWriter.Flush();
            }

            return(sw.GetStringBuilder().ToString());
        }
Ejemplo n.º 10
0
        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));
            }
        }
Ejemplo n.º 11
0
        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);
        }
Ejemplo n.º 12
0
        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);
        }
Ejemplo n.º 13
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());
    }
Ejemplo n.º 14
0
        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);
        }
Ejemplo n.º 15
0
        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();
            }
        }
Ejemplo n.º 16
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();
        }
Ejemplo n.º 17
0
        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);
        }
Ejemplo n.º 18
0
        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);
        }
Ejemplo n.º 19
0
        public ActionResult Index()
        {
            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.ReaderWriter",
                Published   = DateTimeOffset.UtcNow
            };

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

            var item2 = new SyndicationItem()
            {
                Title       = "We need RSS 'frame'",
                Description = "We need a structure that hold the RSS/feed information",
                Id          = "xx",
                Published   = DateTimeOffset.UtcNow
            };

            return(Ok(new[] { item, item2 }));
        }
Ejemplo n.º 20
0
        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);
        }
Ejemplo n.º 21
0
    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());
    }
Ejemplo n.º 22
0
        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());
        }
Ejemplo n.º 23
0
        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 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);
        }
Ejemplo n.º 25
0
        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);
        }
Ejemplo n.º 26
0
        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"));
            }
        }
Ejemplo n.º 27
0
        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);
        }
Ejemplo n.º 28
0
        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();
                }
            }
        }