using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Xml.Linq; namespace ChadSoft.Edificator { internal class XmlWisdomHistory : WisdomHistoryBase { private const string HistoryFilename = "history.xml"; private readonly XElement _historyElement; public XmlWisdomHistory() { _historyElement = XElement.Load(HistoryFilename); Debug.WriteLine("Loaded history file " + HistoryFilename); } public override bool HasBeenSentRecently(WisdomBit wisdom) { string url = GetUrl(wisdom); IEnumerable sentHistoryTimeStamps = from history in _historyElement.Descendants("history") where url.Equals(history.Attribute("url").Value, StringComparison.OrdinalIgnoreCase) let timestamp = history.Attribute("timestamp") where timestamp != null orderby timestamp.Value descending select timestamp.Value; if(sentHistoryTimeStamps.Count() == 0) { Debug.WriteLine(string.Format("Wisdom Url {0} has never been sent before.", url)); return false; } string lastDateString = sentHistoryTimeStamps.OrderByDescending(x => x).First(); DateTime lastSentDate = DateTime.Parse(lastDateString); TimeSpan timeSinceLastSent = DateTime.Now - lastSentDate; bool hasBeenSentRecently = timeSinceLastSent < RecentlySentTimespan; Debug.WriteLine(string.Format("Wisdom Url {0} has been sent recently: [{1}]\tLast Sent: {2}\tTime Since Last Sent: {3}", url, hasBeenSentRecently, lastSentDate, timeSinceLastSent)); return hasBeenSentRecently; } public override void WisdomSent(WisdomBit wisdom) { string elementText = string.Format("", GetUrl(wisdom), DateTime.Now); XElement newHistoryElement = XElement.Parse(elementText); _historyElement.Add(newHistoryElement); _historyElement.Save(HistoryFilename); Debug.WriteLine("Wisdom saved to history: " + elementText); } private static string GetUrl(WisdomBit wisdom) { return wisdom.Uri.AbsoluteUri; } } }