Example #1
0
        public void UpsertShouldModifyTheGivenComment()
        {
            var options = new DbContextOptionsBuilder <ExpensesDbContext>()
                          .UseInMemoryDatabase(databaseName: nameof(UpsertShouldModifyTheGivenComment))
                          .Options;

            using (var context = new ExpensesDbContext(options))
            {
                var commentsService = new CommentService(context);
                var toAdd           = new CommentPostModel()

                {
                    Important = true,
                    Text      = "An important expense",
                };

                var added  = commentsService.Create(toAdd, null);
                var update = new CommentPostModel()
                {
                    Important = false
                };

                var toUp         = commentsService.Create(update, null);
                var updateResult = commentsService.Upsert(added.Id, added);
                Assert.IsNotNull(updateResult);
                Assert.False(toUp.Important);
            }
        }
Example #2
0
        public void Create_RigthData_returnTrue()
        {
            CommentDTO comment = new CommentDTO()
            {
                Id = new Guid("93f0c600-9c1b-48b4-9606-08d7141a36bc"), UserId = new Guid("19824dd6-67bf-4a52-24a7-08d705fcf8d4"), EventId = new Guid("d3994f53-1e0d-4eda-d0e8-08d70c4f9464"), Text = "Text"
            };
            Comments com = new Comments()
            {
                Id = new Guid("93f0c600-9c1b-48b4-9606-08d7141a36bc"), UserId = new Guid("19824dd6-67bf-4a52-24a7-08d705fcf8d4"), EventId = new Guid("d3994f53-1e0d-4eda-d0e8-08d70c4f9464"), Text = "Text"
            };

            mockUnitOfWork.Setup(u => u.UserRepository.Get(new Guid("19824dd6-67bf-4a52-24a7-08d705fcf8d4"))).Returns(new User()
            {
                Email = "*****@*****.**", Id = new Guid("19824dd6-67bf-4a52-24a7-08d705fcf8d4")
            });
            mockUnitOfWork.Setup(u => u.EventRepository.Get(new Guid("d3994f53-1e0d-4eda-d0e8-08d70c4f9464"))).Returns(new Event()
            {
                Id = new Guid("d3994f53-1e0d-4eda-d0e8-08d70c4f9464")
            });
            mockUnitOfWork.Setup(u => u.CommentsRepository.Insert(com));

            var rez = service.Create(comment);

            Assert.IsTrue(rez.Result.Successed);
        }
Example #3
0
        public async Task Create_ValidModel_SuccessfullyAdded()
        {
            var comment = GetTestModel();
            var result  = await _service.Create(comment);

            _mockSet.Verify(m => m.Add(It.IsAny <Comment>()), Times.Once());
            _mockContext.Verify(m => m.SaveChangesAsync(), Times.Once());
            Assert.AreEqual(comment.PostId, result.PostId);
            Assert.AreEqual(comment.Text, result.Text);
        }
        public void CreateComment_TestNullParameter_ActualFalse()
        {
            //Arrange
            CommentWriteDTO commentWriteDTO = null;

            //Act
            var action = commentService.Create(commentWriteDTO);

            //Assert
            Assert.AreEqual(false, action.Result.status);
        }
Example #5
0
        public void Create_Void_ReturnId()
        {
            var list = new List <CommentItem>()
            {
                _comment
            };

            Mock.Get(_commentRepository).Setup(x => x.Create(_comment)).Returns(_comment.Id);
            Mock.Get(_commentRepository).Setup(x => x.GetListByTaskId(_comment.TaskId)).Returns(list);

            var result = _commentService.Create(_comment);

            Assert.AreEqual(result, _comment.Id);
        }
Example #6
0
        protected void lkbPost_Click(object sender, EventArgs e)
        {
            try
            {
                var entry = new Trackback(EntryId, txbTitle.Text, txbUrl.Text.EnsureUrl(), string.Empty,
                                          txbBody.Text.Trim().Length > 0 ? txbBody.Text.Trim() : txbTitle.Text);
                var commentService = new CommentService(SubtextContext, null);

                if (commentService.Create(entry, true /*runFilters*/) > 0)
                {
                    ICommentSpamService feedbackService = null;
                    if (Config.CurrentBlog.FeedbackSpamServiceEnabled)
                    {
                        feedbackService = new AkismetSpamService(Config.CurrentBlog.FeedbackSpamServiceKey,
                                                                 Config.CurrentBlog, null, Url);
                    }
                    var filter = new CommentFilter(SubtextContext, feedbackService);
                    filter.FilterAfterPersist(entry);
                    Messages.ShowMessage(Constants.RES_SUCCESSNEW);
                    Edit.Visible    = false;
                    Results.Visible = true;
                }
                else
                {
                    Messages.ShowError(Constants.RES_FAILUREEDIT
                                       + " There was a baseline problem posting your Trackback.");
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex.Message, ex);
                Messages.ShowError(String.Format(Constants.RES_EXCEPTION,
                                                 Constants.RES_FAILUREEDIT, ex.Message));
            }
        }
Example #7
0
        public void GetByIdShouldReturnCommentWithCorrectId()
        {
            var options = new DbContextOptionsBuilder <ExpensesDbContext>()
                          .UseInMemoryDatabase(databaseName: nameof(GetByIdShouldReturnCommentWithCorrectId))
                          .Options;

            using (var context = new ExpensesDbContext(options))
            {
                var commentsService = new CommentService(context);
                var toAdd           = new CommentPostModel()

                {
                    Important = true,
                    Text      = "An important expense",
                };


                var current  = commentsService.Create(toAdd, null);
                var expected = commentsService.GetById(current.Id);



                Assert.IsNotNull(expected);
                Assert.AreEqual(expected.Text, current.Text);
                Assert.AreEqual(expected.Id, current.Id);
            }
        }
Example #8
0
        public IActionResult RegsterComment(string Text, string ProductId)
        {
            string UserId       = ClaimUtility.GetUserId(HttpContext.User);
            string UserFullName = ClaimUtility.GetUserFullName(HttpContext.User);

            return(Json(_commentService.Create(ProductId, Text, UserId, UserFullName)));
        }
        static FeedbackItem CreateAndUpdateFeedbackWithExactStatus(Entry entry, FeedbackType type,
                                                                   FeedbackStatusFlag status)
        {
            var feedback = new FeedbackItem(type);

            feedback.Title   = UnitTestHelper.GenerateUniqueString();
            feedback.Body    = UnitTestHelper.GenerateUniqueString();
            feedback.EntryId = entry.Id;
            feedback.Author  = "TestAuthor";

            var subtextContext = new Mock <ISubtextContext>();

            subtextContext.Setup(c => c.Cache).Returns(new TestCache());
            subtextContext.SetupBlog(Config.CurrentBlog);
            subtextContext.SetupRepository(ObjectProvider.Instance());
            subtextContext.Setup(c => c.HttpContext.Items).Returns(new Hashtable());
            subtextContext.Setup(c => c.HttpContext).Returns(new HttpContextWrapper(HttpContext.Current));

            var service = new CommentService(subtextContext.Object, null);
            int id      = service.Create(feedback, true /*runFilters*/);

            feedback        = FeedbackItem.Get(id);
            feedback.Status = status;
            FeedbackItem.Update(feedback);

            return(FeedbackItem.Get(id));
        }
Example #10
0
        public void CreateSetsDateCreated()
        {
            //arrange
            var      blog           = new Mock <Blog>();
            DateTime dateCreatedUtc = DateTime.UtcNow;

            blog.Object.Id = 1;
            var entry = new Entry(PostType.BlogPost, blog.Object)
            {
                Id = 123, BlogId = 1, CommentingClosed = false
            };
            var repository = new Mock <ObjectRepository>();

            repository.Setup(r => r.GetEntry(It.IsAny <int>(), true, true)).Returns(entry);
            var context = new Mock <ISubtextContext>();

            context.SetupGet(c => c.Repository).Returns(repository.Object);
            context.SetupGet(c => c.Blog).Returns(blog.Object);
            context.SetupGet(c => c.HttpContext.Items).Returns(new Hashtable());
            context.SetupGet(c => c.Cache).Returns(new TestCache());

            var service = new CommentService(context.Object, null);
            var comment = new FeedbackItem(FeedbackType.Comment)
            {
                EntryId = 123, BlogId = 1, Body = "test", Title = "title"
            };

            //act
            service.Create(comment, true /*runFilters*/);

            //assert
            Assert.GreaterEqualThan(comment.DateCreatedUtc, dateCreatedUtc);
            Assert.GreaterEqualThan(DateTime.UtcNow, comment.DateCreatedUtc);
        }
Example #11
0
        public JsonResult AddComment(Comment comment)
        {
            var service = new CommentService();

            service.Create(comment);
            return(Json(true));
        }
        public void CreateTrackbackSetsFeedbackTypeCorrectly()
        {
            string hostname = UnitTestHelper.GenerateUniqueString();

            Config.CreateBlog("", "username", "password", hostname, string.Empty);
            UnitTestHelper.SetHttpContextWithBlogRequest(hostname, string.Empty, string.Empty);
            Blog blog = Config.GetBlog(hostname, string.Empty);

            BlogRequest.Current.Blog = blog;

            Entry entry    = UnitTestHelper.CreateEntryInstanceForSyndication("phil", "title", "body");
            int   parentId = UnitTestHelper.Create(entry);

            var trackback      = new Trackback(parentId, "title", new Uri("http://url"), "phil", "body", blog.TimeZone.Now);
            var subtextContext = new Mock <ISubtextContext>();

            subtextContext.Setup(c => c.Blog).Returns(Config.CurrentBlog);
            //TODO: FIX!!!
            subtextContext.Setup(c => c.Repository).Returns(ObjectProvider.Instance());
            subtextContext.Setup(c => c.Cache).Returns(new TestCache());
            subtextContext.Setup(c => c.HttpContext.Items).Returns(new Hashtable());
            var commentService = new CommentService(subtextContext.Object, null);
            int id             = commentService.Create(trackback, true /*runFilters*/);

            FeedbackItem loadedTrackback = FeedbackItem.Get(id);

            Assert.IsNotNull(loadedTrackback, "Was not able to load trackback from storage.");
            Assert.AreEqual(FeedbackType.PingTrack, loadedTrackback.FeedbackType, "Feedback should be a PingTrack");
        }
Example #13
0
        public void Create_Comment_With_Right_Data()
        {
            // Arrange
            var testComment = new CreateUpdateCommentInput
            {
                Id   = 17,
                Name = "This is test name",
                Body = "This is test body for comment"
            };

            // Act
            _commentService.Create(testComment);

            // Assert
            _commentRepositoryMock.Verify(_ => _.Create(It.IsAny <Comment>()), Times.Once);
        }
Example #14
0
        public async void Post([FromBody] CommentCreateViewModel model)
        {
            model.User = await _manager.GetUserAsync(User);

            //model.User = await _manager.FindByEmailAsync("*****@*****.**");
            _commentService.Create(model);
        }
Example #15
0
        public void DeleteShouldDeleteAGivenComment()
        {
            var options = new DbContextOptionsBuilder <ExpensesDbContext>()
                          .UseInMemoryDatabase(databaseName: nameof(DeleteShouldDeleteAGivenComment))
                          .Options;

            using (var context = new ExpensesDbContext(options))
            {
                var commentsService = new CommentService(context);
                var toAdd           = new CommentPostModel()

                {
                    Important = true,
                    Text      = "An important expense",
                };


                var actual               = commentsService.Create(toAdd, null);
                var afterDelete          = commentsService.Delete(actual.Id);
                int numberOfCommentsInDb = context.Comments.CountAsync().Result;
                var resultComment        = context.Comments.Find(actual.Id);


                Assert.IsNotNull(afterDelete);
                Assert.IsNull(resultComment);
                Assert.AreEqual(0, numberOfCommentsInDb);
            }
        }
Example #16
0
        public async Task <IActionResult> Create(CommentCreateModel model)
        {
            var user = await _userManager.GetUserAsync(User);

            await _service.Create(model, user.Id);

            return(NoContent());
        }
Example #17
0
        public ActionResult AddComment(int postID, string commentValue)
        {
            var service = new CommentService();

            service.Create(postID, commentValue, GetLoggedUser().Id);
            Db.Save();
            return(new HttpStatusCodeResult(200));
        }
        public async Task AddComment_WithNoneExistingProduct_ShouldThrowException()
        {
            // Arrange
            var context = ApplicationDbContextInMemoryFactory.InitializeContext();

            var groupRepository        = new EfDeletableEntityRepository <Product_Group>(context);
            var productRepository      = new EfDeletableEntityRepository <Product>(context);
            var fireplaceRepository    = new EfDeletableEntityRepository <Fireplace_chamber>(context);
            var suggestItemsReposotory = new EfDeletableEntityRepository <SuggestProduct>(context);
            var commentsRepository     = new EfDeletableEntityRepository <Comment>(context);

            var groupService                 = new GroupService(groupRepository);
            var prodcutService               = new ProductService(productRepository, groupService);
            var cloudinaryService            = new FakeCloudinary();
            var sugestItemsRepositoryService = new SuggestProdcut(suggestItemsReposotory);
            var emailSender      = new FakeEmailSender();
            var fireplaceService = new FireplaceService(fireplaceRepository, groupService, prodcutService, cloudinaryService, sugestItemsRepositoryService);
            var commentServices  = new CommentService(commentsRepository, prodcutService, fireplaceService, emailSender);

            var user = new ApplicationUser
            {
                Id             = "abc",
                FirstName      = "Nikolay",
                LastName       = "Doychev",
                Email          = "*****@*****.**",
                EmailConfirmed = true,
            };

            var       fileName = "Img";
            IFormFile file     = new FormFile(
                new MemoryStream(Encoding.UTF8.GetBytes("This is a dummy file")),
                0,
                0,
                fileName,
                "dummy.png");

            var comment = new CreateCommentInputModel()
            {
                FullName    = "Павлина Якимова",
                Email       = "*****@*****.**",
                Content     = "Тестов коментар",
                ProductId   = "abc1",
                ProductName = "Тестово име",
            };

            var seeder = new DbContextTestsSeeder();
            await seeder.SeedUsersAsync(context);

            await seeder.SeedGroupAsync(context);

            await seeder.SeedProdcutAsync(context);

            await seeder.SeedFireplacesAsync(context);

            // Act
            AutoMapperConfig.RegisterMappings(typeof(CreateCommentInputModel).Assembly);
            await Assert.ThrowsAsync <ArgumentNullException>(() => commentServices.Create(comment));
        }
Example #19
0
 public IActionResult Create(Comment comment)
 {
     if (ModelState.IsValid)
     {
         _commentService.Create(comment);
         return(RedirectToAction(nameof(Index)));
     }
     return(View(comment));
 }
Example #20
0
 public IActionResult Post([FromBody] CommentSendViewModel comment)
 {
     if (ModelState.IsValid)
     {
         _commentService.Create(comment);
         return(Ok(comment));
     }
     return(BadRequest(ModelState));
 }
Example #21
0
        public ActionResult <Comment> Create(Comment comment)
        {
            string Id       = GetUserId();
            string nickname = _userService.GetUserNameById(Id);

            _commentService.Create(comment, nickname);

            return(CreatedAtRoute("GetComment", new { id = comment.Id.ToString() }, comment));
        }
Example #22
0
        public void Create_WhenCommentIsEmpty_ThenThrowValidException()
        {
            // Arrange
            var comment = new CommentDto();

            var service = new CommentService(_unitOfWorkFake, _mapper, _validator);

            // Act - Assert
            Assert.Throws <ValidationException>(() => service.Create(comment));
        }
Example #23
0
        public ActionResult CreateComment(CommentInfo comment, int user, int post)
        {
            TempData["user"] = user;
            TempData["post"] = post;

            comment.AuthorId = studentService.GetById(user).Id;     // maybe 'user' from parameters better?
            comment.PostId   = postService.GetById(post).Id;        // maybe 'post' from parameters better?
            commentService.Create(comment);
            return(RedirectToAction("GetPost", "Post", new { user = TempData["user"], post = TempData["post"] }));
        }
Example #24
0
        public IActionResult CommentOnAnswer([FromBody] Comment comment)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }

            _cs.Create(comment, HttpContext.User.Identity.Name);
            return(Ok(comment));
        }
Example #25
0
        public ActionResult <Comment> Create(Comment comment)
        {
            if (comment.id != null)
            {
                return(BadRequest());
            }
            _commentService.Create(comment);

            return(CreatedAtRoute("GetComment", new { id = comment.id.ToString() }, comment));
        }
Example #26
0
        public void Create_WhenCreateComment_ThenInvokeCreateByRepository()
        {
            // Arrange
            var service = new CommentService(_unitOfWorkFake, _mapper, _alwaysValidValidator);

            // Act
            service.Create(new CommentDto());

            // Assert
            A.CallTo(() => _unitOfWorkFake.CommentRepository.Create(A <Comment> ._)).MustHaveHappened();
        }
Example #27
0
        public void CreateComment(string CommentText, int NewsId, int UsernameId)
        {
            Comment comment = new Comment()
            {
                Comment_Text = CommentText,
                NewsId       = NewsId,
                UsernameId   = UsernameId
            };

            commentService.Create(comment);
        }
Example #28
0
        public void Create_WithNotExistingPublicationIdAndNotExistingUserId_ShouldReturnFalse()
        {
            // Arrange
            StarStuffDbContext db             = this.Database;
            CommentService     commentService = new CommentService(db);

            // Act
            bool result = commentService.Create(1, 1, "Test Content");

            // Assert
            Assert.False(result);
        }
        public ActionResult <Comment> Create(Comment comment, string postId)
        {
            var post = _postService.GetForPostId(postId);

            post.Comments.Add(comment.CommentId);

            _postService.Update(post.Id, post);

            _commentService.Create(comment);

            return(comment);
        }
 public ActionResult <Comment> Create([FromBody] Comment newData)
 {
     try
     {
         newData.Author = HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value;
         return(Ok(_service.Create(newData)));
     }
     catch (Exception e)
     {
         return(BadRequest(e.Message));
     }
 }