Example #1
0
        public async Task <PostInputViewModel> GetPostById(int id)
        {
            var post = await this.postRepo.GetByIdAsync(id);

            if (post == null)
            {
                throw new NullReferenceException("Post not found");
            }

            if (post.IsDeleted)
            {
                throw new InvalidOperationException("Post not found");
            }

            var postModel = new PostInputViewModel
            {
                Author      = post.Author.UserName,
                Id          = post.Id,
                FullContent = this.sanitizer.Sanitize(post.FullContent),
                IsDeleted   = post.IsDeleted,
                Title       = post.Title,
                Tags        = string.Join(", ", post.Tags.Select(p => p.Tag.Name))
            };

            return(postModel);
        }
Example #2
0
        public async Task GetAllActivePosts_WithNoSearchString_ShouldReturnAllPosts()
        {
            //Arrange
            var db = this.SetDb();

            var service = await this.Setup(db);

            var postModelA = new PostInputViewModel
            {
                Title       = "Test Post",
                Author      = "*****@*****.**",
                FullContent = "Some test post content",
                Tags        = "Baking, Cakes"
            };

            await service.CreatePost(postModelA);

            var postModelB = new PostInputViewModel
            {
                Title       = "Test Post 2",
                Author      = "*****@*****.**",
                FullContent = "Some test post content",
                Tags        = "Baking"
            };

            await service.CreatePost(postModelB);

            //Act
            var posts = service.GetAllActivePosts(null);

            //Assert
            Assert.NotEmpty(posts);
        }
Example #3
0
        public async Task GetPostByIdShouldReturnModel()
        {
            // Arange
            var options = new DbContextOptionsBuilder <ApplicationDbContext>()
                          .UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString()).Options;

            //Act
            var db     = new ApplicationDbContext(options);
            var config = new MapperConfiguration(cfg =>
            {
                cfg.AddProfile <ApplicationProfile>();
            });
            var mapper      = new Mapper(config);
            var postService = new PostService(db, mapper);
            var user        = new ApplicationUser
            {
                UserName = "******",
                Email    = "*****@*****.**"
            };
            await db.Users.AddAsync(user);

            var model = new PostInputViewModel
            {
                CreatedOn   = DateTime.UtcNow,
                Description = "d1",
                ImageUrl    = "URL",
                Title       = "some title"
            };
            var id = await postService.AddPostAsync(model, user.Id);

            var modelOutput = postService.GetPostById(id);

            //assert
            Assert.Equal(modelOutput.Id, id);
        }
Example #4
0
        public async Task GetAllCommentsPerPost_WithValidPost_ShouldReturnAllComments()
        {
            //Arrange
            var db = this.SetDb();

            var service = await this.Setup(db);

            var postModel = new PostInputViewModel
            {
                Title       = "Test Post",
                Author      = "*****@*****.**",
                FullContent = "Some test post content",
                Tags        = "Baking, Cakes"
            };

            await service.CreatePost(postModel);

            var commentModel = new CommentInputViewModel
            {
                AuthorName = "*****@*****.**",
                Content    = "Test comment",
                PostId     = 1
            };

            await service.CreateComment(commentModel);

            //Act
            var result = await service.GetAllCommentsPerPost(1);

            var expectedCount = 1;
            var actualCount   = result.Comments.Count();

            //Assert
            Assert.Equal(expectedCount, actualCount);
        }
Example #5
0
        public async Task GetAllMyComments_WithComments_ShouldReturnUserComment()
        {
            //Arrange
            var db = this.SetDb();

            var service = await this.Setup(db);

            var postModel = new PostInputViewModel
            {
                Title       = "Test Post",
                Author      = "*****@*****.**",
                FullContent = "Some test post content",
                Tags        = "Baking, Cakes"
            };

            await service.CreatePost(postModel);

            var commentModel = new CommentInputViewModel
            {
                AuthorName = "*****@*****.**",
                Content    = "Test comment",
                PostId     = 1
            };

            await service.CreateComment(commentModel);

            //Act
            var comments = service.GetAllMyComments("*****@*****.**");

            //Assert
            Assert.NotEmpty(comments);
        }
Example #6
0
        public async Task CreatePost_WithDuplicateTitle_ShouldThrow()
        {
            //Arrange
            var db = this.SetDb();

            var service = await this.Setup(db);

            var postModelA = new PostInputViewModel
            {
                Title       = "Test Post",
                Author      = "*****@*****.**",
                FullContent = "Some test post content",
                Tags        = "Baking, Cakes"
            };
            await service.CreatePost(postModelA);

            var postModelB = new PostInputViewModel
            {
                Title       = "Test Post",
                Author      = "*****@*****.**",
                FullContent = "Some test postB content",
                Tags        = "Baking"
            };

            //Act

            //Assert
            await Assert.ThrowsAsync <InvalidOperationException
                                      >(async() => await service.CreatePost(postModelB));
        }
Example #7
0
        public async Task CreateComment_WithValidData_ShouldAddCommentPost()
        {
            //Arrange
            var db = this.SetDb();

            var service = await this.Setup(db);

            var postModel = new PostInputViewModel
            {
                Title       = "Test Post",
                Author      = "*****@*****.**",
                FullContent = "Some test post content",
                Tags        = "Baking, Cakes"
            };

            await service.CreatePost(postModel);

            var commentModel = new CommentInputViewModel
            {
                AuthorName = "*****@*****.**",
                Content    = "Test comment",
                PostId     = 1
            };

            //Act
            await service.CreateComment(commentModel);

            var comment = this.commentRepo.All().First();

            //Assert
            Assert.Contains <Comment>(comment, postRepo.All().First().Comments);
        }
Example #8
0
        public async Task GetPostsByTag_WithDeletedPost_ShouldThrow()
        {
            //Arrange
            var db = this.SetDb();

            var service = await this.Setup(db);

            var postModelA = new PostInputViewModel
            {
                Title       = "Test Post A",
                Author      = "*****@*****.**",
                FullContent = "Some test post content",
                Tags        = "Cakes"
            };

            await service.CreatePost(postModelA);

            var post = await this.postRepo.GetByIdAsync(1);

            post.IsDeleted = true;

            await this.postRepo.SaveChangesAsync();

            //Act

            //Assert
            Assert.Throws <InvalidOperationException>(() => service.GetPostsByTag("Cakes"));
        }
Example #9
0
        public async Task GetCommentToEditOrDelete_WithInValidCommentId_ShouldThrow()
        {
            //Arrange
            var db = this.SetDb();

            var service = await this.Setup(db);

            var postModel = new PostInputViewModel
            {
                Title       = "Test Post",
                Author      = "*****@*****.**",
                FullContent = "Some test post content",
                Tags        = "Baking, Cakes"
            };

            await service.CreatePost(postModel);

            var commentModel = new CommentInputViewModel
            {
                AuthorName = "*****@*****.**",
                Content    = "Test comment",
                PostId     = 1
            };

            await service.CreateComment(commentModel);

            //Act

            //Assert
            await Assert.ThrowsAsync <NullReferenceException>(async() => await service.GetCommentToEditOrDelete(2));
        }
        public async Task <IActionResult> NewPost(PostInputViewModel post)
        {
            if (this.ModelState.IsValid == false)
            {
                return(this.View(post));
            }

            string postId = this.usersPostsService.AddPostToUser(this.User.FindFirstValue(ClaimTypes.NameIdentifier), post.Description);

            foreach (var photo in post.Photos)
            {
                var photoContent = await this.GetFileContent(photo);

                var photoId = await this.usersPostsService.AddPhotoToPost(postId);

                await this.SavePhotoToLocalSystemAsync(photoId, photoContent);
            }

            foreach (var video in post.Videos)
            {
                var videoContent = await this.GetFileContent(video);

                var videoId = await this.usersPostsService.AddVideoToPost(postId);

                await this.SavePhotoToLocalSystemAsync(videoId, videoContent);
            }

            return(this.Redirect("/"));
        }
Example #11
0
        public async Task <IActionResult> CreateAsync(PostInputViewModel input)
        {
            var userId = UserId();
            await _postService.CreateAsync(input, userId);

            return(Ok());
        }
Example #12
0
        public async Task GetCommentToEditOrDelete_WithValidCommentId_ShouldReturnComment()
        {
            //Arrange
            var db = this.SetDb();

            var service = await this.Setup(db);

            var postModel = new PostInputViewModel
            {
                Title       = "Test Post",
                Author      = "*****@*****.**",
                FullContent = "Some test post content",
                Tags        = "Baking, Cakes"
            };

            await service.CreatePost(postModel);

            var commentModel = new CommentInputViewModel
            {
                AuthorName = "*****@*****.**",
                Content    = "Test comment",
                PostId     = 1
            };

            await service.CreateComment(commentModel);

            //Act
            var comment = service.GetCommentToEditOrDelete(1);

            var expectedCommentId = 1;
            var actualCommentId   = comment.Id;

            //Assert
            Assert.Equal(expectedCommentId, actualCommentId);
        }
Example #13
0
        public async Task <IActionResult> Comment(PostInputViewModel input)
        {
            if (this.ModelState.IsValid)
            {
                var userId = this.userManager.GetUserId(this.User);

                await this.commentService.CreateAsync <PostInputViewModel>(input, userId);
            }

            return(this.RedirectToAction(nameof(this.Discussion), new { id = input.DiscussionId }));
        }
Example #14
0
        public async Task <IActionResult> Add(PostInputViewModel postInputModel)
        {
            if (!this.ModelState.IsValid)
            {
                return(this.View(postInputModel));
            }

            var userId = this.User.FindFirst(ClaimTypes.NameIdentifier).Value;
            var postId = await this.postService.AddPostAsync(postInputModel, userId);

            return(this.Redirect($"/Blogs/Details/{postId}"));
        }
Example #15
0
        public async Task <string> AddPostAsync(PostInputViewModel postInputModel, string userId)
        {
            var post = this.mapper.Map <Post>(postInputModel);

            post.IsDeleted = false;
            post.CreatorId = userId;
            await this.db.Posts.AddAsync(post);

            await this.db.SaveChangesAsync();

            return(post.Id);
        }
Example #16
0
        public async Task <ActionResult <PostViewModel> > CreatePost(PostInputViewModel viewModel)      // null reference happening with viewModel
        {
            if (viewModel == null)
            {
                return(BadRequest());
            }

            Post createdPost = await PostService.AddPost(Mapper.Map <Post>(viewModel));

            return(CreatedAtAction(nameof(Get_PostId),
                                   new { id = createdPost.Id },
                                   Mapper.Map <PostViewModel>(createdPost)));
        }
Example #17
0
        public async Task <IActionResult> SoftDeletePost(PostInputViewModel model)
        {
            try
            {
                await this.forumService.MarkPostAsDeleted(model);
            }
            catch (Exception e)
            {
                ViewData["Errors"] = e.Message;

                return(this.View("Error"));
            }

            return(this.RedirectToAction("Index"));
        }
Example #18
0
        public async Task UpdateComment_WithValidModel_ShouldSaveUpdatedComment()
        {
            //Arrange
            var db = this.SetDb();

            var service = await this.Setup(db);

            var postModel = new PostInputViewModel
            {
                Title       = "Test Post",
                Author      = "*****@*****.**",
                FullContent = "Some test post content",
                Tags        = "Baking, Cakes"
            };

            await service.CreatePost(postModel);

            var commentModel = new CommentInputViewModel
            {
                AuthorName = "*****@*****.**",
                Content    = "Test comment content",
                PostId     = 1
            };

            await service.CreateComment(commentModel);

            var comment = await this.commentRepo.GetByIdAsync(1);

            db.Entry(comment).State = EntityState.Detached;

            var model = this.Mapper.Map <Comment, EditCommentViewModel>(comment);

            model.FullContent = model.FullContent;
            model.Content     = "Edit content.";

            //Act
            await service.UpdateComment(model);

            var expectedCommentContent = "Edit content.";
            var actualCommentContent   = (await this.commentRepo.GetByIdAsync(1)).Content;

            //Assert
            Assert.Equal(expectedCommentContent, actualCommentContent);
        }
Example #19
0
        public async Task MarkPostAsDeleted(PostInputViewModel model)
        {
            var post = await this.postRepo.GetByIdAsync(model.Id);

            post.IsDeleted = true;

            this.postRepo.Update(post);

            try
            {
                await this.postRepo.SaveChangesAsync();
            }
            catch (Exception e)
            {
                this.logger.LogDebug(e.Message);

                throw new InvalidOperationException("Sorry, an error occurred while trying to delete your post");
            }
        }
Example #20
0
        public async Task GetAllPosts_ShouldGetDeletedAndNotDeletedPosts()
        {
            //Arrange
            var db = this.SetDb();

            var service = await this.Setup(db);

            var postModelA = new PostInputViewModel
            {
                Title       = "Test Post A",
                Author      = "*****@*****.**",
                FullContent = "Some test post content",
                Tags        = "Baking"
            };

            await service.CreatePost(postModelA);

            var postModelB = new PostInputViewModel
            {
                Title       = "Test Post B",
                Author      = "*****@*****.**",
                FullContent = "Some test post content",
                Tags        = "Baking"
            };

            await service.CreatePost(postModelB);

            var post = await this.postRepo.GetByIdAsync(2);

            post.IsDeleted = true;

            await this.postRepo.SaveChangesAsync();

            //Act
            var allPosts = service.GetAllPosts();

            var expectedPostCount = 2;
            var actualPostCount   = allPosts.Count();

            //Assert
            Assert.Equal(expectedPostCount, actualPostCount);
        }
Example #21
0
        public async Task MarkCommentAsDeleted_WithValidModel_ShouldMarkCommentAsDeleted()
        {
            //Arrange
            var db = this.SetDb();

            var service = await this.Setup(db);

            var postModel = new PostInputViewModel
            {
                Title       = "Test Post",
                Author      = "*****@*****.**",
                FullContent = "Some test post content",
                Tags        = "Baking, Cakes"
            };

            await service.CreatePost(postModel);

            var commentModel = new CommentInputViewModel
            {
                AuthorName = "*****@*****.**",
                Content    = "Test comment",
                PostId     = 1
            };

            await service.CreateComment(commentModel);

            var comment = await this.commentRepo.GetByIdAsync(1);

            var model = this.Mapper.Map <Comment, EditCommentViewModel>(comment);

            model.FullContent = this.sanitizer.Sanitize(model.FullContent);
            model.Content     = this.sanitizer.Sanitize(model.Content);

            //Act
            await service.MarkCommentAsDeleted(model);

            var expectedCommentIsDeleted = true;
            var actualCommentIsDeleted   = comment.IsDeleted;

            //Assert
            Assert.Equal(expectedCommentIsDeleted, actualCommentIsDeleted);
        }
Example #22
0
        public async Task UpdateAsync(string id, PostInputViewModel input)
        {
            var count = await _repository.CountAsync(SqlConstants.CategoriesCountByIds, new { ids = input.CategoryIds.ToArray() });

            if (count < input.CategoryIds.Count)
            {
                throw new BlogException(StatusCodes.Status400BadRequest, $"参数错误:{nameof(input.CategoryIds)}");
            }

            var parameters = new
            {
                id,
                input.Title,
                input.Content,
                ContentAbstract = input.Content.GetPostAbstract(_blogSettings.PostAbstractWords),
                input.CategoryIds
            };

            await _repository.UpdateAsync(SqlConstants.UpdatePost, parameters);
        }
Example #23
0
        public async Task CreatePost_WithEmptyContent_ShouldThrow()
        {
            //Arrange
            var db = this.SetDb();

            var service = await this.Setup(db);

            var postModel = new PostInputViewModel
            {
                Title       = "Test Post",
                Author      = "*****@*****.**",
                FullContent = "",
                Tags        = "Baking, Cakes"
            };

            //Act

            //Assert
            await Assert.ThrowsAsync <NullReferenceException>(async() => await service.CreatePost(postModel));
        }
Example #24
0
        public async Task UpdatePost_WithValidTags_ShouldSaveUpdatedPost()
        {
            //Arrange
            var db = this.SetDb();

            var service = await this.Setup(db);

            var postModel = new PostInputViewModel
            {
                Title       = "Test Post",
                Author      = "*****@*****.**",
                FullContent = "Some test post content",
                Tags        = "Baking"
            };

            await service.CreatePost(postModel);

            var post = await this.postRepo.GetByIdAsync(1);

            db.Entry(post).State = EntityState.Detached;

            var model = new PostInputViewModel
            {
                Id          = post.Id,
                Author      = post.Author.UserName,
                Title       = post.Title,
                FullContent = post.FullContent,
                Tags        = "Baking, Cakes",
                IsDeleted   = post.IsDeleted
            };

            //Act
            await service.UpdatePost(model);

            var expectedTags = "Baking, Cakes";
            var tags         = (await this.postRepo.GetByIdAsync(1)).Tags;
            var acutalTags   = string.Join(", ", tags.Select(tp => tp.Tag.Name));

            //Assert
            Assert.Equal(expectedTags, acutalTags);
        }
Example #25
0
        public async Task UpdateComment_WithEmptyContent_ShouldThrow()
        {
            //Arrange
            var db = this.SetDb();

            var service = await this.Setup(db);

            var postModel = new PostInputViewModel
            {
                Title       = "Test Post",
                Author      = "*****@*****.**",
                FullContent = "Some test post content",
                Tags        = "Baking, Cakes"
            };

            await service.CreatePost(postModel);

            var commentModel = new CommentInputViewModel
            {
                AuthorName = "*****@*****.**",
                Content    = "Test comment content",
                PostId     = 1
            };

            await service.CreateComment(commentModel);

            var comment = await this.commentRepo.GetByIdAsync(1);

            db.Entry(comment).State = EntityState.Detached;

            var model = this.Mapper.Map <Comment, EditCommentViewModel>(comment);

            model.Content = "";

            //Act

            //Assert
            await Assert.ThrowsAsync <NullReferenceException>(async() => await service.UpdateComment(model));
        }
Example #26
0
        public async Task GetPostsByTag_WithInValidTag_ShouldThrow()
        {
            //Arrange
            var db = this.SetDb();

            var service = await this.Setup(db);

            var postModelA = new PostInputViewModel
            {
                Title       = "Test Post A",
                Author      = "*****@*****.**",
                FullContent = "Some test post content",
                Tags        = "Cakes"
            };

            await service.CreatePost(postModelA);

            //Act

            //Assert
            Assert.Throws <InvalidOperationException>(() => service.GetPostsByTag("Sponge"));
        }
Example #27
0
        public async Task GetPostById_WithInValidId_ShouldThrow()
        {
            //Arrange
            var db = this.SetDb();

            var service = await this.Setup(db);

            var postModelA = new PostInputViewModel
            {
                Title       = "Test Post A",
                Author      = "*****@*****.**",
                FullContent = "Some test post content",
                Tags        = "Baking, Cakes"
            };

            await service.CreatePost(postModelA);

            //Act

            //Assert
            await Assert.ThrowsAsync <NullReferenceException>(async() => await service.GetPostById(2));
        }
Example #28
0
        public async Task GetAllMyComments_WithNoComments_ShouldThrow()
        {
            //Arrange
            var db = this.SetDb();

            var service = await this.Setup(db);

            var postModel = new PostInputViewModel
            {
                Title       = "Test Post",
                Author      = "*****@*****.**",
                FullContent = "Some test post content",
                Tags        = "Baking, Cakes"
            };

            await service.CreatePost(postModel);

            //Act

            //Assert
            Assert.Throws <InvalidOperationException>(() => service.GetAllMyComments("*****@*****.**"));
        }
Example #29
0
        public async Task <IActionResult> CreatePost(PostInputViewModel model)
        {
            if (!ModelState.IsValid)
            {
                var errors = this.ModelState.Values.SelectMany(p => p.Errors).Select(e => e.ErrorMessage).ToList();

                var errorModel = this.errorService.GetErrorModel(errors);

                return(View("Error", errorModel));
            }

            try
            {
                await this.forumService.CreatePost(model);
            }
            catch (Exception e)
            {
                ViewData["Errors"] = e.Message;
                return(this.View("Error"));
            }

            return(RedirectToAction("Index"));
        }
Example #30
0
        public async Task CreateAsync(PostInputViewModel input, string userId)
        {
            var count = await _repository.CountAsync(SqlConstants.CategoriesCountByIds, new { ids = input.CategoryIds.ToArray() });

            if (count < input.CategoryIds.Count)
            {
                throw new BlogException(StatusCodes.Status400BadRequest, $"参数错误:{nameof(input.CategoryIds)}");
            }

            var id = await _repository.GenerateIdAsync();

            var post = new
            {
                id,
                input.Title,
                input.Content,
                ContentAbstract = input.Content.GetPostAbstract(_blogSettings.PostAbstractWords),
                CategoryIds     = input.CategoryIds,
                CreatorId       = userId
            };

            await _repository.InsertAsync(SqlConstants.AddPost, post);
        }