using System;
using System.Configuration;
using System.Linq;
using System.Net.Mail;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.WebPages;
public class CommentHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
Post post = Storage.GetAllPosts().SingleOrDefault(p => p.ID == context.Request["postId"]);
if (post == null)
throw new HttpException(404, "The post does not exist");
string mode = context.Request["mode"];
if (mode == "save" && context.Request.HttpMethod == "POST" && post.AreCommentsOpen(new HttpContextWrapper(context)) && Blog.MatchesUniqueId(context))
{
Save(context, post);
}
else if (mode == "delete")
{
Delete(context, post);
}
else if (mode == "approve")
{
Approve(context, post);
}
}
private static void Save(HttpContext context, Post post)
{
string name = context.Request.Form["name"];
string email = context.Request.Form["email"];
string website = context.Request.Form["website"];
string content = context.Request.Form["content"];
Validate(name, email, content);
Comment comment = new Comment()
{
Author = name.Trim(),
Email = email.Trim(),
Website = GetUrl(website),
Ip = context.Request.UserHostAddress,
UserAgent = context.Request.UserAgent,
IsAdmin = context.User.Identity.IsAuthenticated,
Content = HttpUtility.HtmlEncode(content.Trim()).Replace("\n", "
"),
IsApproved = !Blog.ModerateComments,
};
post.Comments.Add(comment);
Storage.Save(post);
if (!context.User.Identity.IsAuthenticated)
System.Threading.ThreadPool.QueueUserWorkItem((s) => SendEmail(comment, post, context.Request));
RenderComment(context, comment);
}
private static void RenderComment(HttpContext context, Comment comment)
{
var page = (WebPage)WebPageBase.CreateInstanceFromVirtualPath("~/themes/" + Blog.Theme + "/comment.cshtml");
page.Context = new HttpContextWrapper(context);
page.ExecutePageHierarchy(new WebPageContext(page.Context, page: null, model: comment), context.Response.Output);
}
private static void SendEmail(Comment comment, Post post, HttpRequest request)
{
try
{
MailMessage mail = new MailMessage();
mail.From = new MailAddress(comment.Email, comment.Author);
mail.ReplyToList.Add(comment.Email);
mail.To.Add(ConfigurationManager.AppSettings.Get("blog:email"));
mail.Subject = "Blog comment: " + post.Title;
mail.IsBodyHtml = true;
string absoluteUrl = request.Url.Scheme + "://" + request.Url.Authority;
string deleteUrl = absoluteUrl + request.RawUrl + "?postId=" + post.ID + "&commentId=" + comment.ID + "&mode=delete";
string approveUrl = absoluteUrl + request.RawUrl + "?postId=" + post.ID + "&commentId=" + comment.ID + "&mode=approve";
mail.Body = "