Example #1
0
        public async Task Handler_GivenValidData_ShouldUpdatePost()
        {
            // Arrange
            var post = new PostDTO
            {
                Id       = 2,
                Title    = "Title_new",
                Text     = "Text_new",
                TopicId  = 99,
                AuthorId = 99,
                Date     = new DateTime(2020, 05, 01),
            };

            var command = new UpdatePostCommand {
                Model = post
            };

            // Act
            var handler = new UpdatePostCommand.UpdatePostCommandHandler(Context);
            await handler.Handle(command, CancellationToken.None);

            var entity = Context.Posts.Find(post.Id);

            // Assert
            entity.ShouldNotBeNull();

            entity.Title.ShouldBe(command.Model.Title);
            entity.Text.ShouldBe(command.Model.Text);

            entity.TopicId.ShouldNotBe(command.Model.TopicId);
            entity.AuthorId.ShouldNotBe(command.Model.AuthorId);
            entity.Date.ShouldNotBe(command.Model.Date);
        }
        public async Task <IActionResult> EditPost(UpdatePostCommand command)
        {
            if (!ModelState.IsValid)
            {
                ViewBag.ShowMessage = true;
                ViewBag.Message     = "Something went wrong";
                return(View());
            }

            try
            {
                CreatePostValidation.CommandValidation(command);

                var admin = await _adminService.GetAdminAsync();

                await _postService.EditPostAsync(command);

                return(RedirectToAction("Posts"));
            }
            catch (InternalSystemException ex)
            {
                ViewBag.ShowMessage = true;
                ViewBag.Message     = ex.Message;
                return(View());
            }
            catch (Exception)
            {
                return(RedirectToAction("Posts"));
            }
        }
 public async Task UpdatePost(
     [FromRoute] Guid postId,
     [FromBody] UpdatePostCommand command)
 {
     command.PostId = postId;
     await Mediator.Send(command);
 }
        public async Task <ActionResult> Update([FromBody]
                                                UpdatePostCommand updatePostCommand)
        {
            await _mediator.Send(updatePostCommand);

            return(NoContent());
        }
Example #5
0
        public async Task <IActionResult> ModifyPost(int id, [FromBody] JsModifyPost albumInfo)
        {
            var command  = new UpdatePostCommand(id, _mapper.Map <PostInfo>(albumInfo));
            var response = await _mediator.Send(command);

            return(_presenter.ToActionResult(response));
        }
Example #6
0
        public async Task <IActionResult> Put([FromBody] UpdatePostCommand request, string id)
        {
            request.Id = id;
            var response = await Mediator.Send(request);

            return(Ok(response));
        }
Example #7
0
    public async Task <Result <Guid> > Handle(UpdatePostCommand request, CancellationToken cancellationToken)
    {
        var post = await this.context.Posts
                   .FirstOrDefaultAsync(x => x.Id == request.Id, cancellationToken);

        if (post == null || (user.IsAuthenticated && post.UserId != user.Id))
        {
            return(Result <Guid> .Failed("Not found"));
        }

        if (request.Image != null)
        {
            post.Image = request?.Image;
        }

        if (request.Title != null)
        {
            post.Title = request?.Title;
        }

        if (request.Content != null)
        {
            post.Content = request?.Content;
        }

        await this.context.SaveChangesAsync(cancellationToken);

        return(Result <Guid> .Ok(post.Id));
    }
        public void UpdatePostTest_TestsThatAPostIsUpdatedAndRetreivedAsExpected_VerifiesByDatabaseRetrieval()
        {
            var postController = _kernel.Get <PostController>();

            Assert.NotNull(postController);
            string title             = "Post # 1";
            string description       = "Description of Post # 1";
            string category          = "Category of Post # 1";
            string email             = "*****@*****.**";
            var    createPostCommand = new CreatePostCommand();

            createPostCommand.Title       = title;
            createPostCommand.Description = description;
            createPostCommand.Category    = category;
            createPostCommand.Email       = email;

            // Set the Current User's username(which is the same as his email), otherwise the request for posting a new Post will fail
            postController.User = new ClaimsPrincipal(new List <ClaimsIdentity>()
            {
                new ClaimsIdentity(new List <Claim>()
                {
                    new Claim(ClaimTypes.Name, email)
                })
            });

            var    postIdHttpContent = postController.Post(JsonConvert.SerializeObject(createPostCommand));
            string postId            = ((OkNegotiatedContentResult <string>)postIdHttpContent).Content;

            IHttpActionResult  response      = (IHttpActionResult)postController.Get(postId);
            PostRepresentation retreivedPost = ((OkNegotiatedContentResult <PostRepresentation>)response).Content;

            Assert.NotNull(retreivedPost);

            Assert.AreEqual(title, retreivedPost.Title);
            Assert.AreEqual(description, retreivedPost.Description);
            Assert.AreEqual(category, retreivedPost.Category);

            string title2       = "Post # 2";
            string description2 = "Description of Post # 2";
            string category2    = "Category of Post # 2";

            var updatePostCommand = new UpdatePostCommand()
            {
                Category    = category2,
                Description = description2,
                Id          = postId,
                Title       = title2
            };

            postController.Put(JsonConvert.SerializeObject(updatePostCommand));

            response      = (IHttpActionResult)postController.Get(postId);
            retreivedPost = ((OkNegotiatedContentResult <PostRepresentation>)response).Content;
            Assert.NotNull(retreivedPost);

            Assert.AreEqual(title2, retreivedPost.Title);
            Assert.AreEqual(description2, retreivedPost.Description);
            Assert.AreEqual(category2, retreivedPost.Category);
        }
Example #9
0
        public async Task EditPostAsync(UpdatePostCommand command)
        {
            var post = await _context.Posts.SingleOrDefaultAsync(x => x.Id == command.Id);

            post.Update(command.Title, command.Description, command.Content, command.Tags);

            await _context.SaveChangesAsync();
        }
Example #10
0
 public void UpdatePost(Post post)
 {
     UpdatePostCommand.Execute(new
     {
         post.Id,
         post.Content
     });
 }
 public async Task <ActionResult <Response <int> > > Put(int id, UpdatePostCommand command)
 {
     if (id != command.Id)
     {
         return(BadRequest());
     }
     return(Ok(await Mediator.Send(command)));
 }
        public async Task ShouldRequireMinimunFields()
        {
            await RunAsDefaultUserAsync();

            var command = new UpdatePostCommand();

            FluentActions.Invoking(() => SendAsync(command))
            .Should().Throw <ValidationException>();
        }
        public async Task <ActionResult> Update(int id, UpdatePostCommand command)
        {
            if (id != command.Id)
            {
                return(BadRequest());
            }

            await Mediator.Send(command);

            return(NoContent());
        }
Example #14
0
        public async Task <IActionResult> UpdatePost(UpdatePostCommand updatePostCommand)
        {
            if (!ModelState.IsValid)
            {
                return(NoContent());
            }

            await Mediator.Send(updatePostCommand);

            return(NoContent());
        }
Example #15
0
        public async Task <IActionResult> UpdatePostAsync([FromRoute] Guid id, [FromBody] UpdatePostCommand request)
        {
            if (id != request.PostId)
            {
                return(BadRequest());
            }

            await Mediator.Send(request);

            return(NoContent());
        }
Example #16
0
        public async Task <ActionResult> Update(int id, PostRequest postRequest)
        {
            var updatePostCommand = new UpdatePostCommand
            {
                Id      = id,
                Title   = postRequest.Title,
                Excerpt = postRequest.Excerpt
            };
            await Mediator.Send(updatePostCommand);

            return(NoContent());
        }
Example #17
0
        public async Task <IActionResult> Edit(EditPostViewModel model)
        {
            if (ModelState.IsValid)
            {
                /* Update topic of the post.
                 * We use `create` command instead of `update`,
                 * because one topic can relate to multiple posts (one-to-many relations)*/
                var topicDTO = new TopicDTO {
                    Text = model.Topic
                };
                var topicCommand = new CreateTopicCommand {
                    Model = topicDTO
                };

                int topicId;

                try
                {
                    topicId = await _mediator.Send(topicCommand);
                }
                catch (RequestValidationException failures)
                {
                    foreach (var error in failures.Failures)
                    {
                        ModelState.AddModelError(string.Empty, error.Value[0]);
                    }
                    return(View(model));
                }

                // Update post.
                var postDTO = _mapper.Map <EditPostViewModel, PostDTO>(model);
                postDTO.TopicId = topicId;
                var postCommand = new UpdatePostCommand {
                    Model = postDTO
                };

                try
                {
                    await _mediator.Send(postCommand);
                }
                catch (RequestValidationException failures)
                {
                    foreach (var error in failures.Failures)
                    {
                        ModelState.AddModelError(string.Empty, error.Value[0]);
                    }
                    return(View(model));
                }
                return(RedirectToAction("Read", "Posts", new { id = postDTO.Id }));
            }
            return(View(model));
        }
        public async Task <IActionResult> EditPost(int id)
        {
            var post = await _postService.GetPostAsync(id);

            if (post == null)
            {
                return(RedirectToAction("Posts"));
            }

            var command = new UpdatePostCommand(post);

            return(View(command));
        }
Example #19
0
        public void Handle_GivenInvalidPostId_ThrowsException()
        {
            var command = new UpdatePostCommand
            {
                PostId = 1004,
                Text   = Guid.NewGuid().ToString()
            };

            var handler = GetNewHandler();

            Assert.ThrowsAsync <ValidationException>(async() =>
                                                     await handler.Handle(command, CancellationToken.None));
        }
        // PUT api/posts/5
        public HttpResponseMessage Put(int id, UpdatePostCommand command)
        {
            var post = GetPost(id);

            post.Title = command.Title;
            post.Slug = command.Slug ?? post.Slug;
            post.Summary = command.Summary;
            post.ContentType = command.ContentType;
            post.Content = command.Content;
            post.Tags = command.Tags;
            post.PublishDate = command.PublishDate ?? post.PublishDate;

            return new HttpResponseMessage(HttpStatusCode.OK);
        }
        public async Task <IActionResult> Edit(int id, UpdatePostCommand command)
        {
            if (!ModelState.IsValid)
            {
                return(View(_mapper.Map <PostDto>(command)));
            }
            var result = await Mediator.Send(command);

            if (result.Succeeded)
            {
                return(RedirectToAction("index"));
            }
            return(View(_mapper.Map <PostDto>(command)));
        }
Example #22
0
        // PUT api/posts/5
        public HttpResponseMessage Put(int id, UpdatePostCommand command)
        {
            var post = GetPost(id);

            post.Title       = command.Title;
            post.Slug        = command.Slug ?? post.Slug;
            post.Summary     = command.Summary;
            post.ContentType = command.ContentType;
            post.Content     = command.Content;
            post.Tags        = command.Tags;
            post.PublishDate = command.PublishDate ?? post.PublishDate;

            return(new HttpResponseMessage(HttpStatusCode.OK));
        }
Example #23
0
        public async Task Handle_ShouldBeUpdatePost()
        {
            var command = new UpdatePostCommand
            {
                PostId = DefaultPostId,
                Text   = Guid.NewGuid().ToString()
            };

            var handler = GetNewHandler();

            var result = await handler.Handle(command, CancellationToken.None);

            Assert.AreEqual(command.Text, result.Text);
            Assert.That(DateTimeService.NowUtc > result.LastModifiedUtc);
        }
Example #24
0
        public Post SubmitPost(CreatePostModel model)
        {
            //If statement to update the post if there is already one in the database.
            if (model.PostId != 0)
            {
                //converts the data into a post object.
                Post newPost = ConvertToPostWithPostId(model.PostPurpose, model.PostTitle, model.PostDescription,
                                                       model.ExpirationDate, model.PostStatus, model.SubCategoryId,
                                                       model.DatePosted, model.CategoryId, model.PostedBy, model.PostId);

                //command to update the post.
                UpdatePostCommand command = new UpdatePostCommand(newPost);
                commandBus.Execute(command);

                //grabs all images that were uploaded.
                List <String> updateImagePaths = ImagePathCreation();

                //inserts each image into the picture database.
                foreach (string path in updateImagePaths)
                {
                    InsertPictureCommand pictureCommand =
                        new InsertPictureCommand(new Picture(newPost.PostId, path));
                    commandBus.Execute(pictureCommand);
                }

                return(newPost);
            }

            //converts the data into a post object.
            Post post = ConvertToPost(model.PostPurpose, model.PostTitle, model.PostDescription, model.ExpirationDate,
                                      model.PostStatus, model.SubCategoryId, model.DatePosted, model.CategoryId,
                                      model.PostedBy);
            InsertPostCommand postcommand = new InsertPostCommand(post);

            commandBus.Execute(postcommand, delegate(Post result) { post = result; });

            // grabs all images that were uploaded.
            List <String> imagePaths = ImagePathCreation();


            //inserts each image into the picture database.
            foreach (string path in imagePaths)
            {
                InsertPictureCommand command = new InsertPictureCommand(new Picture(post.PostId, path));
                commandBus.Execute(command);
            }
            return(post);
        }
Example #25
0
        public async Task <ResponseFromApi <int> > UpdatePost(PostDetailBlazorVM postDetailViewModel)
        {
            try
            {
                UpdatePostCommand updatePostCommand = _mapper.Map <UpdatePostCommand>(postDetailViewModel);
                await _client.UpdatePostAsync(updatePostCommand);

                return(new ResponseFromApi <int>()
                {
                    Success = true
                });
            }
            catch (ApiException ex)
            {
                return(ex.ConvertApiExceptions());
            }
        }
Example #26
0
        public IActionResult Update(long postId, string postTitle, string postSlug, string postSubTitle, string headMask, int layoutType,
                                    string postMarkDown, string tags, int published, string pubDate, string postHeadImageUrl)
        {
            UpdatePostCommand command = new UpdatePostCommand();

            command.HeadMask         = headMask;
            command.LayoutType       = layoutType;
            command.PostHeadImageUrl = postHeadImageUrl;
            command.PostMarkDown     = postMarkDown;
            command.PostSlug         = postSlug;
            command.postSubTitle     = postSubTitle;
            command.PostTitle        = postTitle;
            command.Published        = published;
            command.Tags             = tags;
            command.PostId           = postId;
            var result = _updatePostCommandInvorker.Execute(command);

            return(RedirectToAction("Index"));
        }
Example #27
0
        /// <summary>
        /// Update an existing post
        /// </summary>
        /// <param name="updatepostCommand"></param>
        /// <param name="currentUserEmail"></param>
        public void UpdatePost(UpdatePostCommand updatepostCommand, string currentUserEmail)
        {
            if (string.IsNullOrWhiteSpace(currentUserEmail))
            {
                throw new NullReferenceException("Couldn't verify current User's identity");
            }
            var post = _postRepository.GetById(updatepostCommand.Id);

            if (post == null)
            {
                throw new NullReferenceException(string.Format("Could not find a Post with ID:{0}", updatepostCommand.Id));
            }
            // If the Post's email is not equal to the current user's email, do not proceed
            if (!currentUserEmail.Equals(post.PosterEmail))
            {
                throw new InvalidOperationException("Email verification mismatch. Aborting operation");
            }
            post.Update(updatepostCommand.Title, updatepostCommand.Description, updatepostCommand.Category);
            _postRepository.Update(post);
        }
Example #28
0
        public async Task Handle_GivenInvalidPostData_ThrowsException()
        {
            // Arrange
            var post = new PostDTO
            {
                Id       = 99,
                Title    = "Title_new",
                Text     = "Text_new",
                TopicId  = 2,
                AuthorId = 2,
                Date     = new DateTime(2020, 05, 01),
            };

            var command = new UpdatePostCommand {
                Model = post
            };

            // Act
            var handler = new UpdatePostCommand.UpdatePostCommandHandler(Context);

            // Assert
            await Should.ThrowAsync <NotFoundException>(() => handler.Handle(command, CancellationToken.None));
        }
        public async Task ShouldUpdatePost()
        {
            var currentUserName = await RunAsDefaultUserAsync();

            var addedPost = await AddAsync(new Post
            {
                DisplayName = "AddedPost",
                UserName    = "******",
                PhotoUrl    = "someUrl",
                Title       = "New Post Title",
                Content     = "New Post Content for Test"
            });

            var command = new UpdatePostCommand
            {
                Id          = addedPost.Id,
                DisplayName = "UpdatedPost",
                UserName    = "******",
                PhotoUrl    = "anotherUrl",
                Title       = "Update Post Title",
                Content     = "Update Post Content for Test"
            };

            await SendAsync(command);

            var updatePost = await FindAsync <Post>(addedPost.Id);

            updatePost.Should().NotBeNull();
            updatePost.DisplayName.Should().Be(command.DisplayName);
            updatePost.UserName.Should().Be(command.UserName);
            updatePost.PhotoUrl.Should().Be(command.PhotoUrl);
            updatePost.Title.Should().Be(command.Title);
            updatePost.Content.Should().Be(command.Content);
            updatePost.LastModified.Should().BeCloseTo(DateTime.Now, 1000);
            updatePost.LastModifiedBy.Should().Be(currentUserName);
        }
        public async Task <IActionResult> Edit(int id, [Bind("Id,Title,Body,Status")] PostDto post)
        {
            if (id != post.Id)
            {
                return(NotFound());
            }

            if (post.Status == PostStatus.Approved)
            {
                return(RedirectToAction(nameof(Index)));
            }

            if (!ModelState.IsValid)
            {
                return(View(post));
            }

            var command = new UpdatePostCommand {
                PostId = id, Post = post
            };
            await _mediator.Send(command);

            return(RedirectToAction(nameof(Index)));
        }
        public async Task <IActionResult> OnGetAsync(Guid id, CancellationToken cancellationToken)
        {
            var result = await _mediator.Send(new GetPostByIdQuery { Id = id }, cancellationToken);

            if (!result.IsSuccess)
            {
                throw result.Exception;
            }

            Post = new UpdatePostCommand
            {
                Id           = result.Value.Id,
                Title        = result.Value.Title,
                Description  = result.Value.Description,
                Content      = result.Value.Content,
                Categories   = result.Value.Categories,
                Published    = result.Value.Published,
                CoverUrl     = result.Value.CoverUrl,
                CoverCaption = result.Value.CoverCaption,
                CoverLink    = result.Value.CoverLink
            };

            return(Page());
        }
        // PUT api/posts/5
        public async Task<HttpResponseMessage> Put(int id, UpdatePostCommand command) 
        {
            HttpResponseMessage result;
            ClaimsPrincipal user = User as ClaimsPrincipal;
            Claim userIdClaim = user.Claims.FirstOrDefault(claim => claim.Type == ClaimTypes.NameIdentifier);

            if (userIdClaim == null || string.IsNullOrEmpty(userIdClaim.Value))
            {
                result = Request.CreateResponse(HttpStatusCode.InternalServerError);
            }
            else
            {
                BlogPost blogPost = await RavenSession.LoadAsync<BlogPost>(id);
                if (blogPost == null)
                {
                    result = Request.CreateResponse(HttpStatusCode.NotFound);
                }
                else
                {
                    if (userIdClaim.Value.Equals(blogPost.AuthorId, StringComparison.InvariantCultureIgnoreCase) == false)
                    {
                        // TODO: Log here
                        // Basically, the blogPost author is not the one who has been authenticated. return 404 for security reasons.
                        result = Request.CreateResponse(HttpStatusCode.NotFound);
                    }
                    else
                    {
                        string newSlugPath = command.Slug ?? command.Title.ToSlug();
                        Slug existingSlug = blogPost.Slugs.FirstOrDefault(slug => slug.Path.Equals(newSlugPath, StringComparison.InvariantCultureIgnoreCase));
                        IList<Tag> tagsToSave = (command.Tags != null && command.Tags.Any())
                            ? command.Tags.Distinct(StringComparer.InvariantCultureIgnoreCase).Select(tag => new Tag { Name = tag, Slug = tag.ToSlug() }).ToList()
                            : blogPost.Tags.ToList();

                        blogPost.Title = command.Title;
                        blogPost.BriefInfo = command.Summary;
                        blogPost.Content = command.Content;
                        blogPost.Tags = new Collection<Tag>(tagsToSave);
                        blogPost.LastUpdatedOn = DateTimeOffset.Now;

                        if (existingSlug == null)
                        {
                            foreach (Slug slug in blogPost.Slugs) { slug.IsDefault = false; }
                            blogPost.Slugs.Add(new Slug
                            {
                                IsDefault = true,
                                Path = newSlugPath,
                                CreatedOn = DateTimeOffset.Now
                            });
                        }

                        HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, new PostModel(blogPost, GetCategoryScheme()));
                        result = response;
                    }
                }
            }

            return result;
        }