Exemplo n.º 1
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);
            }
        }
Exemplo n.º 2
0
        public HttpResponseMessage PostComment([FromBody] CommentPostModel comment,
                                               [ValueProvider(typeof(HeaderValueProviderFactory <string>))] string sessionKey)
        {
            var responseMsg = this.PerformOperationAndHandleExceptions(() =>
            {
                var context = new BookstoreContext();

                var user = context.Users.FirstOrDefault(usr => usr.SessionKey == sessionKey);
                if (user == null)
                {
                    throw new InvalidOperationException("Invalid username or password");
                }

                var book = context.Books.SingleOrDefault(b => b.Id == comment.BookId);
                if (book == null)
                {
                    throw new ServerErrorException("Book to comment does not exist.");
                }

                var commentToAdd  = new Comment();
                commentToAdd.Text = comment.Text;
                commentToAdd.User = user;
                commentToAdd.Book = book;
                context.Comments.Add(commentToAdd);
                context.SaveChanges();
                return(Request.CreateResponse(HttpStatusCode.Created));
            });

            return(responseMsg);
        }
Exemplo n.º 3
0
        public async Task <IActionResult> Post(CommentPostModel model)
        {
            try
            {
                var user = await _userManager.FindByEmailAsync(model.Email);

                var comment = new Comment()
                {
                    User    = user,
                    Content = model.Content,
                    Date    = DateTime.Now.ToLocalTime(),
                    Article = await _mediator.Send(new GetArticleById(model.ArticleId))
                };

                await _mediator.Send(new AddComment(comment));

                Log.Information($"Comment added successfully");

                return(StatusCode(201, "Comment added successfully"));
            }
            catch (Exception ex)
            {
                Log.Error($"Error adding comment:{Environment.NewLine}{ex.Message}");
                return(BadRequest());
            }
        }
Exemplo n.º 4
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);
            }
        }
Exemplo n.º 5
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);
            }
        }
Exemplo n.º 6
0
 public async Task <ActionResult> Add(CommentPostModel model)
 {
     if (ModelState.IsValid)
     {
         await _dbContext.AddCommentAsync(model);
     }
     return(RedirectToAction("Detsils", "Post", routeValues: new { id = model.PostId }));
 }
Exemplo n.º 7
0
        public Comment Create(CommentPostModel comment, int id)
        {
            Comment toAdd   = CommentPostModel.ToComment(comment);
            Expense expense = context.Expenses.FirstOrDefault(e => e.Id == id);

            expense.Comments.Add(toAdd);
            context.SaveChanges();
            return(toAdd);
        }
Exemplo n.º 8
0
        public Comment Create(CommentPostModel comment, User addedBy)
        {
            Comment commentAdd = CommentPostModel.ToComment(comment);

            commentAdd.Owner = addedBy;
            context.Comments.Add(commentAdd);
            context.SaveChanges();
            return(commentAdd);
        }
Exemplo n.º 9
0
        public Comment Create(CommentPostModel comment, int id)
        {
            Comment toAdd = CommentPostModel.ToComment(comment);
            Task    task  = context.Tasks.FirstOrDefault(tas => tas.Id == id);

            task.Comments.Add(toAdd);
            context.SaveChanges();
            return(toAdd);
        }
Exemplo n.º 10
0
 public CommentPostViewModel(CommentPostModel commentPostModel, UsuarioModel usuarioModel,
                             int tempo, string formato)
 {
     Comment           = commentPostModel.Comment;
     IdentityUser      = commentPostModel.IdentityUser;
     Nome              = usuarioModel.Nome + " " + usuarioModel.Sobrenome;
     TempoDoComentario = tempo;
     FormatacaoTempo   = formato;
     FotoPerfil        = usuarioModel.FotoPerfil;
     Id = commentPostModel.Id;
 }
Exemplo n.º 11
0
        public async Task CreateAsync(CommentPostModel postModel)
        {
            var path = $"{_projetoHttpOptions.CurrentValue.CommentPostPath}";

            var httpContent = new StringContent(JsonConvert.SerializeObject(postModel), Encoding.UTF8, "application/json");

            var httpResponseMessage = await _httpClient.PostAsync(path, httpContent);

            if (!httpResponseMessage.IsSuccessStatusCode)
            {
            }
        }
Exemplo n.º 12
0
        public ActionResult Create(CommentPostModel comment)
        {
            var idea = this.ideas.GetById(comment.Id);
            idea.Comments.Add(new Comment()
            {
                AuthorEmail = new HtmlSanitizer().Sanitize(comment.Email),
                Content = new HtmlSanitizer().Sanitize(comment.NewContent),
                AuthorIpAddress = this.GetRandomIpAddress()
            });

            this.ideas.SaveChanges();

            return this.RedirectToAction("Index", "Home");
        }
Exemplo n.º 13
0
        public IActionResult PostComment(Guid id, [FromBody] CommentPostModel model)
        {
            var query   = new GetProjectQuery(id);
            var project = _bus.PublishQuery(query);

            // validation
            if (project == null)
            {
                return(NotFound());
            }

            var command = new PostCommentOnProjectCommand(id, new Guid(User.GetClaim("id")), model.Content, DateTime.Now);

            _bus.PublishCommand(command);
            return(Ok());
        }
Exemplo n.º 14
0
        public ActionResult CommentPoster(int?id)
        {
            //var blog2 = context.Blogs
            //            .Where(b => b.Name == "ADO.NET Blog")
            //            .Include("Posts")
            //            .FirstOrDefault();
            CommentPostModel pageModel = new CommentPostModel();

            var dummyItems = db.BlogTable.FirstOrDefault(x => x.ID == id);



            pageModel.Items           = dummyItems;
            pageModel.Items2          = new CommentPost();
            pageModel.UserIdContainer = "";
            return(View(pageModel));
        }
Exemplo n.º 15
0
        public ActionResult PostComment(CommentPostModel comment)
        {
            var currentArticleId = comment.ArticleId;

            if (this.ModelState.IsValid)
            {
                var newComment = this.Mapper.Map<Comment>(comment);
                newComment.Content = this.sanitizer.Sanitize(newComment.Content);
                newComment.AuthorId = this.User.Identity.GetUserId();
                newComment.ArticleId = currentArticleId;
                this.comments.Create(newComment);
            }

            var articleComments =
                this.comments.GetAll().Where(c => c.ArticleId == currentArticleId).To<CommentViewModel>().ToList();

            return this.PartialView("_CommentsGrid", currentArticleId);
        }
Exemplo n.º 16
0
        public IActionResult Post([Required][FromBody] CommentPostModel newComment)
        {
            if (newComment == null)
            {
                return(BadRequest());
            }

            CommentDTO comment = new CommentDTO
            {
                OwnerId            = newComment.OwnerId,
                CommentedEssenceId = newComment.EssenceId,
                Text = newComment.Text,
                Time = DateTime.Now
            };

            _dataWriter.Add(comment);

            return(Ok());
        }
Exemplo n.º 17
0
        public ActionResult CommentPoster(CommentPostModel NewComment)
        {
            int usermodelidintcontainer = int.Parse(NewComment.UserIdContainer);


            var sentCommentpost = new CommentPost
            {
                BlogPostId  = NewComment.Items.ID,
                Comment     = NewComment.Items2.Comment,
                UserModelId = usermodelidintcontainer
            };



            db.CommentTable.Add(sentCommentpost);
            db.SaveChanges();


            return(View());
        }
Exemplo n.º 18
0
        public async Task <ActionResult <CommentPostModel> > PostCommentPostModel([Bind("Id, IdentityUser,PostModelId,Comment")] CommentPostModel commentPostModel)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            try
            {
                _unitOfWork.BeginTransaction();
                await _commentPostServices.CreateAsync(commentPostModel);

                await _unitOfWork.CommitAsync();
            }
            catch (ModelValidationExceptions e)
            {
                ModelState.AddModelError(e.PropertyName, e.Message);
                return(BadRequest(ModelState));
            }

            return(base.Ok());
        }
Exemplo n.º 19
0
        public async Task <IActionResult> CreateComment(string comment, int idPost)
        {
            try
            {
                var userId = await GetUserIdentityAsync();

                var commentPostModel = new CommentPostModel
                {
                    Comment       = comment,
                    PostModelId   = idPost,
                    IdentityUser  = userId,
                    DataDoComment = DateTime.Now
                };

                await _commentPostServices.CreateAsync(commentPostModel);

                return(RedirectToAction("Index", "Home"));
            }
            catch
            {
                return(RedirectToAction("Index", "Home"));
            }
        }
Exemplo n.º 20
0
        public ActionResult PostComment(CommentPostModel commentPost)
        {
            JsonViewResult json = new JsonViewResult()
            {
                Success = false
            };

            if (!ModelState.IsValid)
            {
                json.Success = false;
                json.Message = "输入错误";
                return(Json(json, JsonRequestBehavior.AllowGet));
            }

            string verifyCode = Session["ValidateCode"] as string;

            if (verifyCode.ToLower() != commentPost.VerifyCode)
            {
                json.Success = false;
                json.Message = "验证码输入错误";
                return(Json(json, JsonRequestBehavior.AllowGet));
            }

            var jokeinfo = jokeBusinessLogic.JokeDetailGet(commentPost.JokeID);

            T_Comment commentDomain = new T_Comment();

            commentDomain.AddDate = DateTime.Now;
            commentDomain.Content = commentPost.Comment;
            commentDomain.Floor   = jokeinfo.CommentCount + 1;
            commentDomain.JokeId  = commentPost.JokeID;
            commentDomain.UserID  = user.UserId;
            jokeinfo.CommentCount = jokeinfo.CommentCount + 1;
            jokeBusinessLogic.UpdateJoke(jokeinfo);
            json.Success = jokeBusinessLogic.AddComment(commentDomain);
            return(Json(json, JsonRequestBehavior.AllowGet));
        }
Exemplo n.º 21
0
        public IActionResult PostComment([FromBody] CommentPostModel comment)
        {
            var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);

            if (comment != null)
            {
                if (comment.Content.Length > 5 && comment.ProductId > 0)
                {
                    Comment comment1 = new Comment()
                    {
                        ProductId = comment.ProductId,
                        Content   = comment.Content,
                        UserId    = userId,
                    };

                    _commentRepository.PostComment(comment1);


                    return(Json(new { success = "true", date = DateTime.Now.ToString() }));
                }
            }

            return(Json(new { success = "false" }));
        }
Exemplo n.º 22
0
        public void CreateShouldAddAndReturnTheCreatedComment()
        {
            var options = new DbContextOptionsBuilder <ExpensesDbContext>()
                          .UseInMemoryDatabase(databaseName: nameof(CreateShouldAddAndReturnTheCreatedComment))
                          .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);


                Assert.IsNotNull(added);
                Assert.AreEqual("An important expense", added.Text);
                Assert.True(added.Important);
            }
        }
Exemplo n.º 23
0
        public IActionResult Put([Required] string id, [Required][FromBody] CommentPostModel commentToEdit)
        {
            if (commentToEdit == null)
            {
                return(BadRequest());
            }
            if (string.IsNullOrEmpty(commentToEdit.Text))
            {
                _dataWriter.Remove(id);
                return(Ok());
            }

            CommentDTO updatedComment = new CommentDTO
            {
                Id                 = id,
                OwnerId            = commentToEdit.OwnerId,
                CommentedEssenceId = commentToEdit.EssenceId,
                Text               = commentToEdit.Text,
                Time               = DateTime.Now
            };

            _dataWriter.Update(updatedComment);
            return(Ok());
        }
Exemplo n.º 24
0
 public void Post([FromQuery] int id, [FromBody] CommentPostModel comment)
 {
     commentService.Create(comment, id);
 }
Exemplo n.º 25
0
 public ActionResult Form(CommentPostModel model)
 {
     return(View(model));
 }
Exemplo n.º 26
0
 public async Task UpdateAsync(CommentPostModel model)
 {
     throw new NotImplementedException();
 }
Exemplo n.º 27
0
        public static async Task <int> AddCommentAsync(this BlogWebDbContext _dbContext, CommentPostModel model)
        {
            Comment comment = new Comment
            {
                Email          = model.Email,
                SubmmittedDate = DateTime.Now,
                Message        = model.Message,
                PostId         = model.PostId,
                Username       = model.Username,
                Website        = model.Website,
                UserId         = 1
            };

            _dbContext.Comments.Add(comment);
            return(await _dbContext.SaveChangesAsync());
        }
Exemplo n.º 28
0
        public void Post([FromBody] CommentPostModel comment)
        {
            User addedBy = usersService.GetCurrentUser(HttpContext);

            commentsService.Create(comment, addedBy);
        }