public bool EditPost(EditPostRequest editPostRequest) { using (var db = new ParchegramDBContext()) { try { Post post = db.Post.Where(p => p.Id == editPostRequest.Id).FirstOrDefault(); if (post == null) { return(false); } post.Description = editPostRequest.Description; post.IdTypePost = editPostRequest.IdTypePost; post.PathFile = editPostRequest.PathFile; db.Post.Update(post); if (db.SaveChanges() == 1) { return(true); } return(false); } catch (Exception e) { _logger.LogInformation(e.Message); return(false); } } }
private ApiResponse EditPost(int id, EditPostRequest request) { var apiResp = new ApiResponse { ResponseCode = ResponseCode.Fail }; var postDto = new Dto.Post { BlogId = request.BlogId, Content = request.Content, Title = request.Title, Id = id }; var resp = _postBusiness.Edit(postDto); if (resp.ResponseCode != ResponseCode.Success) { apiResp.ResponseMessage = resp.ResponseMessage; return(apiResp); } apiResp.ResponseCode = ResponseCode.Success; return(apiResp); }
public async Task <ActionResult> editPost([FromBody] EditPostRequest post) { var status = await _mediator.Send(post); if (status == 1) { return(Ok(ResultObject.Ok <NullDataType>(null, "Cập thật thành công."))); } return(Ok(ResultObject.Fail("Thất bại."))); }
public IActionResult Edit(PostEditViewModel model, [FromServices] LinkGenerator linkGenerator, [FromServices] IPingbackSender pingbackSender) { if (ModelState.IsValid) { string[] tagList = string.IsNullOrWhiteSpace(model.Tags) ? new string[] { } : model.Tags.Split(',').ToArray(); var request = new EditPostRequest(model.PostId) { Title = model.Title.Trim(), Slug = model.Slug.Trim(), HtmlContent = model.HtmlContent, EnableComment = model.EnableComment, ExposedToSiteMap = model.ExposedToSiteMap, IsFeedIncluded = model.FeedIncluded, ContentLanguageCode = model.ContentLanguageCode, IsPublished = model.IsPublished, Tags = tagList, CategoryIds = model.SelectedCategoryIds, RequestIp = HttpContext.Connection.RemoteIpAddress.ToString() }; var response = _postService.EditPost(request); if (response.IsSuccess) { if (model.IsPublished) { Logger.LogInformation($"Trying to Ping URL for post: {response.Item.Id}"); var pubDate = response.Item.PostPublish.PubDateUtc.GetValueOrDefault(); var link = GetPostUrl(linkGenerator, pubDate, response.Item.Slug); if (AppSettings.EnablePingBackSend) { Task.Run(async() => { await pingbackSender.TrySendPingAsync(link, response.Item.PostContent); }); } } return(RedirectToAction(nameof(Manage))); } ModelState.AddModelError("", response.Message); return(View("CreateOrEdit", model)); } return(View("CreateOrEdit", model)); }
public IActionResult Edit([FromRoute] int id, [FromBody] EditPostRequest request) { if (!ModelState.IsValid) { return(BadRequest(GetModelStateErrors(ModelState))); } var resp = EditPost(id, request); if (resp.ResponseCode != ResponseCode.Success) { return(BadRequest(resp.ResponseMessage)); } return(Ok(resp)); }
public async Task <CreatePostResponse> EditPost(EditPostRequest req) { var post = await _dbContext.UserPosts.Include(x => x.Owner.User).Where(x => x.Owner.User.Id == req.UserId && x.Id == req.PostId).FirstOrDefaultAsync(); if (post != null) { post.Latitude = req.Latitude; post.Longitude = req.Longitude; post.PostDescription = req.PostDescription; _dbContext.UserPosts.Update(post); await _dbContext.SaveChangesAsync(); var mapped = _mapper.Map <CreatePostResponse>(post); return(mapped); } return(null); }
public ActionResult ChangePost(EditPostRequest post, Guid userId) { try { var result = _dbContext.Posts.FirstOrDefault(x => x.Id == post.PostId); if (result == null) { return(Result.GetResult("Post not found", HttpStatusCode.NotFound)); } result.Data = post.Data; result.LastChanged = DateTime.Now; result.ChangedByUserId = userId.ToString(); _dbContext.SaveChanges(); return(Result.Ok()); } catch (Exception ex) { return(Result.Error(ex.Message)); } }
public Task <bool> EditPostAsync(long postId, PublishPostDataModel publishPostDataModel, CancellationTokenSource cancellationTokenSource) => Task <PostDTO> .Run(async() => { if (!CrossConnectivity.Current.IsConnected) { throw new InvalidOperationException(AppConsts.ERROR_INTERNET_CONNECTION); } EditPostRequest editPostRequest = new EditPostRequest() { Url = string.Format(GlobalSettings.Instance.Endpoints.PostEndpoints.EditPostEndPoint, postId), AccessToken = GlobalSettings.Instance.UserProfile.AccesToken, Data = publishPostDataModel }; try { EditPostResponse editPostResponse = await _requestProvider.PostAsync <EditPostRequest, EditPostResponse>(editPostRequest); if (editPostResponse != null) { return(true); } } catch (ServiceAuthenticationException exc) { _identityUtilService.RefreshToken(); throw exc; } catch (Exception exc) { Crashes.TrackError(exc); Debug.WriteLine($"ERROR:{exc.Message}"); throw; } return(false); }, cancellationTokenSource.Token);
public async Task <IActionResult> CreateOrEdit(PostEditViewModel model, [FromServices] LinkGenerator linkGenerator, [FromServices] IPingbackSender pingbackSender) { try { if (!ModelState.IsValid) { return(Conflict(ModelState)); } var tags = string.IsNullOrWhiteSpace(model.Tags) ? Array.Empty <string>() : model.Tags.Split(',').ToArray(); var request = new EditPostRequest(model.PostId) { Title = model.Title.Trim(), Slug = model.Slug.Trim(), EditorContent = model.EditorContent, EnableComment = model.EnableComment, ExposedToSiteMap = model.ExposedToSiteMap, IsFeedIncluded = model.FeedIncluded, ContentLanguageCode = model.ContentLanguageCode, IsPublished = model.IsPublished, Tags = tags, CategoryIds = model.SelectedCategoryIds }; var tzDate = _dateTimeResolver.NowOfTimeZone; if (model.ChangePublishDate && model.PublishDate.HasValue && model.PublishDate <= tzDate && model.PublishDate.GetValueOrDefault().Year >= 1975) { request.PublishDate = model.PublishDate; } var postEntity = model.PostId == Guid.Empty ? await _postService.CreateAsync(request) : await _postService.UpdateAsync(request); if (model.IsPublished) { _logger.LogInformation($"Trying to Ping URL for post: {postEntity.Id}"); var pubDate = postEntity.PubDateUtc.GetValueOrDefault(); var link = linkGenerator.GetUriByAction(HttpContext, "Slug", "Post", new { year = pubDate.Year, month = pubDate.Month, day = pubDate.Day, postEntity.Slug }); if (_blogConfig.AdvancedSettings.EnablePingBackSend) { _ = Task.Run(async() => { await pingbackSender.TrySendPingAsync(link, postEntity.PostContent); }); } } return(Json(new { PostId = postEntity.Id })); } catch (Exception ex) { _logger.LogError(ex, "Error Creating New Post."); Response.StatusCode = (int)HttpStatusCode.InternalServerError; return(Json(ex.Message)); } }
public async Task <Response <PostEntity> > EditPost(EditPostRequest request) { return(await TryExecuteAsync <PostEntity>(async() => { var postModel = await _postRepository.GetAsync(request.Id); if (null == postModel) { return new FailedResponse <PostEntity>((int)ResponseFailureCode.PostNotFound); } postModel.CommentEnabled = request.EnableComment; postModel.PostContent = request.EditorContent; postModel.ContentAbstract = Utils.GetPostAbstract( request.EditorContent, AppSettings.PostAbstractWords, AppSettings.Editor == EditorChoice.Markdown); // Address #221: Do not allow published posts back to draft status // postModel.PostPublish.IsPublished = request.IsPublished; // Edit draft -> save and publish, ignore false case because #221 bool isNewPublish = false; if (request.IsPublished && !postModel.PostPublish.IsPublished) { postModel.PostPublish.IsPublished = true; postModel.PostPublish.PubDateUtc = DateTime.UtcNow; isNewPublish = true; } // #325: Allow changing publish date for published posts if (request.PublishDate != null && postModel.PostPublish.PubDateUtc.HasValue) { var tod = postModel.PostPublish.PubDateUtc.Value.TimeOfDay; var adjustedDate = _dateTimeResolver.GetUtcTimeFromUserTZone(request.PublishDate.Value); postModel.PostPublish.PubDateUtc = adjustedDate.AddTicks(tod.Ticks); } postModel.Slug = request.Slug; postModel.Title = request.Title; postModel.PostPublish.ExposedToSiteMap = request.ExposedToSiteMap; postModel.PostPublish.LastModifiedUtc = DateTime.UtcNow; postModel.PostPublish.IsFeedIncluded = request.IsFeedIncluded; postModel.PostPublish.ContentLanguageCode = request.ContentLanguageCode; ++postModel.PostPublish.Revision; // 1. Add new tags to tag lib foreach (var item in request.Tags.Where(item => !_tagRepository.Any(p => p.DisplayName == item))) { await _tagRepository.AddAsync(new TagEntity { DisplayName = item, NormalizedName = Utils.NormalizeTagName(item) }); await _moongladeAudit.AddAuditEntry(EventType.Content, AuditEventId.TagCreated, $"Tag '{item}' created."); } // 2. update tags postModel.PostTag.Clear(); if (request.Tags.Any()) { foreach (var tagName in request.Tags) { if (!Utils.ValidateTagName(tagName)) { continue; } var tag = await _tagRepository.GetAsync(t => t.DisplayName == tagName); if (tag != null) { postModel.PostTag.Add(new PostTagEntity { PostId = postModel.Id, TagId = tag.Id }); } } } // 3. update categories postModel.PostCategory.Clear(); if (null != request.CategoryIds && request.CategoryIds.Length > 0) { foreach (var cid in request.CategoryIds) { if (_categoryRepository.Any(c => c.Id == cid)) { postModel.PostCategory.Add(new PostCategoryEntity { PostId = postModel.Id, CategoryId = cid }); } } } await _postRepository.UpdateAsync(postModel); await _moongladeAudit.AddAuditEntry( EventType.Content, isNewPublish ? AuditEventId.PostPublished : AuditEventId.PostUpdated, $"Post updated, id: {postModel.Id}"); return new SuccessResponse <PostEntity>(postModel); })); }
public async Task <IActionResult> CreateOrEdit(PostEditViewModel model, [FromServices] LinkGenerator linkGenerator, [FromServices] IPingbackSender pingbackSender) { try { if (ModelState.IsValid) { var tagList = string.IsNullOrWhiteSpace(model.Tags) ? new string[] { } : model.Tags.Split(',').ToArray(); var request = new EditPostRequest(model.PostId) { Title = model.Title.Trim(), Slug = model.Slug.Trim(), EditorContent = model.EditorContent, EnableComment = model.EnableComment, ExposedToSiteMap = model.ExposedToSiteMap, IsFeedIncluded = model.FeedIncluded, ContentLanguageCode = model.ContentLanguageCode, IsPublished = model.IsPublished, Tags = tagList, CategoryIds = model.SelectedCategoryIds, RequestIp = HttpContext.Connection.RemoteIpAddress.ToString() }; var tzDate = _dateTimeResolver.GetNowWithUserTZone(); if (model.ChangePublishDate && model.PublishDate.HasValue && model.PublishDate <= tzDate && model.PublishDate.GetValueOrDefault().Year >= 1975) { request.PublishDate = model.PublishDate; } var response = model.PostId == Guid.Empty ? await _postService.CreateNewPost(request) : await _postService.EditPost(request); if (response.IsSuccess) { if (model.IsPublished) { Logger.LogInformation($"Trying to Ping URL for post: {response.Item.Id}"); var pubDate = response.Item.PostPublish.PubDateUtc.GetValueOrDefault(); var link = GetPostUrl(linkGenerator, pubDate, response.Item.Slug); if (_blogConfig.AdvancedSettings.EnablePingBackSend) { _ = Task.Run(async() => { await pingbackSender.TrySendPingAsync(link, response.Item.PostContent); }); } } return(Json(new { PostId = response.Item.Id })); } Response.StatusCode = (int)HttpStatusCode.InternalServerError; return(Json(new FailedResponse(response.Message))); } Response.StatusCode = (int)HttpStatusCode.BadRequest; return(Json(new FailedResponse("Invalid ModelState"))); } catch (Exception ex) { Logger.LogError(ex, "Error Creating New Post."); Response.StatusCode = (int)HttpStatusCode.InternalServerError; return(Json(new FailedResponse(ex.Message))); } }
private async void EditExecute() { if (!_findierService.IsAuthenticated) { NavigationService.Navigate(typeof(AuthenticationPage), true); return; } var type = PostType.Freebie; decimal price = 0; if (IsFixed) { type = PostType.Fixed; // convert the price into a decimal if (!decimal.TryParse(Price, out price) || price < 1) { CurtainPrompt.ShowError("Please enter a valid price."); return; } } else if (IsMoney) { type = PostType.Money; } if (!string.IsNullOrWhiteSpace(Email) && !Email.IsEmail()) { CurtainPrompt.ShowError("Please enter a valid email."); return; } if (!string.IsNullOrWhiteSpace(PhoneNumber) && !PhoneNumber.IsPhoneNumber()) { CurtainPrompt.ShowError("Please enter a valid phone number."); return; } if (string.IsNullOrWhiteSpace(Email) && string.IsNullOrWhiteSpace(PhoneNumber)) { CurtainPrompt.ShowError("Please enter at least one contact method."); return; } var editPostRequest = new EditPostRequest(_post.Id, _post.Text == Text ? null : Text, _post.Type == type ? null : (PostType?)type, _post.Price == price ? null : (decimal?)price, _post.IsNsfw == IsNsfw || !CanEditNsfw ? null : (bool?)IsNsfw, _post.Email == Email ? null : Email, _post.PhoneNumber == PhoneNumber ? null : PhoneNumber); IsLoading = true; var restResponse = await _findierService.SendAsync(editPostRequest); IsLoading = false; if (restResponse.IsSuccessStatusCode) { CurtainPrompt.Show("Edit was saved."); NavigationService.GoBack(); } else { CurtainPrompt.ShowError(restResponse.DeserializedResponse?.Error ?? "Problem editing post. Try again later."); } var props = new Dictionary <string, string>(); if (restResponse.IsSuccessStatusCode) { props.Add("Error", restResponse.DeserializedResponse?.Error ?? "Unknown"); props.Add("StatusCode", restResponse.StatusCode.ToString()); } _insightsService.TrackEvent("EditPost", props); }
public ActionResult ChangePost([FromBody] EditPostRequest request) { return(_forumService.ChangePost(request, Guid.Parse(_contextAccessor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value))); }
public Response <PostEntity> EditPost(EditPostRequest request) { return(TryExecute <PostEntity>(() => { var postModel = _postRepository.Get(request.Id); if (null == postModel) { return new FailedResponse <PostEntity>((int)ResponseFailureCode.PostNotFound); } postModel.CommentEnabled = request.EnableComment; postModel.PostContent = _htmlCodec.HtmlEncode(request.HtmlContent); postModel.ContentAbstract = Utils.GetPostAbstract(request.HtmlContent, AppSettings.PostSummaryWords); postModel.PostPublish.IsPublished = request.IsPublished; postModel.Slug = request.Slug; postModel.Title = request.Title; postModel.PostPublish.ExposedToSiteMap = request.ExposedToSiteMap; postModel.PostPublish.LastModifiedUtc = DateTime.UtcNow; postModel.PostPublish.IsFeedIncluded = request.IsFeedIncluded; postModel.PostPublish.ContentLanguageCode = request.ContentLanguageCode; ++postModel.PostPublish.Revision; // from draft if (!postModel.PostPublish.PubDateUtc.HasValue) { postModel.PostPublish.PubDateUtc = DateTime.UtcNow; } // 1. Add new tags to tag lib foreach (var item in request.Tags.Where(item => !_tagRepository.Any(p => p.DisplayName == item))) { _tagRepository.Add(new TagEntity { DisplayName = item, NormalizedName = Utils.NormalizeTagName(item) }); } // 2. update tags postModel.PostTag.Clear(); if (request.Tags.Any()) { foreach (var t in request.Tags) { var tag = _tagRepository.Get(_ => _.DisplayName == t); if (tag != null) { postModel.PostTag.Add(new PostTagEntity { PostId = postModel.Id, TagId = tag.Id }); } } } // 3. update categories postModel.PostCategory.Clear(); if (null != request.CategoryIds && request.CategoryIds.Length > 0) { foreach (var cid in request.CategoryIds) { if (_categoryRepository.Any(c => c.Id == cid)) { postModel.PostCategory.Add(new PostCategoryEntity { PostId = postModel.Id, CategoryId = cid }); } } } _postRepository.Update(postModel); return new SuccessResponse <PostEntity>(postModel); })); }
public async Task <PostEntity> UpdateAsync(EditPostRequest request) { var post = await _postRepository.GetAsync(request.Id); if (null == post) { throw new InvalidOperationException($"Post {request.Id} is not found."); } post.CommentEnabled = request.EnableComment; post.PostContent = request.EditorContent; post.ContentAbstract = GetPostAbstract( request.EditorContent, AppSettings.PostAbstractWords, AppSettings.Editor == EditorChoice.Markdown); // Address #221: Do not allow published posts back to draft status // postModel.IsPublished = request.IsPublished; // Edit draft -> save and publish, ignore false case because #221 bool isNewPublish = false; if (request.IsPublished && !post.IsPublished) { post.IsPublished = true; post.PubDateUtc = DateTime.UtcNow; isNewPublish = true; } // #325: Allow changing publish date for published posts if (request.PublishDate != null && post.PubDateUtc.HasValue) { var tod = post.PubDateUtc.Value.TimeOfDay; var adjustedDate = _dateTimeResolver.ToUtc(request.PublishDate.Value); post.PubDateUtc = adjustedDate.AddTicks(tod.Ticks); } post.Slug = request.Slug; post.Title = request.Title; post.ExposedToSiteMap = request.ExposedToSiteMap; post.LastModifiedUtc = DateTime.UtcNow; post.IsFeedIncluded = request.IsFeedIncluded; post.ContentLanguageCode = request.ContentLanguageCode; // 1. Add new tags to tag lib foreach (var item in request.Tags.Where(item => !_tagRepository.Any(p => p.DisplayName == item))) { await _tagRepository.AddAsync(new TagEntity { DisplayName = item, NormalizedName = TagService.NormalizeTagName(item) }); await _blogAudit.AddAuditEntry(EventType.Content, AuditEventId.TagCreated, $"Tag '{item}' created."); } // 2. update tags post.PostTag.Clear(); if (request.Tags.Any()) { foreach (var tagName in request.Tags) { if (!TagService.ValidateTagName(tagName)) { continue; } var tag = await _tagRepository.GetAsync(t => t.DisplayName == tagName); if (tag != null) { post.PostTag.Add(new PostTagEntity { PostId = post.Id, TagId = tag.Id }); } } } // 3. update categories post.PostCategory.Clear(); if (null != request.CategoryIds && request.CategoryIds.Length > 0) { foreach (var cid in request.CategoryIds) { if (_categoryRepository.Any(c => c.Id == cid)) { post.PostCategory.Add(new PostCategoryEntity { PostId = post.Id, CategoryId = cid }); } } } await _postRepository.UpdateAsync(post); await _blogAudit.AddAuditEntry( EventType.Content, isNewPublish?AuditEventId.PostPublished : AuditEventId.PostUpdated, $"Post updated, id: {post.Id}"); _cache.Remove(CacheDivision.Post, request.Id.ToString()); return(post); }
public Response <PostEntity> EditPost(EditPostRequest request) { return(TryExecute <PostEntity>(() => { var postModel = _postRepository.Get(request.Id); if (null == postModel) { return new FailedResponse <PostEntity>((int)ResponseFailureCode.PostNotFound); } postModel.CommentEnabled = request.EnableComment; postModel.PostContent = AppSettings.Editor == EditorChoice.Markdown ? request.EditorContent : _htmlCodec.HtmlEncode(request.EditorContent); postModel.ContentAbstract = Utils.GetPostAbstract( request.EditorContent, AppSettings.PostSummaryWords, AppSettings.Editor == EditorChoice.Markdown); // Address #221: Do not allow published posts back to draft status // postModel.PostPublish.IsPublished = request.IsPublished; // Edit draft -> save and publish, ignore false case because #221 if (request.IsPublished && !postModel.PostPublish.IsPublished) { postModel.PostPublish.IsPublished = true; postModel.PostPublish.PublisherIp = request.RequestIp; postModel.PostPublish.PubDateUtc = DateTime.UtcNow; } postModel.Slug = request.Slug; postModel.Title = request.Title; postModel.PostPublish.ExposedToSiteMap = request.ExposedToSiteMap; postModel.PostPublish.LastModifiedUtc = DateTime.UtcNow; postModel.PostPublish.IsFeedIncluded = request.IsFeedIncluded; postModel.PostPublish.ContentLanguageCode = request.ContentLanguageCode; ++postModel.PostPublish.Revision; // 1. Add new tags to tag lib foreach (var item in request.Tags.Where(item => !_tagRepository.Any(p => p.DisplayName == item))) { _tagRepository.Add(new TagEntity { DisplayName = item, NormalizedName = Utils.NormalizeTagName(item) }); } // 2. update tags postModel.PostTag.Clear(); if (request.Tags.Any()) { foreach (var tagName in request.Tags) { if (!Utils.ValidateTagName(tagName)) { continue; } var tag = _tagRepository.Get(t => t.DisplayName == tagName); if (tag != null) { postModel.PostTag.Add(new PostTagEntity { PostId = postModel.Id, TagId = tag.Id }); } } } // 3. update categories postModel.PostCategory.Clear(); if (null != request.CategoryIds && request.CategoryIds.Length > 0) { foreach (var cid in request.CategoryIds) { if (_categoryRepository.Any(c => c.Id == cid)) { postModel.PostCategory.Add(new PostCategoryEntity { PostId = postModel.Id, CategoryId = cid }); } } } _postRepository.Update(postModel); return new SuccessResponse <PostEntity>(postModel); })); }