(All original content on this site is licensed under the Creative Commons License Attribution-Noncommercial-No Derivative Works 3.0.)

Determine BlogEngine.NET comments that haven't been published

Unfortunately, BlogEngine.NET doesn't currently have a very good way to determine, at a glance, all of the comments that haven't been approved. While this will certainly be coming in a future release, or as an extension, I figured writing something simple to do this would be a good LINQ to XML test for me.

You can download the built executable, or play with the code, which is included below.

Download the executable (7-Zip format). Requires .NET Framework 3.5.

The form I created consisted of a TextBox, Button, and a DataGridView, with the default names.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml.Linq;

namespace TestBlogEngine {
	public partial class Form1 : Form {
		public Form1() {
			InitializeComponent();
		}

		private void button1_Click(object sender, EventArgs e) {
			OpenFileDialog sampleFile = new OpenFileDialog();
			sampleFile.Filter = "xml files (*.xml)|*.xml|All files (*.*)|*.*";

			if (sampleFile.ShowDialog() == DialogResult.OK) {
				textBox1.Text = sampleFile.FileName;

				string postsDirectory = System.IO.Path.GetDirectoryName(sampleFile.FileName);
				sampleFile.Dispose();

				string[] postFiles = System.IO.Directory.GetFiles(postsDirectory);

				DataTable comments = new DataTable();
				comments.Columns.Add("Post");
				comments.Columns.Add("CommentApproved");
				comments.Columns.Add("FileId");

				XDocument postXml;

				foreach (string postFile in postFiles) {
					postXml = XDocument.Load(postFile);

					var posts = from postData in postXml.Descendants("post")
						select new {
							Title = postData.Element("title").Value,
							CommentItems = (from commentItems in postData.Element("comments").Elements("comment")
								select commentItems).ToList()
						};

					foreach (var post in posts) {
						if (post.CommentItems.Count > 0) {
							foreach (var commentItem in post.CommentItems) {
								if (commentItem.Attribute("approved") != null && commentItem.Attribute("approved").Value == "False") {
									DataRow comment = comments.NewRow();
									comment["Post"] = post.Title;
									comment["CommentApproved"] = commentItem.Attribute("approved").Value;
									comment["FileId"] = "/post.aspx?id=" + System.IO.Path.GetFileNameWithoutExtension(postFile);
									comments.Rows.Add(comment);
								}
							}

						}
					}
				}

				postXml = null;

				dataGridView1.DataSource = comments;

			}
		}
	}
}

EDIT: Scott Guthrie's excellent Using LINQ to XML (and how to build a custom RSS Feed Reader with it) is the article that I keep going back to when I forget LINQ to XML basics.

blog comments powered by Disqus

Archives