PageRenderTime 6ms CodeModel.GetById 2ms app.highlight 2ms RepoModel.GetById 1ms app.codeStats 0ms

/QDFeedParser/FileSystemFeedFactory.cs

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