Пример #1
0
        public async Task AddCommentShouldAddCommentWhenGameExists()
        {
            //arrange
            var existingGame = new Games.Core.Entties.Game.Game(Guid.NewGuid().ToString("N"), "test", "Test", "test", "Test", DateTime.UtcNow);

            _gameRepositoryMock.Setup(x => x.Get(existingGame.Id, CancellationToken.None)).ReturnsAsync(existingGame);
            var comment = new Comment("test", "test", "test", DateTime.UtcNow);

            //act
            var result = await _commentService.AddComment(existingGame.Id, comment, CancellationToken.None);

            //assert
            _gameRepositoryMock.Verify(x => x.Update(It.IsAny <Games.Core.Entties.Game.Game>(), CancellationToken.None), Times.Once);
        }
        public async Task ReturnCorrectViewModel()
        {
            var dabataseName = nameof(Throw_WhenText_IsEmpty);

            var options = CommentTestUtil.GetOptions(dabataseName);

            var mappingProviderMock = new Mock <IMappingProvider>();

            string commentText = "Very interesting.Would love to see it!";

            string title = "Avengers EndGame";

            string userName = "******";

            mappingProviderMock.Setup(x => x.MapTo <CommentViewModel>(It.IsAny <Comment>())).Returns(new CommentViewModel());

            using (var actAndAssertContext = new MovieManagementContext(options))
            {
                var sut = new CommentService(actAndAssertContext, mappingProviderMock.Object);

                var result = await sut.AddComment(commentText, title, userName);

                Assert.IsInstanceOfType(result, typeof(CommentViewModel));
            }
        }
        public ActionResult AddComment(Comment comment /*, HttpPostedFileBase uploadFile*/)
        {
            if ((AccountLogin)Session["account"] != null)
            {
                var account = (AccountLogin)Session["account"];
                if (comment.Description == null && comment.Image == null)
                {
                    return(View(comment));
                }
                var fHinh = Request.Files["myFileImage"];
                if (fHinh != null)
                {
                    var pathHinh = Server.MapPath("~/Images/Comments/" + fHinh.FileName);
                    fHinh.SaveAs(pathHinh);
                    comment.Image = fHinh.FileName;
                }
                else
                {
                    comment.Image = null;
                }

                comment.Time        = DateTime.Now;
                comment.AccountName = account.AccountName;
                var cmt = _commentService.AddComment(comment);
                if (cmt != null)
                {
                    return(View("DetailNews"));
                }
                return(View(comment));
            }
            return(View(comment));
        }
Пример #4
0
        public void AddCommentShouldAddsCommentAndReturnCommentIdCorrect()
        {
            // Arrange

            var options = new DbContextOptionsBuilder <WAGDbContext>()
                          .UseInMemoryDatabase(databaseName: "Add_Comment_Db")
                          .Options;

            var dbContext = new WAGDbContext(options);
            var service   = new CommentService(dbContext);

            var userId         = Guid.NewGuid().ToString();
            var articleId      = 5;
            var commentContent = "Test Comment Text";

            // Act
            var commentId = service.AddComment(userId, articleId, commentContent);

            var addedComment = dbContext
                               .Comments
                               .FirstOrDefault(comment => comment.Id == commentId);

            // Assert
            Assert.NotNull(addedComment);
            Assert.Equal(userId, addedComment.WAGUserId);
            Assert.Equal(articleId, addedComment.ArticleId);
            Assert.Equal(commentContent, addedComment.TextBody);
        }
        public async Task AddNewComment_WhenAllParametersAreValid()
        {
            var dabataseName = nameof(Throw_WhenText_IsEmpty);

            var options = CommentTestUtil.GetOptions(dabataseName);

            var mappingProviderMock = new Mock <IMappingProvider>();

            string commentText = "Very interesting.Would love to see it!";

            string title = "Avengers EndGame";

            string userName = "******";


            using (var arrangeContext = new MovieManagementContext(options))
            {
                var sut = new CommentService(arrangeContext, mappingProviderMock.Object);


                await sut.AddComment(commentText, title, userName);

                arrangeContext.SaveChanges();
            }

            using (var actAndAssertContext = new MovieManagementContext(options))
            {
                Assert.IsTrue(actAndAssertContext.Comments.Count() == 1);
                Assert.IsTrue(actAndAssertContext.Comments.Any(m => m.Text == commentText));
            }
        }
Пример #6
0
        private async void PostComment()
        {
            if (this.IsBusy)
            {
                return;
            }
            this.IsBusy = true;

            if (!this.CanPostComment)
            {
                this.IsBusy = false;
                return;
            }

            var loading = DependencyService.Get <ILoadingHelper>();

            loading.Show();

            if (!CrossConnectivity.Current.IsConnected)
            {
                DependencyService.Get <IMessageHelper>().LongAlert($"Gagal mengirim. Periksa kembali koneksi internet anda.");
                this.IsBusy = false;
                return;
            }

            var result = await CommentService.AddComment(
                this.CommentText,
                this.User.ID,
                this.SelectedMenu.ID,
                this.User.Username,
                this.User.Password);

            switch (result)
            {
            case ServerResponseStatus.INVALID:
                await this.NavigationService.CurrentPage.DisplayAlert("Gagal Memposting Komentar", "Terjadi kesalahan pada server. Coba lagi nanti.", "OK");

                this.IsBusy = false;
                loading.Hide();
                return;

            case ServerResponseStatus.ERROR:
                await this.NavigationService.CurrentPage.DisplayAlert("Gagal Memposting Komentar", "Terjadi kesalahan pada server. Coba lagi nanti.", "OK");

                this.IsBusy = false;
                loading.Hide();
                return;
            }

            var newComment = (await CommentService.GetComments(this.SelectedMenu.ID, 1, 1)).Item1[0];

            this.CommentList.Insert(0, newComment);

            this.CommentText = string.Empty;

            loading.Hide();

            this.IsBusy = false;
        }
Пример #7
0
        public void AddCommentTest()
        {
            // Arrange
            var expected = new CommentDto
            {
                Id     = "1",
                BookId = "1",
                Book   = new Book()
                {
                    Id          = "1",
                    Title       = "Stephen",
                    Description = "King"
                },
                UserId = "1",
                User   = new UserProfile()
                {
                    Id        = "1",
                    FirstName = "Oleksii",
                    LastName  = "Rudenko"
                },
                Message   = "Best book ever",
                TimeStamp = DateTime.Now
            };
            var repository = new Mock <IRepository <Comment> >();

            repository.Setup(r => r.Get(expected.Id)).Returns(new Comment
            {
                Id     = "1",
                BookId = "1",
                Book   = new Book()
                {
                    Id          = "1",
                    Title       = "Stephen",
                    Description = "King"
                },
                UserId = "1",
                User   = new UserProfile()
                {
                    Id        = "1",
                    FirstName = "Oleksii",
                    LastName  = "Rudenko"
                },
                Message   = "Best book ever",
                TimeStamp = DateTime.Now
            });
            var mapper = new Mock <IMapper>();

            mapper.Setup(m => m.Map <Comment, CommentDto>(It.IsAny <Comment>())).Returns(expected);
            mapper.Setup(m => m.Map <CommentDto, Comment>(It.IsAny <CommentDto>())).Returns(new Comment());
            var svc = new CommentService(repository.Object, mapper.Object);

            // Act
            svc.AddComment(expected);

            // Assert
            mapper.Verify(m => m.Map <CommentDto, Comment>(It.IsAny <CommentDto>()), Times.Once());
            repository.Verify(r => r.Create(It.IsAny <Comment>()), Times.Once());
            repository.Verify(r => r.Save(), Times.Once());
        }
        public async Task <IActionResult> AddComment(CommentViewModel model)
        {
            var user = await UserService.GetUserByEmail(User.Identity.Name);

            var comment = await CommentService.AddComment(user.UserId, model.MaterialId, model.CommentText);

            return(Ok(comment));
        }
Пример #9
0
        public IActionResult AddComment([FromForm] AddCommentViewModel model)
        {
            var userEmail = userManager.GetUserName(User);
            var user      = userService.GetUserByUserEmail(userEmail);

            commentService.AddComment(model.text, model.reviewTitle, user);
            return(View("DashboardView", "Dashboard"));
        }
        public IHttpActionResult Post([FromBody] CommentModel comment)
        {
            var userInfo = CallContext.GetData("UserInfo") as UserDetails;

            comment.UserId = userInfo.UserId;

            commentService.AddComment(comment);
            return(Ok());
        }
Пример #11
0
        public ActionResult Post(CommentModel comment)
        {
            string UserId = Request.Headers["UserId"];

            JObject objResponse = _commentService.AddComment(comment, UserId, null);

            if (200 == (int)objResponse["status"])
            {
                return(new ObjectResult(objResponse));
            }
            else if (404 == (int)objResponse["status"])
            {
                return(new NotFoundObjectResult(objResponse));
            }
            else
            {
                return(new BadRequestObjectResult(objResponse));
            }
        }
Пример #12
0
        public async Task <IActionResult> AddComment(NewCommentViewModel newComment)
        {
            var loggedUser = await _userManager.GetUserAsync(User);

            newComment.UserId = loggedUser.Id;

            _commentService.AddComment(newComment);

            return(RedirectToAction("Index", "Post"));
        }
        public IActionResult Add(int id, [FromBody] CommentDTO comment)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            comment.ResourceId = id;
            _commentService.AddComment(comment, User.Identity.Name);

            return(Ok());
        }
Пример #14
0
        public void AddComment_ShouldCallInsertCommentOnceWhenCommentEntity()
        {
            // Arrange
            string gameKey = "c21";

            // Act
            _commentService.AddComment(_comment, gameKey);

            // Assert
            _commentRepository.Verify(a => a.Insert(_comment), Times.Once);
        }
Пример #15
0
 public ActionResult <BaseResponseModel> PostAddComment([FromBody] CommentInsertModel commentInsertModel)
 {
     try
     {
         commentService.AddComment(commentInsertModel);
         return(new SuccessResponseModel <bool>(true));
     }
     catch (Exception ex)
     {
         return(new BaseResponseModel(ex.Message));
     }
 }
Пример #16
0
        public ActionResult Comment(Guid id, firewood.CommentModels model)
        {
            Guid uid;

            if (Session["User"] != null)
            {
                uid = new Guid(Session["User"].ToString());
            }
            else
            {
                return(Redirect(SiteConfig.SiteUrl + "/User/PostLogin"));
            }
            model.ActID = id;

            //显示活动详情
            Activity act = showAct(id);

            ViewData["TopActList"] = actService.GetTopActList();
            ViewData["OrgList"]    = orgService.ShowAllOrg(9, 1);

            if (joinService.IsExist(model.ActID, uid))
            {
                ViewBag.Button = "您已参与";
            }
            else
            {
                ViewBag.Button = "我想参加";
            }

            if (!ModelState.IsValid)
            {
                return(View("Index", model));
            }

            Comment comment = new Comment();

            comment.ComID   = Guid.NewGuid();
            comment.UserID  = uid;
            comment.OrgID   = act.OrgID;
            comment.ActID   = model.ActID;
            comment.ComCon  = model.ComCon;
            comment.ComTime = DateTime.Now;
            comment.Type    = 1;
            if (!commentService.AddComment(comment))
            {
                return(Content("<script>alert('系统异常');</script>"));
            }

            showComment(id);

            return(Redirect(SiteConfig.SiteUrl + "/Act/Index/ID/" + id));
        }
Пример #17
0
        public IActionResult AddComment(string body, long postId)
        {
            if (body is null)
            {
                body = string.Empty;
            }
            commentService.AddComment(body, postId);

            return(Json(new
            {
                flag = true
            }));
        }
Пример #18
0
 public ActionResult AddComment(string anonymous, Comment cm, int productId)
 {
     if (anonymous != null)
     {
         cm.Email = "Anonymous";
     }
     else if (!System.Web.HttpContext.Current.User.Identity.IsAuthenticated)
     {
         return(RedirectToAction("Login", "Account"));
     }
     commentService.AddComment(cm);
     return(RedirectToAction("Detail", new { id = productId }));
 }
Пример #19
0
        public void ThenCommentIsNotDisplayedUnderThePost(string yesOrNot)
        {
            GivenThereIsSomePost();
            bool areDisplayed = yesOrNot != "not";

            if (areDisplayed)
            {
                Assert.IsTrue(CommentService.IsCommentDisplayed(CommentService.AddComment(CommentBuilder.GenerateComment())));
            }
            else
            {
                Assert.IsFalse(CommentService.IsCommentDisplayed(CommentService.AddComment(CommentBuilder.GenerateComment())));
            }
        }
Пример #20
0
        public void AddComment_Comment_CreateCalled()
        {
            var fakeCommentDTO = new CommentDTO()
            {
                Id = Guid.NewGuid(), Name = "3", Body = "3"
            };
            var fakeComment = _mapper.Map <Comment>(fakeCommentDTO);

            _uow.Setup(x => x.Comments.Create(fakeComment));

            _sut.AddComment(fakeCommentDTO);

            _uow.Verify(uow => uow.Comments.Create(It.IsAny <Comment>()), Times.Once);
        }
Пример #21
0
        public async Task <IActionResult> Comment(HomeVm vm, int id)
        {
            var comment = new Comment();

            ClaimsPrincipal currentUser   = this.User;
            var             currentUserId = currentUser.FindFirst(ClaimTypes.NameIdentifier).Value;

            comment.Description = vm.Description;
            comment.UserId      = currentUserId;
            comment.PostId      = id;
            var UserName = commentService.GetUserNameById(currentUserId);

            comment.UserName = UserName;

            string uniqueFileName = null;

            if (vm.CommentImage == null)
            {
                commentService.AddComment(comment);
            }

            else if (commentService.IsImage(vm.Image) && vm.Image.Length < (3 * 1024 * 1024))
            {
                string uploadFolder = Path.Combine(hostingEnvironment.WebRootPath, "images");
                uniqueFileName = Guid.NewGuid().ToString() + "_" + vm.Image.FileName;
                string filePath = Path.Combine(uploadFolder, uniqueFileName);

                using (var fileStream = new FileStream(filePath, FileMode.Create))
                {
                    vm.Image.CopyTo(fileStream);
                }
                comment.ImagePath = uniqueFileName;
                commentService.AddComment(comment);
            }

            return(RedirectToAction(nameof(Index)));
        }
        public void CommentFactory_ShouldCallCreateCommentOnce_WhenAddCommentIsCalled()
        {
            // Arrange
            var unitOfWorkMock     = new Mock <IUnitOfWork>();
            var commentRepoMock    = new Mock <IRepository <Comment> >();
            var commentFactoryMock = new Mock <ICommentFactory>();

            var commentService = new CommentService(unitOfWorkMock.Object, commentRepoMock.Object, commentFactoryMock.Object);

            //Act
            commentService.AddComment(new Guid(), "_", "_");

            //Assert
            commentFactoryMock.Verify(x => x.CreateComment(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <DateTime>(), It.IsAny <Guid>()), Times.Once);
        }
Пример #23
0
        public IActionResult AddComment(Comment comment)
        {
            var userId = postService.GetUserIdByPostId(comment.PostId);

            if (!friendService.AreFriends(userId, currentUser.Id) &&
                !(currentUser.Id == userId))
            {
                return(AccessDenied());
            }

            comment.UserId = currentUser.Id;
            commentService.AddComment(comment);

            return(Ok());
        }
        public void UnitOfWork_ShouldCallCommitOnce_WhenAddCommentIsCalled()
        {
            // Arrange
            var unitOfWorkMock     = new Mock <IUnitOfWork>();
            var commentRepoMock    = new Mock <IRepository <Comment> >();
            var commentFactoryMock = new Mock <ICommentFactory>();

            var commentService = new CommentService(unitOfWorkMock.Object, commentRepoMock.Object, commentFactoryMock.Object);

            //Act
            commentService.AddComment(new Guid(), "_", "_");

            //Assert
            unitOfWorkMock.Verify(x => x.Commit(), Times.Once);
        }
Пример #25
0
 public JsonResult AddComment(AddComment comment)
 {
     if (comment.NewsId <= 0)
     {
         return(Json(new ResponseModel {
             code = 0, result = "News does not exist."
         }));
     }
     if (string.IsNullOrEmpty(comment.Contents))
     {
         return(Json(new ResponseModel {
             code = 0, result = "Content is empty."
         }));
     }
     return(Json(_commentService.AddComment(comment)));
 }
Пример #26
0
 public IActionResult AddComment(AddComment comment)
 {
     if (comment.NewsId <= 0)
     {
         return(Json(new ResponseModel {
             code = 0, result = "新闻不存在"
         }));
     }
     if (string.IsNullOrEmpty(comment.Contents))
     {
         return(Json(new ResponseModel {
             code = 0, result = "内容不能为空"
         }));
     }
     return(Json(_commentService.AddComment(comment)));
 }
Пример #27
0
        public ActionResult AddComment(PublicationPanelViewModel pubCom)
        {
            if (pubCom.NewCommentText.Length > 0)
            {
                ICommentService commentService = new CommentService();
                IUserService    userService    = new UserService();
                string          userId         = User.Identity.GetUserId();

                commentService.AddComment(pubCom.NewCommentText, pubCom.PublicationId, userId);

                return(Redirect("Open/" + pubCom.PublicationId.ToString()));
            }
            else
            {
                return(View("Open", pubCom));
            }
        }
        public void TestAddCommentCallsRepositoryAddComment()
        {
            Mock <ICommentRepository>  mockCommentRepository  = new Mock <ICommentRepository>();
            Mock <IDocumentRepository> mockDocumentRepository = new Mock <IDocumentRepository>();
            Mock <IUserRepository>     mockUserRepository     = new Mock <IUserRepository>();

            ICommentService commentService = new CommentService
            {
                CommentRepository  = mockCommentRepository.Object,
                DocumentRepository = mockDocumentRepository.Object,
                UserRepository     = mockUserRepository.Object
            };

            IEnumerable <Comment> fakeComments = GetFakeComment();
            Comment  fakeComment  = fakeComments.ElementAt(1);
            Document fakeDocument = GetFakeDocument();
            User     fakeUser     = GetFakeUser();

            mockCommentRepository
            .Setup(wl => wl.AddComment(fakeComment));

            mockDocumentRepository
            .Setup(wl => wl.Exists(fakeDocument.Id))
            .Returns(true);

            mockDocumentRepository
            .Setup(wl => wl.GetById(fakeDocument.Id))
            .Returns(fakeDocument);

            mockUserRepository
            .Setup(wl => wl.Exists(fakeUser.Email))
            .Returns(true);

            mockUserRepository
            .Setup(wl => wl.GetByEmail(fakeUser.Email))
            .Returns(fakeUser);

            commentService.AddComment(fakeUser.Email, fakeDocument.Id.ToString(), fakeComment);

            mockCommentRepository.VerifyAll();
            mockDocumentRepository.VerifyAll();
            mockUserRepository.VerifyAll();

            Assert.IsTrue(true);
        }
Пример #29
0
        public async Task <ActionResult> AddComment()
        {
            using (var reader = new StreamReader(Request.Body))
            {
                var body = await reader.ReadToEndAsync();

                var json = JsonSerializer.Deserialize <Dictionary <string, dynamic> >(body);
                try
                {
                    _commentService.AddComment(json);
                    return(Ok());
                }
                catch (Exception e)
                {
                    return(BadRequest(e));
                }
            }
        }
Пример #30
0
        public JsonResult AddComment(AddComment comment)
        {
            var userList = HttpContext.Session.Get <UsersModel>("CacheUser");

            if (comment.NewsId <= 0)
            {
                return(Json(new ResponseModel {
                    code = 0, result = "新闻不存在"
                }));
            }
            if (string.IsNullOrEmpty(comment.Contents))
            {
                return(Json(new ResponseModel {
                    code = 0, result = "内容不能为空"
                }));
            }
            return(Json(_commentService.AddComment(comment, userList.data)));
        }