PageRenderTime 50ms CodeModel.GetById 2ms app.highlight 41ms RepoModel.GetById 2ms app.codeStats 0ms

/BlogEngine/DotNetSlave.BusinessLogic/Providers/XmlProvider/Posts.cs

#
C# | 377 lines | 259 code | 58 blank | 60 comment | 42 complexity | e2ef41226b644913c292860a6a531aea MD5 | raw file
  1namespace BlogEngine.Core.Providers
  2{
  3    using System;
  4    using System.Collections.Generic;
  5    using System.Globalization;
  6    using System.IO;
  7    using System.Linq;
  8    using System.Web;
  9    using System.Xml;
 10
 11    /// <summary>
 12    /// A storage provider for BlogEngine that uses XML files.
 13    ///     <remarks>
 14    /// To build another provider, you can just copy and modify
 15    ///         this one. Then add it to the web.config's BlogEngine section.
 16    ///     </remarks>
 17    /// </summary>
 18    public partial class XmlBlogProvider : BlogProvider
 19    {
 20        // private static string _Folder = System.Web.HttpContext.Current.Server.MapPath(BlogSettings.Instance.StorageLocation);
 21        #region Properties
 22
 23        /// <summary>
 24        ///     Gets the storage folder of the current blog instance.
 25        /// </summary>
 26        internal string Folder
 27        {
 28            get
 29            {
 30                return GetFolder(Blog.CurrentInstance);
 31            }
 32        }
 33
 34        /// <summary>
 35        ///     Gets the storage folder for the blog.
 36        /// </summary>
 37        internal string GetFolder(Blog blog)
 38        {
 39            // if "blog" == null, this means it's the primary instance being asked for -- which
 40            // is in the root of BlogConfig.StorageLocation.
 41            string location = blog == null ? BlogConfig.StorageLocation : blog.StorageLocation;
 42            var p = location.Replace("~/", string.Empty);
 43            return Path.Combine(HttpRuntime.AppDomainAppPath, p);
 44        }
 45
 46        #endregion
 47
 48        #region Public Methods
 49
 50        /// <summary>
 51        /// Deletes a post from the data store.
 52        /// </summary>
 53        /// <param name="post">
 54        /// The post to delete.
 55        /// </param>
 56        public override void DeletePost(Post post)
 57        {
 58            var fileName = string.Format("{0}posts{1}{2}.xml", this.Folder, Path.DirectorySeparatorChar, post.Id);
 59            if (File.Exists(fileName))
 60            {
 61                File.Delete(fileName);
 62            }
 63        }
 64
 65        /// <summary>
 66        /// Retrieves all posts from the data store
 67        /// </summary>
 68        /// <returns>
 69        /// List of Posts
 70        /// </returns>
 71        public override List<Post> FillPosts()
 72        {
 73            var folder = this.Folder + "posts" + Path.DirectorySeparatorChar;
 74            var posts = (from file in Directory.GetFiles(folder, "*.xml", SearchOption.TopDirectoryOnly)
 75                         select new FileInfo(file)
 76                         into info
 77                         select info.Name.Replace(".xml", string.Empty)
 78                         into id
 79                         select Post.Load(new Guid(id))).ToList();
 80
 81            posts.Sort();
 82            return posts;
 83        }
 84
 85        /// <summary>
 86        /// Inserts a new Post to the data store.
 87        /// </summary>
 88        /// <param name="post">
 89        /// The post to insert.
 90        /// </param>
 91        public override void InsertPost(Post post)
 92        {
 93            if (!Directory.Exists(string.Format("{0}posts", this.Folder)))
 94            {
 95                Directory.CreateDirectory(string.Format("{0}posts", this.Folder));
 96            }
 97
 98            var fileName = string.Format("{0}posts{1}{2}.xml", this.Folder, Path.DirectorySeparatorChar, post.Id);
 99            var settings = new XmlWriterSettings { Indent = true };
100
101            var ms = new MemoryStream();
102
103            using (var writer = XmlWriter.Create(ms, settings))
104            {
105                writer.WriteStartDocument(true);
106                writer.WriteStartElement("post");
107
108                writer.WriteElementString("author", post.Author);
109                writer.WriteElementString("title", post.Title);
110                writer.WriteElementString("description", post.Description);
111                writer.WriteElementString("content", post.Content);
112                writer.WriteElementString("ispublished", post.IsPublished.ToString());
113                writer.WriteElementString("isdeleted", post.IsDeleted.ToString());
114                writer.WriteElementString("iscommentsenabled", post.HasCommentsEnabled.ToString());
115                writer.WriteElementString(
116                    "pubDate", 
117                    post.DateCreated.AddHours(-BlogSettings.Instance.Timezone).ToString(
118                        "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture));
119                writer.WriteElementString(
120                    "lastModified", 
121                    post.DateModified.AddHours(-BlogSettings.Instance.Timezone).ToString(
122                        "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture));
123                writer.WriteElementString("raters", post.Raters.ToString(CultureInfo.InvariantCulture));
124                writer.WriteElementString("rating", post.Rating.ToString(CultureInfo.InvariantCulture));
125                writer.WriteElementString("slug", post.Slug);
126
127                // Tags
128                writer.WriteStartElement("tags");
129                foreach (var tag in post.Tags)
130                {
131                    writer.WriteElementString("tag", tag);
132                }
133
134                writer.WriteEndElement();
135
136                // comments
137                writer.WriteStartElement("comments");
138                foreach (var comment in post.AllComments)
139                {
140                    writer.WriteStartElement("comment");
141                    writer.WriteAttributeString("id", comment.Id.ToString());
142                    writer.WriteAttributeString("parentid", comment.ParentId.ToString());
143                    writer.WriteAttributeString("approved", comment.IsApproved.ToString());
144                    writer.WriteAttributeString("spam", comment.IsSpam.ToString());
145                    writer.WriteAttributeString("deleted", comment.IsDeleted.ToString());
146
147                    writer.WriteElementString(
148                        "date", 
149                        comment.DateCreated.AddHours(-BlogSettings.Instance.Timezone).ToString(
150                            "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture));
151                    writer.WriteElementString("author", comment.Author);
152                    writer.WriteElementString("email", comment.Email);
153                    writer.WriteElementString("country", comment.Country);
154                    writer.WriteElementString("ip", comment.IP);
155
156                    if (comment.Website != null)
157                    {
158                        writer.WriteElementString("website", comment.Website.ToString());
159                    }
160
161                    if (!string.IsNullOrEmpty(comment.ModeratedBy))
162                    {
163                        writer.WriteElementString("moderatedby", comment.ModeratedBy);
164                    }
165
166                    if (comment.Avatar != null)
167                    {
168                        writer.WriteElementString("avatar", comment.Avatar);
169                    }
170
171                    writer.WriteElementString("content", comment.Content);
172
173                    writer.WriteEndElement();
174                }
175
176                writer.WriteEndElement();
177
178                // categories
179                writer.WriteStartElement("categories");
180                foreach (var cat in post.Categories)
181                {
182                    // if (cat.Id = .Instance.ContainsKey(key))
183                    // writer.WriteElementString("category", key.ToString());
184                    writer.WriteElementString("category", cat.Id.ToString());
185                }
186
187                writer.WriteEndElement();
188
189                // Notification e-mails
190                writer.WriteStartElement("notifications");
191                foreach (var email in post.NotificationEmails)
192                {
193                    writer.WriteElementString("email", email);
194                }
195
196                writer.WriteEndElement();
197
198                writer.WriteEndElement();
199            }
200
201            using (var fs = File.Open(fileName, FileMode.Create, FileAccess.Write))
202            {
203                ms.WriteTo(fs);
204                ms.Dispose();
205            }
206        }
207
208        /// <summary>
209        /// Retrieves a Post from the provider based on the specified id.
210        /// </summary>
211        /// <param name="id">
212        /// The Post id.
213        /// </param>
214        /// <returns>
215        /// A Post object.
216        /// </returns>
217        public override Post SelectPost(Guid id)
218        {
219            var fileName = string.Format("{0}posts{1}{2}.xml", this.Folder, Path.DirectorySeparatorChar, id);
220            var post = new Post();
221            var doc = new XmlDocument();
222            doc.Load(fileName);
223
224            post.Title = doc.SelectSingleNode("post/title").InnerText;
225            post.Description = doc.SelectSingleNode("post/description").InnerText;
226            post.Content = doc.SelectSingleNode("post/content").InnerText;
227
228            if (doc.SelectSingleNode("post/pubDate") != null)
229            {
230                post.DateCreated = DateTime.Parse(
231                    doc.SelectSingleNode("post/pubDate").InnerText, CultureInfo.InvariantCulture);
232            }
233
234            if (doc.SelectSingleNode("post/lastModified") != null)
235            {
236                post.DateModified = DateTime.Parse(
237                    doc.SelectSingleNode("post/lastModified").InnerText, CultureInfo.InvariantCulture);
238            }
239
240            if (doc.SelectSingleNode("post/author") != null)
241            {
242                post.Author = doc.SelectSingleNode("post/author").InnerText;
243            }
244
245            if (doc.SelectSingleNode("post/ispublished") != null)
246            {
247                post.IsPublished = bool.Parse(doc.SelectSingleNode("post/ispublished").InnerText);
248            }
249
250            if (doc.SelectSingleNode("post/isdeleted") != null)
251            {
252                post.IsDeleted = bool.Parse(doc.SelectSingleNode("post/isdeleted").InnerText);
253            }
254
255            if (doc.SelectSingleNode("post/iscommentsenabled") != null)
256            {
257                post.HasCommentsEnabled = bool.Parse(doc.SelectSingleNode("post/iscommentsenabled").InnerText);
258            }
259
260            if (doc.SelectSingleNode("post/raters") != null)
261            {
262                post.Raters = int.Parse(doc.SelectSingleNode("post/raters").InnerText, CultureInfo.InvariantCulture);
263            }
264
265            if (doc.SelectSingleNode("post/rating") != null)
266            {
267                post.Rating = float.Parse(
268                    doc.SelectSingleNode("post/rating").InnerText, CultureInfo.GetCultureInfo("en-gb"));
269            }
270
271            if (doc.SelectSingleNode("post/slug") != null)
272            {
273                post.Slug = doc.SelectSingleNode("post/slug").InnerText;
274            }
275
276            // Tags
277            foreach (var node in
278                doc.SelectNodes("post/tags/tag").Cast<XmlNode>().Where(node => !string.IsNullOrEmpty(node.InnerText)))
279            {
280                post.Tags.Add(node.InnerText);
281            }
282
283            // comments
284            foreach (XmlNode node in doc.SelectNodes("post/comments/comment"))
285            {
286                var comment = new Comment
287                    {
288                        Id = new Guid(node.Attributes["id"].InnerText), 
289                        ParentId =
290                            (node.Attributes["parentid"] != null)
291                                ? new Guid(node.Attributes["parentid"].InnerText)
292                                : Guid.Empty, 
293                        Author = node.SelectSingleNode("author").InnerText, 
294                        Email = node.SelectSingleNode("email").InnerText, 
295                        Parent = post
296                    };
297
298                if (node.SelectSingleNode("country") != null)
299                {
300                    comment.Country = node.SelectSingleNode("country").InnerText;
301                }
302
303                if (node.SelectSingleNode("ip") != null)
304                {
305                    comment.IP = node.SelectSingleNode("ip").InnerText;
306                }
307
308                if (node.SelectSingleNode("website") != null)
309                {
310                    Uri website;
311                    if (Uri.TryCreate(node.SelectSingleNode("website").InnerText, UriKind.Absolute, out website))
312                    {
313                        comment.Website = website;
314                    }
315                }
316
317                if (node.SelectSingleNode("moderatedby") != null)
318                {
319                    comment.ModeratedBy = node.SelectSingleNode("moderatedby").InnerText;
320                }
321
322                comment.IsApproved = node.Attributes["approved"] == null ||
323                                     bool.Parse(node.Attributes["approved"].InnerText);
324
325                if (node.SelectSingleNode("avatar") != null)
326                {
327                    comment.Avatar = node.SelectSingleNode("avatar").InnerText;
328                }
329
330                comment.IsSpam = node.Attributes["spam"] == null ? false : 
331                                    bool.Parse(node.Attributes["spam"].InnerText);
332
333                comment.IsDeleted = node.Attributes["deleted"] == null ? false : 
334                                    bool.Parse(node.Attributes["deleted"].InnerText);
335
336                comment.Content = node.SelectSingleNode("content").InnerText;
337                comment.DateCreated = DateTime.Parse(
338                    node.SelectSingleNode("date").InnerText, CultureInfo.InvariantCulture);
339
340                post.AllComments.Add(comment);
341            }
342
343            post.AllComments.Sort();
344
345            // categories
346            foreach (var cat in from XmlNode node in doc.SelectNodes("post/categories/category")
347                                select new Guid(node.InnerText)
348                                into key select Category.GetCategory(key)
349                                into cat where cat != null select cat)
350            {
351                // CategoryDictionary.Instance.ContainsKey(key))
352                post.Categories.Add(cat);
353            }
354
355            // Notification e-mails
356            foreach (XmlNode node in doc.SelectNodes("post/notifications/email"))
357            {
358                post.NotificationEmails.Add(node.InnerText);
359            }
360
361            return post;
362        }
363
364        /// <summary>
365        /// Updates an existing Post in the data store specified by the provider.
366        /// </summary>
367        /// <param name="post">
368        /// The post to update.
369        /// </param>
370        public override void UpdatePost(Post post)
371        {
372            this.InsertPost(post);
373        }
374
375        #endregion
376    }
377}