using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Xml.Linq; using Luticate2.Utils.Dbo.Result; using VDS.RDF; using WebApiWebSem.Dbo.Feed; namespace WebApiWebSem.DataAccess { public class FeedDataAccess { public LuResult> Parse(string url) { try { using (var client = new HttpClient()) { var request = new HttpRequestMessage(HttpMethod.Get, url); var responseTask = client.SendAsync(request); responseTask.Wait(); using (var response = responseTask.Result) { var streamTask = response.Content.ReadAsStreamAsync(); streamTask.Wait(); using (var stream = streamTask.Result) { var doc = XDocument.Load(stream); var entries = from item in doc.Root.Descendants() .First(i => i.Name.LocalName == "channel") .Elements() .Where(i => i.Name.LocalName == "item") select new FeedDbo { Content = item.Elements().First(i => i.Name.LocalName == "description").Value, Link = item.Elements().First(i => i.Name.LocalName == "link").Value, PublishDate = ParseDate( item.Elements().First(i => i.Name.LocalName == "pubDate").Value), Title = item.Elements().First(i => i.Name.LocalName == "title").Value }; return LuResult>.Ok(entries.ToList()); } } } } catch (Exception e) { return LuResult>.Error(LuStatus.BackendError, e, "Failed to read remote RSS feed"); } } private DateTime ParseDate(string date) { DateTime result; if (DateTime.TryParse(date, out result)) return result; return DateTime.MinValue; } } }