private async Task FetchNewsPages() { var pages = await NewsPageViewModel.FetchNewsPages(ServiceProvider, 30); var sortedPages = pages.OrderBy(x => x.Date).Reverse().ToList(); Dispatcher.Invoke(() => NewsPages = new ObservableList <NewsPageViewModel>(sortedPages)); }
public static async Task <List <NewsPageViewModel> > FetchNewsPages(IViewModelServiceProvider serviceProvider, int maxCount) { var result = new List <NewsPageViewModel>(); var rss = new MemoryStream(); try { WebRequest request = WebRequest.Create(Urls.RssFeed); using (var reponse = await request.GetResponseAsync()) { using (var str = reponse.GetResponseStream()) { str?.CopyTo(rss); } } } catch (Exception) { // Unable to reach the url, return an empty list. return(result); } rss.Position = 0; if (rss.Length == 0) { return(result); } try { int count = 0; using (XmlReader rssReader = XmlReader.Create(rss)) { rssReader.MoveToContent(); while (rssReader.ReadToFollowing("item") && count < maxCount) { rssReader.ReadToFollowing("title"); string title = rssReader.Read() ? rssReader.Value : null; rssReader.ReadToFollowing("description"); string description = rssReader.Read() ? rssReader.Value : null; rssReader.ReadToFollowing("pubDate"); var date = new DateTime(); bool dateValid = rssReader.Read() && DateTime.TryParseExact(rssReader.Value, "ddd, dd MMM yyyy HH:mm:ss zz00", CultureInfo.InvariantCulture, DateTimeStyles.None, out date); rssReader.ReadToFollowing("link"); string link = rssReader.Read() ? rssReader.Value : null; if (dateValid && title != null && link != null && description != null) { var page = new NewsPageViewModel(serviceProvider) { Title = title, Url = link, Description = description, Date = date }; result.Add(page); ++count; } } } } catch (Exception) { result.Clear(); } return(result); }