using System.Configuration; using MongoDB.Driver; namespace Core.Helpers { public class MongoHelper<T> where T : class { public MongoCollection<T> Collection { get; private set; } public MongoHelper() { var con = new MongoConnectionStringBuilder(ConfigurationManager.ConnectionStrings["MongoDB"].ConnectionString); var server = MongoServer.Create(con); var db = server.GetDatabase(con.DatabaseName); Collection = db.GetCollection<T>(typeof(T).Name.ToLower()); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web.Mvc; using MongoDB.Bson; using System.ComponentModel.DataAnnotations; using MongoDB.Bson.Serialization.Attributes; namespace Core.Domain { [BsonIgnoreExtraElements] public class Post { [ScaffoldColumn(false)] [BsonId] public ObjectId PostId { get; set; } [ScaffoldColumn(false)] public DateTime Date { get; set; } [Required] public string Title { get; set; } [ScaffoldColumn(false)] public string Url { get; set; } [Required] public string Summary { get; set; } [UIHint("WYSIWYG")] [AllowHtml] public string Details { get; set; } [ScaffoldColumn(false)] public string Author { get; set; } [ScaffoldColumn(false)] public int TotalComments { get; set; } [ScaffoldColumn(false)] public IList<Comment> Comments { get; set; } } }
using System; using System.Collections.Generic; using System.Configuration; using System.Globalization; using System.Linq; using System.Text; using MongoDB.Driver; using Core.Domain; using MongoDB.Driver.Builders; using MongoDB.Bson; using System.Text.RegularExpressions; using System.Web; using Core.Helpers; using System.Diagnostics; namespace Core.Services { public class PostService { private readonly MongoHelper<Post> _posts; public PostService() { _posts = new MongoHelper<Post>(); } public void Create(Post post) { post.Comments = new List<Comment>(); _posts.Collection.Save(post); } public void Edit(Post post) { _posts.Collection.Update( Query.EQ("_id", post.PostId), Update.Set("Title", post.Title) .Set("Url", post.Url) .Set("Summary", post.Summary) .Set("Details", post.Details)); } public void Delete(ObjectId postId) { _posts.Collection.Remove(Query.EQ("_id", postId)); } public IList<Post> GetPosts() { return _posts.Collection.FindAll().SetFields(Fields.Exclude("Comments")).SetSortOrder(SortBy.Descending("Date")).ToList(); } public Post GetPost(ObjectId id) { var post = _posts.Collection.Find(Query.EQ("_id", id)).SetFields(Fields.Slice("Comments", -5)).Single(); post.Comments = post.Comments.OrderByDescending(c => c.Date).ToList(); return post; } public Post GetPost(string url) { var post = _posts.Collection.Find(Query.EQ("Url", url)).SetFields(Fields.Slice("Comments", -5)).Single(); post.Comments = post.Comments.OrderByDescending(c => c.Date).ToList(); return post; } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Web; using System.Web.Mvc; using Core.Domain; using Core.Services; using MongoDBTutorial.Helpers; using MongoDB.Bson; namespace MongoDBTutorial.Controllers { public class PostController : Controller { private readonly PostService _postService; private readonly CommentService _commentService; public PostController() { _postService = new PostService(); _commentService = new CommentService(); } public ActionResult Index() { return View(_postService.GetPosts()); } [HttpGet] public ActionResult Create() { return View(new Post()); } [HttpPost] public ActionResult Create(Post post) { if (ModelState.IsValid) { post.Url = post.Title.GenerateSlug(); post.Author = User.Identity.Name; post.Date = DateTime.Now; _postService.Create(post); return RedirectToAction("Index"); } return View(); } [HttpGet] public ActionResult Update(string id) { return View(_postService.GetPost(id)); } [HttpGet] public ActionResult Delete(ObjectId id) { return View(_postService.GetPost(id)); } [HttpPost, ActionName("Delete")] public ActionResult ConfirmDelete(ObjectId id) { _postService.Delete(id); return RedirectToAction("Index"); } [HttpPost] public ActionResult Update(Post post) { if (ModelState.IsValid) { post.Url = post.Title.GenerateSlug(); _postService.Edit(post); return RedirectToAction("Index"); } return View(); } [HttpGet] public ActionResult Detail(string id) { var post = _postService.GetPost(id); ViewBag.PostId = post.PostId; ViewBag.TotalComments = post.TotalComments; ViewBag.LoadedComments = 5; return View(post); } [HttpPost] public ActionResult AddComment(ObjectId postId, Comment comment) { if (ModelState.IsValid) { var newComment = new Comment() { CommentId = ObjectId.GenerateNewId(), Author = User.Identity.Name, Date = DateTime.Now, Detail = comment.Detail }; _commentService.AddComment(postId, newComment); ViewBag.PostId = postId; return Json( new { Result = "ok", CommentHtml = RenderPartialViewToString("Comment", newComment), FormHtml = RenderPartialViewToString("AddComment", new Comment()) }); } ViewBag.PostId = postId; return Json( new { Result = "fail", FormHtml = RenderPartialViewToString("AddComment", comment) }); } public ActionResult RemoveComment(ObjectId postId, ObjectId commentId) { _commentService.RemoveComment(postId, commentId); return new EmptyResult(); } [HttpPost] public ActionResult CommentList(ObjectId postId, int skip, int limit, int totalComments) { ViewBag.TotalComments = totalComments; ViewBag.LoadedComments = skip + limit; return PartialView(_commentService.GetComments(postId, ViewBag.LoadedComments, limit, totalComments)); } /// <summary> /// </summary> /// <param name="viewName"></param> /// <param name="model"></param> /// <returns></returns> protected string RenderPartialViewToString(string viewName, object model) { if (string.IsNullOrEmpty(viewName)) viewName = ControllerContext.RouteData.GetRequiredString("action"); ViewData.Model = model; using (StringWriter sw = new StringWriter()) { ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName); ViewContext viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw); viewResult.View.Render(viewContext, sw); return sw.GetStringBuilder().ToString(); } } } }