PageRenderTime 42ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/QDFeedParser/FileSystemFeedFactory.cs

#
C# | 73 lines | 51 code | 16 blank | 6 comment | 2 complexity | 6f97506a70fc06785f86c37f303407ad MD5 | raw file
  1. using System;
  2. using System.IO;
  3. using QDFeedParser.Xml;
  4. namespace QDFeedParser
  5. {
  6. public partial class FileSystemFeedFactory : BaseFeedFactory
  7. {
  8. public FileSystemFeedFactory()
  9. : this(new LinqFeedXmlParser())
  10. { }
  11. public FileSystemFeedFactory(IFeedXmlParser parser)
  12. : this(parser, null)
  13. { }
  14. public FileSystemFeedFactory(IFeedInstanceProvider instanceProvider)
  15. : this(new LinqFeedXmlParser(), instanceProvider)
  16. { }
  17. public FileSystemFeedFactory(IFeedXmlParser parser, IFeedInstanceProvider instanceProvider)
  18. : base(parser, instanceProvider)
  19. { }
  20. public override bool PingFeed(Uri feeduri)
  21. {
  22. return File.Exists(feeduri.LocalPath);
  23. }
  24. public override string DownloadXml(Uri feeduri)
  25. {
  26. if (!this.PingFeed(feeduri)) throw new MissingFeedException(string.Format("Was unable to open local XML file {0}", feeduri.LocalPath));
  27. return DownloadXmlFromUri(feeduri).FeedContent;
  28. }
  29. //Hacking asynchronous file IO just to make the interface consistent - there's not much performance benefit otheriwse
  30. public override IAsyncResult BeginDownloadXml(Uri feeduri, AsyncCallback callback)
  31. {
  32. if (!this.PingFeed(feeduri)) throw new MissingFeedException(string.Format("Was unable to open local XML file {0}", feeduri.LocalPath));
  33. return FeedWorkerDelegate.BeginInvoke(feeduri, callback, new FeedTuple());
  34. }
  35. public override FeedTuple EndDownloadXml(IAsyncResult asyncResult)
  36. {
  37. var result = FeedWorkerDelegate.EndInvoke(asyncResult);
  38. return result;
  39. }
  40. protected readonly FileIOWorker FeedWorkerDelegate = new FileIOWorker(DownloadXmlFromUri);
  41. protected delegate FeedTuple FileIOWorker(Uri feeduri);
  42. /// <summary>
  43. /// Requires a valid uri on local disk - otherwise the method will promptly fail.
  44. /// </summary>
  45. /// <param name="feeduri">A valid uri on local disk</param>
  46. /// <returns>The xml content of the uri</returns>
  47. protected static FeedTuple DownloadXmlFromUri(Uri feeduri)
  48. {
  49. string xmlContent;
  50. using (var reader = new StreamReader(feeduri.OriginalString))
  51. {
  52. xmlContent = reader.ReadToEnd();
  53. }
  54. return new FeedTuple { FeedContent = xmlContent, FeedUri = feeduri };
  55. }
  56. }
  57. }