Exemplo n.º 1
0
        public async Task ReadImage()
        {
            using (XmlReader xmlReader = XmlReader.Create(@"..\..\..\TestFeeds\simpleAtomFeed.xml", new XmlReaderSettings {
                Async = true
            }))
            {
                var reader     = new AtomFeedReader(xmlReader);
                int imagesRead = 0;

                List <String> contentsOfImages = new List <string>();

                while (await reader.Read())
                {
                    if (reader.ElementType == SyndicationElementType.Image)
                    {
                        ISyndicationImage image = await reader.ReadImage();

                        imagesRead++;
                        contentsOfImages.Add(image.Url.OriginalString);
                    }
                }
                Assert.True(imagesRead == 2);
                Assert.True(contentsOfImages[0] == "/icon.jpg");
                Assert.True(contentsOfImages[1] == "/logo.jpg");
            }
        }
Exemplo n.º 2
0
        public async Task ReadPerson()
        {
            using (XmlReader xmlReader = XmlReader.Create(@"..\..\..\TestFeeds\simpleAtomFeed.xml", new XmlReaderSettings {
                Async = true
            }))
            {
                var persons = new List <ISyndicationPerson>();
                var reader  = new AtomFeedReader(xmlReader);
                while (await reader.Read())
                {
                    if (reader.ElementType == SyndicationElementType.Person)
                    {
                        ISyndicationPerson person = await reader.ReadPerson();

                        persons.Add(person);
                    }
                }

                Assert.True(persons.Count() == 2);
                Assert.True(persons[0].Name == "Mark Pilgrim");
                Assert.True(persons[0].Email == "*****@*****.**");
                Assert.True(persons[0].Uri == "http://example.org/");
                Assert.True(persons[1].Name == "Sam Ruby");
            }
        }
Exemplo n.º 3
0
        public override async Task <DBSubscription> CreateSubscriptionAsync(Uri uri)
        {
            var url = uri.AbsoluteUri.Contains(".rss") ? uri.AbsoluteUri : $"{uri.AbsoluteUri}.rss";

            using (var xmlReader = XmlReader.Create(url, new XmlReaderSettings {
                Async = true
            }))
            {
                var feedReader = new AtomFeedReader(xmlReader);

                while (await feedReader.Read())
                {
                    switch (feedReader.ElementType)
                    {
                    case SyndicationElementType.Content:
                        var content = await feedReader.ReadContent();

                        if (string.Equals(content.Name, "id", StringComparison.OrdinalIgnoreCase))
                        {
                            return(new DBSubscription
                            {
                                Source = ESource.Reddit,
                                IsProtected = false,
                                SourceId = content.Value,
                                Username = content.Value.Replace(".rss", string.Empty)
                            });
                        }
                        break;
                    }
                }
            }

            return(null);
        }
Exemplo n.º 4
0
        public override async Task <List <DBCard> > GetCardsAsync(DBSubscription subscription)
        {
            var items = new List <DBCard>();

            using (var xmlReader = XmlReader.Create(new StringReader(await BaseClient.GetStringAsync(new RestRequest($"https://www.reddit.com{subscription.SourceId}"))), new XmlReaderSettings {
                Async = true
            }))
            {
                var feedReader = new AtomFeedReader(xmlReader);

                while (await feedReader.Read())
                {
                    switch (feedReader.ElementType)
                    {
                    case SyndicationElementType.Item:
                        var item = await feedReader.ReadItem();

                        var card = new DBCard
                        {
                            CardId      = item.Id,
                            Text        = item.Title,
                            Header      = item.Categories.First().Label,
                            Timestamp   = item.LastUpdated,
                            OriginalUrl = item.Links.First().Uri.AbsoluteUri
                        };

                        items.Add(card);
                        break;
                    }
                }
            }

            return(items);
        }
Exemplo n.º 5
0
        public async Task ReadItemContent()
        {
            using (XmlReader xmlReader = XmlReader.Create(@"..\..\..\TestFeeds\simpleAtomFeed.xml", new XmlReaderSettings {
                Async = true
            }))
            {
                var reader = new AtomFeedReader(xmlReader);

                while (await reader.Read())
                {
                    if (reader.ElementType == SyndicationElementType.Item)
                    {
                        ISyndicationContent content = await reader.ReadContent();

                        var fields = content.Fields.ToArray();

                        Assert.True(fields.Length == 12);

                        Assert.True(fields[0].Name == "title");
                        Assert.False(string.IsNullOrEmpty(fields[0].Value));

                        Assert.True(fields[1].Name == "link");
                        Assert.True(fields[1].Attributes.Count() > 0);

                        Assert.True(fields[2].Name == "link");
                        Assert.True(fields[2].Attributes.Count() > 0);

                        Assert.True(fields[3].Name == "id");
                        Assert.False(string.IsNullOrEmpty(fields[3].Value));

                        Assert.True(fields[4].Name == "updated");
                        Assert.False(string.IsNullOrEmpty(fields[4].Value));

                        Assert.True(fields[5].Name == "published");
                        Assert.False(string.IsNullOrEmpty(fields[5].Value));

                        Assert.True(fields[6].Name == "source");
                        Assert.True(fields[6].Fields.Count() > 0);

                        Assert.True(fields[7].Name == "author");
                        Assert.True(fields[7].Fields.Count() > 0);

                        Assert.True(fields[8].Name == "contributor");
                        Assert.True(fields[8].Fields.Count() > 0);

                        Assert.True(fields[9].Name == "contributor");
                        Assert.True(fields[9].Fields.Count() > 0);

                        Assert.True(fields[10].Name == "rights");
                        Assert.False(string.IsNullOrEmpty(fields[10].Value));

                        Assert.True(fields[11].Name == "content");
                        Assert.False(string.IsNullOrEmpty(fields[11].Value));
                    }
                }
            }
        }
Exemplo n.º 6
0
        private static async Task <List <object> > ParseExport(XmlReader xmlReader)
        {
            List <object> result = new List <object>();
            {
                var feedReader = new AtomFeedReader(xmlReader);
                while (await feedReader.Read())
                {
                    switch (feedReader.ElementType)
                    {
                    // Read category
                    case SyndicationElementType.Category:
                        ISyndicationCategory category = await feedReader.ReadCategory();

                        result.Add(category);
                        break;

                    // Read Image
                    case SyndicationElementType.Image:
                        ISyndicationImage image = await feedReader.ReadImage();

                        result.Add(image);
                        break;

                    // Read Item
                    case SyndicationElementType.Item:
                        ISyndicationItem item = await feedReader.ReadItem();

                        result.Add(item);
                        break;

                    // Read link
                    case SyndicationElementType.Link:
                        ISyndicationLink link = await feedReader.ReadLink();

                        result.Add(link);
                        break;

                    // Read Person
                    case SyndicationElementType.Person:
                        ISyndicationPerson person = await feedReader.ReadPerson();

                        result.Add(person);
                        break;

                    // Read content
                    default:
                        ISyndicationContent content = await feedReader.ReadContent();

                        result.Add(content);
                        break;
                    }
                }

                return(result);
            }
        }
Exemplo n.º 7
0
        public override async Task <DBSubscription> CreateSubscriptionAsync(Uri uri)
        {
            var id = uri.Segments.ElementAtOrDefault(2);

            if (id == null)
            {
                return(null);
            }

            if (uri.Segments.ElementAt(1) == "c/" || uri.Segments.ElementAt(1) == "user/")
            {
                var channelId = await PollyHelper.WebFallbackAsync(() => _client.ChannelId(uri.AbsoluteUri));

                if (channelId == null)
                {
                    return(null);
                }

                id = channelId;
            }

            using (var xmlReader = XmlReader.Create($"https://www.youtube.com/feeds/videos.xml?channel_id={id}", new XmlReaderSettings {
                Async = true
            }))
            {
                var feedReader = new AtomFeedReader(xmlReader);

                while (await feedReader.Read())
                {
                    switch (feedReader.ElementType)
                    {
                    case SyndicationElementType.Content:
                        var content = await feedReader.ReadContent();

                        if (string.Equals(content.Name, "title", StringComparison.OrdinalIgnoreCase))
                        {
                            return(new DBSubscription
                            {
                                Source = ESource.Youtube,
                                IsProtected = false,
                                SourceId = id,
                                Username = content.Value
                            });
                        }
                        break;
                    }
                }
            }

            return(null);
        }
Exemplo n.º 8
0
        private async Task ProcessBlog(Blog blog)
        {
            using (var reader = XmlReader.Create(blog.FeedUrl, new XmlReaderSettings {
                Async = true, DtdProcessing = DtdProcessing.Parse
            }))
            {
                ISyndicationFeedReader feedReader = null;
                if (blog.FeedType == "atom")
                {
                    feedReader = new AtomFeedReader(reader);
                }
                else
                {
                    feedReader = new RssFeedReader(reader);
                }

                while (await feedReader.Read())
                {
                    switch (feedReader.ElementType)
                    {
                    case SyndicationElementType.Item:
                        ISyndicationItem item = await feedReader.ReadItem();

                        var entity = new RssItem()
                        {
                            Title = item.Title,
                            Link  = item.Id,
                        };

                        if (!entity.Link.StartsWith("http"))
                        {
                            entity.Link = blog.Url + item.Id;
                        }

                        using (var txn = this.StateManager.CreateTransaction())
                        {
                            var items = await this.StateManager.GetOrAddAsync <IReliableDictionary <string, RssItem> >(string.Format(rssItems, blog.Id.ToString("N")));

                            await items.AddAsync(txn, Guid.NewGuid().ToString("N"), entity);

                            await txn.CommitAsync();
                        }
                        break;

                    default:
                        break;
                    }
                }
            }
        }
        private void UpdateCollection()
        {
            try
            {
                _sdataResourceCollectionRequest = new SDataResourceCollectionRequest(Service)
                {
                    ResourceKind = tbCollectionResourceKind.Text,
                    StartIndex   = (int)numStartIndex.Value,
                    Count        = (int)numCount.Value
                };
                _feed   = _sdataResourceCollectionRequest.Read();
                _reader = null;

                var lookup = _feed.Links.ToLookup(link => link.Relation);
                btnFirst.Enabled    = lookup["first"].Any();
                btnPrevious.Enabled = lookup["previous"].Any();
                btnNext.Enabled     = lookup["next"].Any();
                btnLast.Enabled     = lookup["last"].Any();

                var table = new DataTable();
                table.Columns.Add("Author");
                table.Columns.Add("Id");
                table.Columns.Add("Title");

                // iterate through the list of entries in the feed
                foreach (var atomentry in _feed.Entries)
                {
                    var dr = table.NewRow();
                    dr[0] = atomentry.Authors.Select(author => author.Name).FirstOrDefault();
                    dr[1] = atomentry.Id.Uri.AbsoluteUri;
                    dr[2] = atomentry.Title.Content;

                    table.Rows.Add(dr);
                }

                // show it in the grid
                atomEntryGrid.DataSource = table;
                atomEntryGrid.Refresh();
                atomEntryGrid.AutoResizeColumns();

                if (atomEntryGrid.SelectedRows.Count != 0)
                {
                    atomEntryGrid_CellContentClick(null, null);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Exemplo n.º 10
0
        private async Task <SubscriptionUpdate[]> CheckRssForUpdatesAsync(Subscription subscription, CancellationToken cancellationToken)
        {
            var url = subscription.Url;

            var response = await _httpClient.GetAsync(new HttpRequestMessage(HttpMethod.Get, url), cancellationToken);

            if (!response.IsSuccessStatusCode)
            {
                var content = await response.Content.ReadAsStringAsync();

                throw new ResponseException($"Failed to check for subscription update of {url}. Response code: {response.StatusCode}, Response: {content}");
            }

            var updates = new List <SubscriptionUpdate>();

            // https://github.com/dotnet/SyndicationFeedReaderWriter
            using (var xmlReader = XmlReader.Create(await response.Content.ReadAsStreamAsync(), new XmlReaderSettings()
            {
                Async = true
            }))
            {
                // TODO: auto detect Atom vs Rss
                var feedReader = new AtomFeedReader(xmlReader);
                while (await feedReader.Read())
                {
                    switch (feedReader.ElementType)
                    {
                    case SyndicationElementType.Item:
                        ISyndicationItem item = await feedReader.ReadItem();

                        var date  = item.Published;
                        var title = item.Title ?? $"update by {subscription.Name}";
                        var link  = item.Links.FirstOrDefault()?.Uri?.ToString() ?? subscription.Url;

                        updates.Add(new SubscriptionUpdate
                        {
                            Subscription = subscription,
                            Name         = subscription.Name,
                            LastUpdated  = date,
                            Message      = title,
                            Url          = link
                        });
                        break;
                    }
                }
            }

            return(updates.ToArray());
        }
Exemplo n.º 11
0
        public override async Task <List <DBCard> > GetCardsAsync(DBSubscription subscription)
        {
            var items = new List <DBCard>();

            using (var xmlReader = XmlReader.Create(new StringReader(await BaseClient.GetStringAsync(new RestRequest(subscription.SourceId))), new XmlReaderSettings {
                Async = true, IgnoreComments = true, IgnoreWhitespace = true
            }))
            {
                XmlFeedReader feedReader;

                if (new Atom10FeedFormatter().CanRead(xmlReader))
                {
                    feedReader = new AtomFeedReader(xmlReader);
                }
                else
                {
                    feedReader = new RssFeedReader(xmlReader);
                }

                while (await feedReader.Read())
                {
                    switch (feedReader.ElementType)
                    {
                    case SyndicationElementType.Item:
                        var item = await feedReader.ReadItem();

                        var card = new DBCard
                        {
                            CardId      = item.Id,
                            Header      = subscription.Username,
                            Text        = item.Title.Trim().Replace("&quot;", "\""),
                            Timestamp   = item.Published,
                            OriginalUrl = item.Links.FirstOrDefault(f => string.Equals(f.RelationshipType, "alternate", StringComparison.OrdinalIgnoreCase))?.Uri.AbsoluteUri
                        };

                        items.Add(card);
                        break;
                    }
                }
            }

            return(items);
        }
Exemplo n.º 12
0
        public async Task ReadCategory()
        {
            using (XmlReader xmlReader = XmlReader.Create(@"..\..\..\TestFeeds\simpleAtomFeed.xml", new XmlReaderSettings {
                Async = true
            }))
            {
                var reader = new AtomFeedReader(xmlReader);
                while (await reader.Read())
                {
                    if (reader.ElementType == SyndicationElementType.Category)
                    {
                        ISyndicationCategory category = await reader.ReadCategory();

                        Assert.True(category.Name == "sports");
                        Assert.True(category.Label == "testLabel");
                        Assert.True(category.Scheme == "testScheme");
                    }
                }
            }
        }
Exemplo n.º 13
0
        public override async Task <DBSubscription> CreateSubscriptionAsync(Uri uri)
        {
            using (var xmlReader = XmlReader.Create(uri.AbsoluteUri, new XmlReaderSettings {
                Async = true, IgnoreComments = true, IgnoreWhitespace = true
            }))
            {
                XmlFeedReader feedReader;

                if (new Atom10FeedFormatter().CanRead(xmlReader))
                {
                    feedReader = new AtomFeedReader(xmlReader);
                }
                else
                {
                    feedReader = new RssFeedReader(xmlReader);
                }

                while (await feedReader.Read())
                {
                    switch (feedReader.ElementType)
                    {
                    case SyndicationElementType.Content:
                        var content = await feedReader.ReadContent();

                        if (string.Equals(content.Name, "title", StringComparison.OrdinalIgnoreCase))
                        {
                            return(new DBSubscription
                            {
                                Source = ESource.RSS,
                                IsProtected = false,
                                SourceId = uri.AbsoluteUri,
                                Username = content.Value
                            });
                        }
                        break;
                    }
                }
            }

            return(null);
        }
Exemplo n.º 14
0
        public async Task ReadLink()
        {
            using (XmlReader xmlReader = XmlReader.Create(@"..\..\..\TestFeeds\simpleAtomFeed.xml", new XmlReaderSettings {
                Async = true
            }))
            {
                var           reader = new AtomFeedReader(xmlReader);
                List <string> hrefs  = new List <string>();
                while (await reader.Read())
                {
                    if (reader.ElementType == SyndicationElementType.Link)
                    {
                        ISyndicationLink link = await reader.ReadLink();

                        hrefs.Add(link.Uri.OriginalString);
                    }
                }
                Assert.True(hrefs[0] == "http://example.org/");
                Assert.True(hrefs[1] == "http://example.org/feed.atom");
            }
        }
Exemplo n.º 15
0
        public async Task ReadItem()
        {
            using (XmlReader xmlReader = XmlReader.Create(@"..\..\..\TestFeeds\simpleAtomFeed.xml", new XmlReaderSettings {
                Async = true
            }))
            {
                var reader = new AtomFeedReader(xmlReader);
                while (await reader.Read())
                {
                    if (reader.ElementType == SyndicationElementType.Item)
                    {
                        IAtomEntry item = await reader.ReadEntry();

                        //Assert content of item
                        Assert.True(item.Title == "Atom draft-07 snapshot");
                        Assert.True(item.Links.Count() == 3);
                        Assert.True(item.Contributors.Count() == 3);
                        Assert.True(item.Rights == "All rights Reserved. Contoso.");
                        Assert.True(item.Id == "tag:example.org,2003:3.2397");
                    }
                }
            }
        }
        private void btnReaderRead_Click(object sender, EventArgs e)
        {
            try
            {
                _sdataResourceCollectionRequest = new SDataResourceCollectionRequest(Service)
                {
                    ResourceKind = tbCollectionResourceKind.Text,
                    StartIndex   = (int)numStartIndex.Value,
                    Count        = (int)numCount.Value
                };

                _feed   = null;
                _reader = _sdataResourceCollectionRequest.ExecuteReader();

                tbReaderCount.Text = _reader.Count.ToString();

                UpdateReaderGrid();
            }
            catch (SDataClientException ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Exemplo n.º 17
0
        public override async Task <List <DBCard> > GetCardsAsync(DBSubscription subscription)
        {
            var items = new List <DBCard>();

            using (var xmlReader = XmlReader.Create(new StringReader(await BaseClient.GetStringAsync(new RestRequest($"https://www.youtube.com/feeds/videos.xml?channel_id={subscription.SourceId}"))), new XmlReaderSettings {
                Async = true
            }))
            {
                var feedReader = new AtomFeedReader(xmlReader);

                while (await feedReader.Read())
                {
                    switch (feedReader.ElementType)
                    {
                    case SyndicationElementType.Item:
                        var item = await feedReader.ReadItem();

                        var id = item.Id.Split(":").Last();

                        var card = new DBCard
                        {
                            CardId      = item.Id,
                            Text        = item.Title,
                            Header      = item.Contributors.FirstOrDefault()?.Name,
                            Timestamp   = item.Published,
                            OriginalUrl = $"https://www.youtube.com/embed/{id}?autoplay=1&modestbranding=0&rel=0"
                        };

                        items.Add(card);
                        break;
                    }
                }
            }

            return(items);
        }
 public AtomFeedReaderTest()
 {
     _feedReader = new AtomFeedReader(Mock.Of <ILogger <AtomFeedReader> >());
 }
Exemplo n.º 19
0
        // Handles RSS2.0 and Atom feeds
        private async Task <bool> HandleXmlFeed(Feed feed, bool populateCacheOnly = false)
        {
            using (log.BeginScope($"{ nameof(FeedService) }->{ nameof(HandleXmlFeed) } with feed: {feed}"))
            {
                try
                {
                    // Create async reader
                    using (XmlReader xmlReader = XmlReader.Create(feed.ConnectionString, new XmlReaderSettings()
                    {
                        Async = true
                    }))
                    {
                        ISyndicationFeedReader reader = null;

                        // Special reader for every type
                        switch (feed.Type)
                        {
                        case FeedType.RSS:
                            log.LogDebug("Creating RssFeedReader");
                            reader = new RssFeedReader(xmlReader);
                            break;

                        case FeedType.Atom:
                            log.LogDebug("Creating AtomFeedReader");
                            reader = new AtomFeedReader(xmlReader);
                            break;

                        default:
                            log.LogError("Invalid FeedType found.");
                            return(false);
                        }

                        log.LogDebug("Starting feed reading");

                        // Read the entries async
                        while (await reader.Read())
                        {
                            log.LogDebug("Found elementType '{ElementType}'", reader.ElementType);

                            // We only need the entrytypes (yet)
                            if (reader.ElementType == SyndicationElementType.Item)
                            {
                                FeedEntry feedEntry = null;

                                // Create my feedEntry
                                switch (feed.Type)
                                {
                                case FeedType.RSS:
                                    ISyndicationItem rssEntry = await(reader as RssFeedReader).ReadItem();
                                    log.LogDebug("ISyndicationItem: {Item}", rssEntry);
                                    feedEntry = CreateFeedEntry(rssEntry, feed);
                                    break;

                                case FeedType.Atom:
                                    IAtomEntry atomEntry = await(reader as AtomFeedReader).ReadEntry();
                                    log.LogDebug("IAtomEntry: {Entry}", atomEntry);
                                    feedEntry = CreateFeedEntry(atomEntry, feed);
                                    break;

                                default:
                                    continue;
                                }

                                // Check if we already had this one
                                if (await cache.IsCached(feedEntry.Id))
                                {
                                    log.LogDebug("ID '{Id}' is in cache", feedEntry.Id);
                                }
                                // Check if the entry is older then MaxAge to prevent double posting
                                else if (feedEntry?.Published <= (DateTime.Now - cfg.Application.Cache.MaxAge))
                                {
                                    log.LogInformation("Entry '{Id}' is too old.", feedEntry.Id);
                                }
                                else
                                {
                                    // Hand over to instance service
                                    log.LogDebug("Tooting id '{Id}' ", feedEntry.Id);
                                    await TootTheFeedEntry(feedEntry, populateCacheOnly, feed);
                                }
                            }
                        }

                        return(true);
                    }
                }
                catch (Exception ex)
                {
                    log.LogError(ex, "HandleXmlFeed Exception - {feed}", feed);
                    return(false);
                }
            }
        }
Exemplo n.º 20
0
        /// <summary>
        /// Reads the Atom feed at <see cref="ReleaseUpdateUri"/> and fills the <see cref="Releases"/>
        /// collection with information. If a release with higher version number than <see cref="ApplicationVersion"/>
        /// is found then the <see cref="ReleaseToUpdate"/> is set to this release.
        /// </summary>
        /// <param name="force"></param>
        /// <returns></returns>
        public async Task <bool> CheckForUpdate(bool force = false)
        {
            EnsureUpdateEntry();
            if (updateEntry.LastCheck == DateTime.Today && !force)
            {
                return(false);
            }
            try
            {
                using (var cl = new HttpClient())
                {
                    var response = await cl.GetAsync(ReleaseUpdateUri);

                    response.EnsureSuccessStatusCode();
                    using (var xmlReader = XmlReader.Create(await response.Content.ReadAsStreamAsync(),
                                                            new XmlReaderSettings
                    {
                        Async = true
                    }))
                    {
                        Releases.Clear();
                        ReleaseToUpdate = null;
                        var feedReader = new AtomFeedReader(xmlReader);

                        while (await feedReader.Read())
                        {
                            switch (feedReader.ElementType)
                            {
                            case SyndicationElementType.Category:
                                await feedReader.ReadCategory();

                                break;

                            case SyndicationElementType.Image:
                                await feedReader.ReadImage();

                                break;

                            case SyndicationElementType.Item:
                                var entry = await feedReader.ReadEntry();

                                var r = new Release();
                                r.DownloadUri = entry.Links.FirstOrDefault(x => x.RelationshipType == "alternate")?.Uri;
                                if (r.DownloadUri != null)
                                {
                                    r.Updated       = entry.LastUpdated.ToUniversalTime().LocalDateTime;
                                    r.ParsedVersion = ParseVersion(r.DownloadUri.AbsolutePath);
                                    if (r.ParsedVersion != null)
                                    {
                                        Releases.Add(r);
                                    }
                                }

                                break;

                            case SyndicationElementType.Link:
                                await feedReader.ReadLink();

                                break;

                            case SyndicationElementType.Person:
                                await feedReader.ReadPerson();

                                break;

                            default:
                                await feedReader.ReadContent();

                                break;
                            }
                        }

                        if (Releases.Count == 0)
                        {
                            return(false);
                        }
                        var top = Releases.OrderByDescending(x => x.ParsedVersion).First();
                        if (top.ParsedVersion > ApplicationVersion)
                        {
                            ReleaseToUpdate = top;
                            return(true);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogException(ex);
                return(false);
            }
            updateEntry.LastCheck = DateTime.Today;
            SaveUpdateEntry();
            return(false);
        }
Exemplo n.º 21
0
    public static async Task ReadAtomFeed(string filePath)
    {
        //
        // Create an XmlReader from file
        // Example: ..\tests\TestFeeds\simpleAtomFeed.xml
        using (XmlReader xmlReader = XmlReader.Create(filePath, new XmlReaderSettings()
        {
            Async = true
        }))
        {
            //
            // Create an AtomFeedReader
            var reader = new AtomFeedReader(xmlReader);

            //
            // Read the feed
            while (await reader.Read())
            {
                //
                // Check the type of the current element.
                switch (reader.ElementType)
                {
                //
                // Read category
                case SyndicationElementType.Category:
                    ISyndicationCategory category = await reader.ReadCategory();

                    break;

                //
                // Read image
                case SyndicationElementType.Image:
                    ISyndicationImage image = await reader.ReadImage();

                    break;

                //
                // Read entry
                case SyndicationElementType.Item:
                    IAtomEntry entry = await reader.ReadEntry();

                    break;

                //
                // Read link
                case SyndicationElementType.Link:
                    ISyndicationLink link = await reader.ReadLink();

                    break;

                //
                // Read person
                case SyndicationElementType.Person:
                    ISyndicationPerson person = await reader.ReadPerson();

                    break;

                //
                // Read content
                default:
                    ISyndicationContent content = await reader.ReadContent();

                    break;
                }
            }
        }
    }
        private async Task <List <BlogPost> > GetFeed()
        {
            var xmlReader = XmlReader.Create(_settings.Value.FeedUrl);
            var reader    = new AtomFeedReader(xmlReader);

            var posts = new List <BlogPost>();

            //
            // Read the feed
            while (await reader.Read())
            {
                //
                // Check the type of the current element.
                switch (reader.ElementType)
                {
                //
                // Read category
                case SyndicationElementType.Category:
                    ISyndicationCategory category = await reader.ReadCategory();

                    break;

                //
                // Read image
                case SyndicationElementType.Image:
                    ISyndicationImage image = await reader.ReadImage();

                    break;

                //
                // Read entry
                case SyndicationElementType.Item:
                    IAtomEntry entry = await reader.ReadEntry();

                    // these are the only ones we need for now
                    posts.Add(new BlogPost
                    {
                        Title         = entry.Title,
                        PublishedDate = entry.Published.DateTime,
                        Categories    = entry.Categories?.Select(c => c.Name)?.ToList()
                    });
                    break;

                //
                // Read link
                case SyndicationElementType.Link:
                    ISyndicationLink link = await reader.ReadLink();

                    break;

                //
                // Read person
                case SyndicationElementType.Person:
                    ISyndicationPerson person = await reader.ReadPerson();

                    break;

                //
                // Read content
                default:
                    ISyndicationContent content = await reader.ReadContent();

                    break;
                }
            }

            return(posts);
        }
 /// <summary>
 /// Performs initial read from AtomFeedReader
 /// </summary>
 /// <returns></returns>
 public AtomFeedReader ExecuteReader()
 {
     var reader = new AtomFeedReader(this);
     return reader.Read() ? reader : null;
 }
        private void UpdateCollection()
        {
            try
            {
                _sdataResourceCollectionRequest = new SDataResourceCollectionRequest(Service)
                                                  {
                                                      ResourceKind = tbCollectionResourceKind.Text,
                                                      StartIndex = (int) numStartIndex.Value,
                                                      Count = (int) numCount.Value
                                                  };
                _feed = _sdataResourceCollectionRequest.Read();
                _reader = null;

                var lookup = _feed.Links.ToLookup(link => link.Relation);
                btnFirst.Enabled = lookup["first"].Any();
                btnPrevious.Enabled = lookup["previous"].Any();
                btnNext.Enabled = lookup["next"].Any();
                btnLast.Enabled = lookup["last"].Any();

                var table = new DataTable();
                table.Columns.Add("Author");
                table.Columns.Add("Id");
                table.Columns.Add("Title");

                // iterate through the list of entries in the feed
                foreach (var atomentry in _feed.Entries)
                {
                    var dr = table.NewRow();
                    dr[0] = atomentry.Authors.Select(author => author.Name).FirstOrDefault();
                    dr[1] = atomentry.Id.Uri.AbsoluteUri;
                    dr[2] = atomentry.Title.Content;

                    table.Rows.Add(dr);
                }

                // show it in the grid
                atomEntryGrid.DataSource = table;
                atomEntryGrid.Refresh();
                atomEntryGrid.AutoResizeColumns();

                if (atomEntryGrid.SelectedRows.Count != 0)
                {
                    atomEntryGrid_CellContentClick(null, null);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        private void btnReaderRead_Click(object sender, EventArgs e)
        {
            try
            {
                _sdataResourceCollectionRequest = new SDataResourceCollectionRequest(Service)
                                                  {
                                                      ResourceKind = tbCollectionResourceKind.Text,
                                                      StartIndex = (int) numStartIndex.Value,
                                                      Count = (int) numCount.Value
                                                  };

                _feed = null;
                _reader = _sdataResourceCollectionRequest.ExecuteReader();

                tbReaderCount.Text = _reader.Count.ToString();

                UpdateReaderGrid();
            }
            catch (SDataClientException ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Exemplo n.º 26
0
        public async Task <AtomPage> ReadAtomPage(Stream stream)
        {
            using var xmlReader = XmlReader.Create(stream, new XmlReaderSettings { Async = true });

            var feedReader = new AtomFeedReader(xmlReader);
            var entries = new List <AtomEntry>();
            Uri?nextPageUri = null, previousPageUri = null, realTimeNotificationUri = null;

            while (await feedReader.Read())
            {
                await ProcessElementAsync();
            }

            return(new AtomPage(
                       nextArchivePageUri: nextPageUri,
                       previousArchivePageUri: previousPageUri,
                       realTimeNotificationUri: realTimeNotificationUri,
                       entries: entries
                       ));

            async Task ProcessElementAsync()
            {
                switch (feedReader.ElementType)
                {
                case SyndicationElementType.Item:
                    await ProcessItemElementAsync();

                    break;

                case SyndicationElementType.Link:
                    await ProcessLinkElementAsync();

                    break;
                }
            }

            async Task ProcessItemElementAsync()
            {
                var item = (Microsoft.SyndicationFeed.Atom.AtomEntry) await feedReader.ReadItem();

                var atomEntry = new AtomEntry(
                    id: item.Id,
                    published: item.Published,
                    contentType: item.ContentType,
                    payload: item.Description
                    );

                entries.Insert(0, atomEntry);
            }

            async Task ProcessLinkElementAsync()
            {
                ISyndicationLink link = await feedReader.ReadLink();

                switch (link.RelationshipType)
                {
                case "next-archive" when nextPageUri == null:
                    nextPageUri = link.Uri;
                    break;

                case "prev-archive" when previousPageUri == null:
                    previousPageUri = link.Uri;
                    break;

                case "notifications" when realTimeNotificationUri == null:
                    realTimeNotificationUri = link.Uri;
                    break;
                }
            }
        }
        public async Task <IEnumerable <IAtomEntry> > ReadEntriesAsync(
            Uri feedUrl,
            long?from,
            string feedUserName = "",
            string feedPassword = "",
            bool embedEvent     = true,
            bool embedObject    = true)
        {
            var entries = new List <IAtomEntry>();

            var embedString = string.Empty;

            if (embedObject && embedEvent)
            {
                embedString = "embed: \"event,object\"";
            }
            else if (embedObject)
            {
                embedString = "embed: \"object\"";
            }
            else if (embedEvent)
            {
                embedString = "embed: \"event\"";
            }

            _httpClient.DefaultRequestHeaders.Remove("X-Filtering");
            if (from.HasValue)
            {
                var filter = string.IsNullOrEmpty(embedString) ? $"{{ position: {@from} }}" : $"{{ position: {@from}, {embedString} }}";
                _httpClient.DefaultRequestHeaders.Add("X-Filtering", filter);
            }
            else
            {
                _httpClient.DefaultRequestHeaders.Add("X-Filtering", $"{{ {embedString} }}");
            }


            if (!string.IsNullOrEmpty(feedUserName) && !string.IsNullOrEmpty(feedPassword))
            {
                _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes($"{feedUserName}:{feedPassword}")));
            }

            try
            {
                using (var response = await _httpClient.GetAsync(feedUrl))
                    using (var responseStream = await response.Content.ReadAsStreamAsync())
                        using (var xmlReader = XmlReader.Create(responseStream, new XmlReaderSettings {
                            Async = true
                        }))
                        {
                            var atomReader = new AtomFeedReader(xmlReader);
                            while (await atomReader.Read())
                            {
                                if (atomReader.ElementType == SyndicationElementType.Item)
                                {
                                    entries.Add(await atomReader.ReadEntry());
                                }
                            }
                        }
            }
            catch (Exception e)
            {
                _logger.LogError(e.Message, e);

                throw;
            }

            return(entries);
        }