public void EditPost(Post post, PostEdit postEdit, User editingUser) { // TODO: text parsing is controller for new topic and replies, see issue #121 https://github.com/POPWorldMedia/POPForums/issues/121 // TODO: also not checking for empty posts var oldText = post.FullText; post.Title = _textParsingService.Censor(postEdit.Title); if (postEdit.IsPlainText) { post.FullText = _textParsingService.ForumCodeToHtml(postEdit.FullText); } else { post.FullText = _textParsingService.ClientHtmlToHtml(postEdit.FullText); } post.ShowSig = postEdit.ShowSig; post.LastEditTime = DateTime.UtcNow; post.LastEditName = editingUser.Name; post.IsEdited = true; _postRepository.Update(post); _moderationLogService.LogPost(editingUser, ModerationType.PostEdit, post, postEdit.Comment, oldText); _searchIndexQueueRepository.Enqueue(new SearchIndexPayload { TenantID = _tenantService.GetTenant(), TopicID = post.TopicID }); }
public async Task <ActionResult> EditPost(string id, [FromBody] PostEdit model) { try { var entity = _mapper.Map <Post>(model); entity.Id = id; entity.AuthorId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value; entity.CreatedAt = DateTime.Now; await _postService.Update(entity); if (model.CategoriesId.Any()) { List <Post_Category> post_Categories = model.CategoriesId.Select(x => new Post_Category { CategoryId = x, PostId = entity.Id }).ToList(); await _post_CategoryService.EditRange(post_Categories); } return(NoContent()); } catch (Exception ex) { _logger.LogCritical(ex.Message); return(BadRequest()); } }
public ActionResult Edit(int id, PostEdit model) { if (!ModelState.IsValid) { return(View(model)); } if (model.PostID != id) { ModelState.AddModelError("", "ID Mismatch"); return(View(model)); } var service = CreatePostService(); if (service.UpdatePost(model)) { TempData["SaveResult"] = "Your post was updated."; return(RedirectToAction("ThreadIndex", "Post", new { postID = model.PostID })); //return RedirectToAction("Index"); } ModelState.AddModelError("", "Your post could not be updated."); return(View(model)); }
public PostEdit GetPostForEdit(Post post, User user, bool isMobile) { if (post == null) { throw new ArgumentNullException("post"); } if (user == null) { throw new ArgumentNullException("user"); } var profile = _profileRepository.GetProfile(user.UserID); var postEdit = new PostEdit(post) { IsPlainText = profile.IsPlainText }; if (profile.IsPlainText || isMobile) { postEdit.FullText = _textParsingService.HtmlToForumCode(post.FullText); postEdit.IsPlainText = true; } else { postEdit.FullText = _textParsingService.HtmlToClientHtml(post.FullText); } return(postEdit); }
public ActionResult Create(PermissionArea Area, ApType ApType, PostEdit PostEdit) { if (!ModelState.IsValid) { ViewData["Post"] = PostEdit; ViewData["Salt"] = "PostCreate"; return View("Form" + ApType.ToProper(), Area); } ////////////////////////// // Everything passed. Create new post ////////////////////////// var post = Mapper.Map<PostEdit, Post>(PostEdit); middleManagement.Post.Add(post); ////////////////////////// // Send user to new post ////////////////////////// return RedirectToAction("View", "Blog", new { postid = post.ID, title = post.Title.ToUrlFriendly() }); }
public async Task <PostEdit> GetPostForEdit(Post post, User user) { if (post == null) { throw new ArgumentNullException("post"); } if (user == null) { throw new ArgumentNullException("user"); } var profile = await _profileRepository.GetProfile(user.UserID); var postEdit = new PostEdit(post) { IsPlainText = profile.IsPlainText, IsFirstInTopic = post.IsFirstInTopic }; if (profile.IsPlainText) { postEdit.FullText = _textParsingService.HtmlToForumCode(post.FullText); postEdit.IsPlainText = true; } else { postEdit.FullText = _textParsingService.HtmlToClientHtml(post.FullText); } return(postEdit); }
public ActionResult Edit(int postID, PostEdit model) { if (!ModelState.IsValid) { return(View(model)); } if (model.PostID != postID) { ModelState.AddModelError("", "ID Mismatch"); return(View(model)); } var service = CreatePostService(); var detail = service.GetPostByID(postID); if (service.UpdatePost(model)) { TempData["SaveResult"] = "Your post was updated."; return(RedirectToAction("ThreadPostsIndex", new { threadID = detail.ThreadID })); } ModelState.AddModelError("", "Your post could not be updated."); return(View(model)); }
// Post: Admin/Post/Edit/id public virtual ActionResult Edit(int id, PostEdit postEdit) { if (!ModelState.IsValid) { postEdit.TagList = _tagService.DropDownList(postEdit.TagIds); postEdit.CategoryList = _categoryService.DropDownList(postEdit.CategoryIds); return(View(postEdit)); } HttpPostedFileBase file = Request.Files["user-avatar"]; if (string.IsNullOrEmpty(file.FileName)) { var post = _postService.Find(id); postEdit.TitleImg = post.TitleImg; } else { var path = Path.Combine(Server.MapPath("~/Content/upload/images/"), file.FileName); file.SaveAs(path); postEdit.TitleImg = file.FileName; } _postService.Update(postEdit, id); _uow.SaveAllChanges(); return(RedirectToAction("Index"));; }
public ActionResult Edit(int id, PostEdit model) { var db = new ArtistService(); ViewBag.ArtistID = new SelectList(db.GetArtists().ToList(), "ArtistID", "ArtistName", model.ArtistID); var service = CreatePostService(); var detail = service.GetPostbyID(id); var modelPrevious = new PostEdit { Files = detail.Files, }; model.Files = modelPrevious.Files; model.PhotoId = detail.PhotoId; if (!ModelState.IsValid) { return(View(model)); } if (model.PostID != id) { ModelState.AddModelError("", "Id Mismatch"); return(View(model)); } if (service.UpdatePost(model)) { TempData["SaveResult"] = "The post was updated."; return(RedirectToAction("Index")); } ModelState.AddModelError("", "The post could not be saved. Either no changes were made or fields have been filled out incorrectly."); return(View(model)); }
public ActionResult Edit(int id, PostEdit postEdit, HttpPostedFileBase UploadFile) { var post = _postService.Get(id); if (!User.IsPostEditable(post)) { return(this.Forbidden("Forbidden", null)); } if (UploadFile != null && UploadFile.ContentLength > 0) { string path = AppDomain.CurrentDomain.BaseDirectory + "/UploadFiles/"; string filename = post.PostTime.ToString("yyyyMMddHHmmss"); string extension = Path.GetExtension(UploadFile.FileName); if (!string.IsNullOrEmpty(post.FileUrl)) { // Delete exiting file System.IO.File.Delete(Path.Combine(path, post.FileUrl)); } post.FileUrl = filename + extension; UploadFile.SaveAs(Path.Combine(path, filename + extension)); } post.IsAnonymous = postEdit.IsAnonymous; _postService.EditPost(post, postEdit, this.CurrentUser()); return(RedirectToAction("PostLink", new { id = post.PostID })); }
public async Task <BasicServiceResponse <Post> > EditPost(int postID, PostEdit postEdit, User editingUser, Func <Post, string> redirectLinkGenerator) { var censoredNewTitle = _textParsingService.Censor(postEdit.Title); var post = await _postRepository.Get(postID); if (!editingUser.IsPostEditable(post)) { return(GetReplyFailMessage(Resources.Forbidden)); } var oldText = post.FullText; if (post.IsFirstInTopic && post.Title != censoredNewTitle) { if (string.IsNullOrEmpty(censoredNewTitle)) { return(GetReplyFailMessage(Resources.PostEmpty)); } var oldTitle = post.Title; post.Title = censoredNewTitle; var topic = await _topicRepository.Get(post.TopicID); var forum = await _forumRepository.Get(topic.ForumID); var urlName = censoredNewTitle.ToUniqueUrlName(await _topicRepository.GetUrlNamesThatStartWith(censoredNewTitle.ToUrlName())); await _topicRepository.UpdateTitleAndForum(topic.TopicID, forum.ForumID, censoredNewTitle, urlName); await _moderationLogService.LogTopic(editingUser, ModerationType.TopicRenamed, topic, forum, $"Old title: {oldTitle}"); } if (postEdit.IsPlainText) { post.FullText = _textParsingService.ForumCodeToHtml(postEdit.FullText); } else { post.FullText = _textParsingService.ClientHtmlToHtml(postEdit.FullText); } if (string.IsNullOrEmpty(postEdit.FullText)) { return(GetReplyFailMessage(Resources.PostEmpty)); } post.ShowSig = postEdit.ShowSig; post.LastEditTime = DateTime.UtcNow; post.LastEditName = editingUser.Name; post.IsEdited = true; await _postRepository.Update(post); await _moderationLogService.LogPost(editingUser, ModerationType.PostEdit, post, postEdit.Comment, oldText); await _searchIndexQueueRepository.Enqueue(new SearchIndexPayload { TenantID = _tenantService.GetTenant(), TopicID = post.TopicID }); var redirectLink = redirectLinkGenerator(post); return(new BasicServiceResponse <Post> { Data = post, IsSuccessful = true, Message = string.Empty, Redirect = redirectLink }); }
public IHttpActionResult UpdatePost([FromUri] int id, [FromBody] PostEdit model) { var service = CreatePostService(); if (!service.UpdatePostsById(id, model)) { return(InternalServerError()); } return(Ok()); }
public ActionResult Edit(int id, PostEdit postEdit) { var post = _postService.Get(id); if (!User.IsPostEditable(post)) { return(this.Forbidden("Forbidden", null)); } _postService.EditPost(post, postEdit, this.CurrentUser()); return(RedirectToAction("PostLink", new { id = post.PostID })); }
public async Task <IActionResult> OnPostAsync() { if (ModelState.IsValid) { var editingPost = await S.Db.Posts .Include(p => p.Edits) .Include(p => p.ModerationInfo) .Include(p => p.Author) .FirstOrDefaultAsync(p => p.Id == PostId); await S.Permissions.ValidateEditPostAsync(editingPost); var authorId = await S.Utilities.GetCurrentUserIdOrThrowAsync(); var author = await S.Db.Users .Include(u => u.ModeratorsInChargeGroup) .FirstOrDefaultAsync(u => u.Id == authorId); if (!await S.Permissions.CanEditPostTitleAsync(editingPost)) { Title = editingPost.Title; } var edit = new PostEdit(author, EditReason, DateTime.UtcNow, editingPost); var sanitizedBody = await S.Sanitizer.SanitizePostBodyAsync(Body); editingPost.Body = sanitizedBody; editingPost.Title = Title; editingPost.BodyPreview = getPostBodyPreview(sanitizedBody); editingPost.Edits.Add(edit); if (editingPost.ModerationInfo.State == ModerationState.MODERATION_NOT_PASSED) { editingPost.ModerationInfo.State = ModerationState.UNDER_MODERATION; editingPost.ModerationInfo.StateReasoning = "Post was edited"; author.ModeratorsInChargeGroup.AddEntityToCheck(editingPost, CheckReason.NEED_MODERATION); } else if (editingPost.ModerationInfo.State == ModerationState.MODERATED) { author.ModeratorsInChargeGroup.AddEntityToCheck(editingPost, CheckReason.CHECK_REQUIRED); } await S.Repository.AddUserActionAsync(author, new UserAction(ActionType.POST_EDITED, editingPost)); await S.Db.SaveChangesAsync(); await S.CacheManager.ResetPostPageCacheAsync(PostId); LayoutModel.AddMessage("Changes applied!"); return(RedirectToPage("/Post", new { id = editingPost.Id })); } else { return(Page()); } }
public bool UpdatePost(PostEdit model) { using (var ctx = new ApplicationDbContext()) { var entity = ctx.Posts.Single(e => e.PostId == model.PostId && e.AuthorId == _userId); entity.Title = model.Title; entity.Text = model.Text; entity.PostId = model.PostId; return(ctx.SaveChanges() == 1); } }
/// <summary> /// 修改岗位 /// </summary> /// <param name="post"></param> /// <returns></returns> public ActionResult <bool> EditPost(PostEdit post) { try { var dbpost = _rpspost.GetModel(p => p.ID == post.ID); if (dbpost == null) { throw new Exception("未找到所需修改的岗位"); } if (post.Org == Guid.Empty || post.Principal == Guid.Empty) { throw new Exception("请选择组织架构或负责人!"); } var check = _rpspost.Any(p => p.Name == post.Name && p.ID != post.ID); if (check) { throw new Exception("该岗位名已存在"); } var _dbpost = post.CopyTo <Basic_Post>(dbpost); //自定义项 usedefinedService.DeleteBusinessValue(_dbpost.ID); var definedvalue = new UserDefinedBusinessValue { BusinessID = _dbpost.ID, Values = post.UserDefineds }; var defined = usedefinedService.SaveBuisnessValue(definedvalue); if (defined.state != 200) { throw new Exception(defined.msg); } //文件 srvFile.DelFileByBusinessId(_dbpost.ID); var files = new AttachFileSave { BusinessID = _dbpost.ID, files = post.fileNews }; var file = srvFile.SaveFiles(files); if (file.state != 200) { throw new Exception(file.msg); } _rpspost.Update(_dbpost); _work.Commit(); return(new ActionResult <bool>(true)); } catch (Exception ex) { return(new ActionResult <bool>(ex)); } }
//EDIT POST public bool EditPost(PostEdit model) { using (var db = new ApplicationDbContext()) { var entity = db.Posts.Single(e => e.ID == model.ID && e.UserID == _userId); entity.Title = model.Title; entity.Body = model.Body; entity.TimeEdited = DateTimeOffset.Now; return(db.SaveChanges() == 1); } }
public bool UpdatedPost(PostEdit post) { using (var ctx = new ApplicationDbContext()) { var entity = ctx.Posts.Single(e => e.Id == post.PostId && e.Author == _userId); entity.Text = post.Text; entity.Title = post.Title; entity.ModifiedUtc = DateTimeOffset.UtcNow; return(ctx.SaveChanges() == 1); } }
public bool UpdatePost(PostEdit model) { var entity = _dbContext.Posts .Single(x => x.PostID == model.PostID); entity.PostContent = model.PostContent; // May add in future //entity.ModifiedUtc = DateTimeOffset.UtcNow; return(_dbContext.SaveChanges() == 1); }
// TODO: test validate [ValidateInput(false)] public ActionResult Edit(int id, PostEdit postEdit) { var post = _postService.Get(id); var user = _userRetrievalShim.GetUser(HttpContext); if (!user.IsPostEditable(post)) { return(Forbid()); } _postService.EditPost(post, postEdit, user); return(RedirectToAction("PostLink", new { id = post.PostID })); }
public ActionResult Edit(Guid id) { var service = CreatePostService(); var detail = service.GetPostById(id); var model = new PostEdit { PostID = detail.PostID, Body = detail.Body }; return(View(model)); }
public bool UpdatePostsById([FromUri] int id, [FromBody] PostEdit model)//get { using (var ctx = new ApplicationDbContext()) { var entity = ctx .Posts .Single(e => e.PostId == id && e.Author == _userId); entity.Title = model.Title; entity.Text = model.Text; return(ctx.SaveChanges() == 1); } }
// GET: Offers/Edit/5 public ActionResult Edit(int id) { var service = CreatePostService(); var detail = service.GetPostById(id); var model = new PostEdit { PostId = detail.PostId, Title = detail.Title, Body = detail.Body, }; return(View(model)); }
//PUT public bool UpdatePost(PostEdit model) { using (var db = new ApplicationDbContext()) { var entity = db.Posts.Single(e => e.PostId == model.PostId && e.OwnerId == _userId); entity.Title = model.Title; entity.Content = model.Content; entity.ModifiedUtc = DateTimeOffset.Now; return(db.SaveChanges() == 1); } }
public bool UpdatePost(PostEdit model) { using (var ctx = new ApplicationDbContext()) { var entity = ctx .Posts .Single(e => e.PostId == model.PostId); entity.Body = model.Body; entity.ModifiedUTC = DateTimeOffset.Now; return(ctx.SaveChanges() == 1); } }
public IHttpActionResult Put(PostEdit Post) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var service = CreatePostService(); if (!service.UpdatedPost(Post)) { return(InternalServerError()); } return(Ok("The Post Was Successfully Updated.")); }
public IHttpActionResult Put(PostEdit post) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var service = CreatePostService(); if (!service.UpdatePost(post)) { return(InternalServerError()); } return(Ok()); }
public async Task <ActionResult> Edit(int id, PostEdit postEdit) { var user = _userRetrievalShim.GetUser(); string RedirectLinkGenerator(Post p) => Url.RouteUrl(new { controller = "Forum", action = "PostLink", id = p.PostID }); var result = await _postMasterService.EditPost(id, postEdit, user, RedirectLinkGenerator); if (result.IsSuccessful) { return(Redirect(result.Redirect)); } ViewBag.Message = result.Message; return(View(postEdit)); }
public bool UpdatePost(PostEdit model) { using (var ctx = new ApplicationDbContext()) { var entity = ctx .Posts .Single(p => p.PostId == model.PostId && p.OwnerId == _userId); entity.Title = model.Title; entity.Text = model.Text; entity.ModifiedPost = DateTimeOffset.UtcNow; return(ctx.SaveChanges() == 1); } }
public bool UpdatePost(PostEdit model) { using (var ctx = new ApplicationDbContext()) { var entity = ctx .Posts .Single(e => e.PostID == model.PostID && e.UserID == _userID); entity.PostTitle = model.PostTitle; entity.PostText = model.PostText; entity.UserID = model.UserID; //entity.ModifiedUtc = DateTimeOffset.UtcNow; return(ctx.SaveChanges() == 1); } }
public bool UpdatePost(PostEdit model) { using (var ctx = new ApplicationDbContext()) { var entity = ctx .Posts .Single(e => e.Id == model.PostId && e.AuthorId == _userId); entity.Content = model.Content; entity.ModifiedUtc = DateTimeOffset.Now; return(ctx.SaveChanges() == 1); } }
public PostEdit Add(PostEdit entity) { var isTheSame = false; var isEmpty = true; // only add if they are not the same if (!string.IsNullOrEmpty(entity.EditedPostTitle) && !string.IsNullOrEmpty(entity.OriginalPostTitle)) { if (string.Compare(entity.EditedPostTitle, entity.OriginalPostTitle, StringComparison.OrdinalIgnoreCase) == 0) { isTheSame = true; } isEmpty = false; } if (!string.IsNullOrEmpty(entity.EditedPostContent) && !string.IsNullOrEmpty(entity.OriginalPostContent)) { if (string.Compare(entity.EditedPostContent, entity.OriginalPostContent, StringComparison.OrdinalIgnoreCase) == 0) { // If we get here, and is empty is false and isthesame is false, it means the titles are // different - So DON't set as the same. if (isEmpty == false && isTheSame == false) { // DO Nothing } else { isTheSame = true; } } else { isTheSame = false; } isEmpty = false; } // Check it's not empty and the data is not the same if (!isEmpty && !isTheSame) { return _context.PostEdit.Add(entity); } return entity; }
public ActionResult EditPostTopic(CreateEditTopicViewModel editPostViewModel) { using (var unitOfWork = UnitOfWorkManager.NewUnitOfWork()) { // Get the category var category = _categoryService.Get(editPostViewModel.Category); // First check this user is allowed to create topics in this category var permissions = RoleService.GetPermissions(category, UsersRole); // Now we have the category and permissionSet - Populate the optional permissions // This is just in case the viewModel is return back to the view also sort the allowedCategories // Get the allowed categories for this user var allowedAccessCategories = _categoryService.GetAllowedCategories(UsersRole); var allowedCreateTopicCategories = _categoryService.GetAllowedCategories(UsersRole, SiteConstants.Instance.PermissionCreateTopics); var allowedCreateTopicCategoryIds = allowedCreateTopicCategories.Select(x => x.Id); allowedAccessCategories.RemoveAll(x => allowedCreateTopicCategoryIds.Contains(x.Id)); editPostViewModel.OptionalPermissions = GetCheckCreateTopicPermissions(permissions); editPostViewModel.Categories = _categoryService.GetBaseSelectListCategories(allowedAccessCategories); editPostViewModel.IsTopicStarter = editPostViewModel.Id == Guid.Empty; if (editPostViewModel.PollAnswers == null) { editPostViewModel.PollAnswers = new List<PollAnswer>(); } if (ModelState.IsValid) { try { var topicPostInModeration = false; // Check stop words var stopWords = _bannedWordService.GetAll(true); foreach (var stopWord in stopWords) { if (editPostViewModel.Content.IndexOf(stopWord.Word, StringComparison.CurrentCultureIgnoreCase) >= 0 || editPostViewModel.Name.IndexOf(stopWord.Word, StringComparison.CurrentCultureIgnoreCase) >= 0) { ShowMessage(new GenericMessageViewModel { Message = LocalizationService.GetResourceString("StopWord.Error"), MessageType = GenericMessages.danger }); var p = _postService.Get(editPostViewModel.Id); var t = p.Topic; // Ahhh found a stop word. Abandon operation captain. return Redirect(t.NiceUrl); } } // Quick check to see if user is locked out, when logged in if (LoggedOnReadOnlyUser.IsLockedOut || LoggedOnReadOnlyUser.DisablePosting == true || !LoggedOnReadOnlyUser.IsApproved) { FormsAuthentication.SignOut(); return ErrorToHomePage(LocalizationService.GetResourceString("Errors.NoAccess")); } // Got to get a lot of things here as we have to check permissions // Get the post var post = _postService.Get(editPostViewModel.Id); // Get the topic var topic = post.Topic; if (post.User.Id == LoggedOnReadOnlyUser.Id || permissions[SiteConstants.Instance.PermissionEditPosts].IsTicked) { // Get the DB user so we can use lazy loading and update var loggedOnUser = MembershipService.GetUser(LoggedOnReadOnlyUser.Id); // Want the same edit date on both post and postedit var dateEdited = DateTime.UtcNow; // Create a post edit var postEdit = new PostEdit { Post = post, DateEdited = dateEdited, EditedBy = loggedOnUser, OriginalPostContent = post.PostContent, OriginalPostTitle = post.IsTopicStarter ? topic.Name : string.Empty }; // User has permission so update the post post.PostContent = _bannedWordService.SanitiseBannedWords(editPostViewModel.Content); post.DateEdited = dateEdited; post = _postService.SanitizePost(post); // Update postedit content postEdit.EditedPostContent = post.PostContent; // if topic starter update the topic if (post.IsTopicStarter) { // if category has changed then update it if (topic.Category.Id != editPostViewModel.Category) { var cat = _categoryService.Get(editPostViewModel.Category); topic.Category = cat; } topic.IsLocked = editPostViewModel.IsLocked; topic.IsSticky = editPostViewModel.IsSticky; topic.Name = StringUtils.GetSafeHtml(_bannedWordService.SanitiseBannedWords(editPostViewModel.Name)); // Update post edit postEdit.EditedPostTitle = topic.Name; // See if there is a poll if (editPostViewModel.PollAnswers != null && editPostViewModel.PollAnswers.Count(x => !string.IsNullOrEmpty(x?.Answer)) > 1 && permissions[SiteConstants.Instance.PermissionCreatePolls].IsTicked) { // Now sort the poll answers, what to add and what to remove // Poll answers already in this poll. //var existingAnswers = topic.Poll.PollAnswers.Where(x => postedIds.Contains(x.Id)).ToList(); var postedIds = editPostViewModel.PollAnswers.Where(x => !string.IsNullOrEmpty(x?.Answer)).Select(x => x.Id); // This post might not have a poll on it, if not they are creating a poll for the first time var topicPollAnswerIds = new List<Guid>(); var pollAnswersToRemove = new List<PollAnswer>(); if (topic.Poll == null) { // Create a new Poll var newPoll = new Poll { User = loggedOnUser }; // Create the poll _pollService.Add(newPoll); // Save the poll in the context so we can add answers unitOfWork.SaveChanges(); // Add the poll to the topic topic.Poll = newPoll; } else { topicPollAnswerIds = topic.Poll.PollAnswers.Select(p => p.Id).ToList(); pollAnswersToRemove = topic.Poll.PollAnswers.Where(x => !postedIds.Contains(x.Id)).ToList(); } // Set the amount of days to close the poll topic.Poll.ClosePollAfterDays = editPostViewModel.PollCloseAfterDays; var existingAnswers = editPostViewModel.PollAnswers.Where(x => !string.IsNullOrEmpty(x.Answer) && topicPollAnswerIds.Contains(x.Id)).ToList(); var newPollAnswers = editPostViewModel.PollAnswers.Where(x => !string.IsNullOrEmpty(x.Answer) && !topicPollAnswerIds.Contains(x.Id)).ToList(); // Loop through existing and update names if need be //TODO: Need to think about this in future versions if they change the name //TODO: As they could game the system by getting votes and changing name? foreach (var existPollAnswer in existingAnswers) { // Get the existing answer from the current topic var pa = topic.Poll.PollAnswers.FirstOrDefault(x => x.Id == existPollAnswer.Id); if (pa != null && pa.Answer != existPollAnswer.Answer) { // If the answer has changed then update it pa.Answer = existPollAnswer.Answer; } } // Loop through and remove the old poll answers and delete foreach (var oldPollAnswer in pollAnswersToRemove) { // Delete _pollAnswerService.Delete(oldPollAnswer); // Remove from Poll topic.Poll.PollAnswers.Remove(oldPollAnswer); } // Poll answers to add foreach (var newPollAnswer in newPollAnswers) { if (newPollAnswer != null) { var npa = new PollAnswer { Poll = topic.Poll, Answer = newPollAnswer.Answer }; _pollAnswerService.Add(npa); topic.Poll.PollAnswers.Add(npa); } } } else { // Need to check if this topic has a poll, because if it does // All the answers have now been removed so remove the poll. if (topic.Poll != null) { //Firstly remove the answers if there are any if (topic.Poll.PollAnswers != null && topic.Poll.PollAnswers.Any()) { var answersToDelete = new List<PollAnswer>(); answersToDelete.AddRange(topic.Poll.PollAnswers); foreach (var answer in answersToDelete) { // Delete _pollAnswerService.Delete(answer); // Remove from Poll topic.Poll.PollAnswers.Remove(answer); } } // Now delete the poll var pollToDelete = topic.Poll; _pollService.Delete(pollToDelete); // Remove from topic. topic.Poll = null; } } // Tags topic.Tags.Clear(); if (!string.IsNullOrEmpty(editPostViewModel.Tags)) { _topicTagService.Add(editPostViewModel.Tags.ToLower(), topic); } // if the Category has moderation marked then the topic needs to // go back into moderation if (topic.Category.ModerateTopics == true) { topic.Pending = true; topicPostInModeration = true; } // Sort the post search field post.SearchField = _postService.SortSearchField(post.IsTopicStarter, topic, topic.Tags); } else { // if the Category has moderation marked then the post needs to // go back into moderation if (topic.Category.ModeratePosts == true) { post.Pending = true; topicPostInModeration = true; } } // Add the post edit too _postEditService.Add(postEdit); // Commit the changes unitOfWork.Commit(); if (topicPostInModeration) { // If in moderation then let the user now TempData[AppConstants.MessageViewBagName] = new GenericMessageViewModel { Message = LocalizationService.GetResourceString("Moderate.AwaitingModeration"), MessageType = GenericMessages.info }; } else { TempData[AppConstants.MessageViewBagName] = new GenericMessageViewModel { Message = LocalizationService.GetResourceString("Post.Updated"), MessageType = GenericMessages.success }; } // redirect back to topic return Redirect($"{topic.NiceUrl}?postbadges=true"); } } catch (Exception ex) { unitOfWork.Rollback(); LoggingService.Error(ex); TempData[AppConstants.MessageViewBagName] = new GenericMessageViewModel { Message = LocalizationService.GetResourceString("Errors.GenericError"), MessageType = GenericMessages.danger }; } return ErrorToHomePage(LocalizationService.GetResourceString("Errors.NoPermission")); } } return View(editPostViewModel); }
private PostEdit GetType(ApType Type) { PostEdit postEdit; switch (Type) { case ApType.blog: postEdit = new PostEdit { Type = Type.ToProper(), Format = Format.PlainText, Published = true, Promote = true }; break; default: throw new ArgumentOutOfRangeException(""); } return postEdit; }
public ActionResult Edit(PermissionArea Area, PostEdit PostEdit, ApType ApType) { if (!ModelState.IsValid) { ViewData["Post"] = PostEdit; ViewData["Salt"] = "PostEdit"; return View("Form" + ApType.ToProper(), Area); } var postToSave = Mapper.Map<PostEdit, Post>(PostEdit); middleManagement.Post.Save(postToSave); return RedirectToAction("View", "Blog", new { postid = postToSave.ID, title = postToSave.Title.ToUrlFriendly() }); }
public void Delete(PostEdit entity) { _context.PostEdit.Remove(entity); }