Beispiel #1
0
        // GET: CommentForms/Details/5
        public ActionResult Details(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            CommentForm commentForm = db.CommentForms.Find(id);

            if (commentForm == null)
            {
                return(HttpNotFound());
            }

            var viewModel = new CommentFormViewModel
            {
                CommentForm = commentForm,
                //We don't want to pull back all the procedures, just the one with the
                //same priority as our comment
                Procedure = (from p in db.Procedures
                             where p.Priority == commentForm.Priority
                             select p).First()
            };

            return(View(viewModel));
        }
        public async Task <Comment> CreateCommentAsync(CommentForm form, CancellationToken ct)
        {
            if (form == null)
            {
                throw new ArgumentException("Invalid data");
            }

            var newComment = new CommentEntity
            {
                Id         = new Guid(),
                Content    = form.Content,
                TodoTaskId = form.TodoTaskId,
                CreatedAt  = DateTimeOffset.UtcNow
            };

            _dbContext.Comments.Add(newComment);

            var created = await _dbContext.SaveChangesAsync(ct);

            if (created < 1)
            {
                throw new InvalidOperationException("Could not create the entry");
            }

            return(Mapper.Map <Comment>(newComment));
        }
        public ActionResult CreateComment(CommentForm commentInput)
        {
            string comment      = commentInput.comment;
            string postIdString = commentInput.postId;
            int    postId       = int.Parse(postIdString);

            string connectionString = ConfigurationManager.ConnectionStrings["BlogDB"].ToString();

            SqlConnection connection = new SqlConnection(connectionString);

            connection.Open();


            string query  = string.Format("SELECT Id FROM dbo.[User] WHERE UserName = '******'", User.Identity.Name);
            int    userId = connection.Query <int>(query, null).FirstOrDefault();

            DateTime TimeStamp = DateTime.Now;

            query = "INSERT INTO dbo.Comment (Body, PostId, UserId, TimeStamp) VALUES (@comment, @postId, @userId, @TimeStamp)";
            connection.Execute(query, new { comment, postId, userId, TimeStamp });


            connection.Close();

            return(RedirectToRoute("Post", new { postId = postId }));
        }
Beispiel #4
0
        public async Task <IActionResult> AddReply(CommentForm model)
        {
            if (ModelState.IsValid)
            {
                var user = await _workContext.GetCurrentUser();

                var reply = new Comment()
                {
                    ParentId      = model.ParentId,
                    UserId        = user.Id,
                    CommentText   = model.CommentText,
                    CommenterName = model.CommenterName,
                    Status        = _isCommentsRequireApproval ? CommentStatus.Pending : CommentStatus.Approved,
                    EntityId      = model.EntityId,
                    EntityTypeId  = model.EntityTypeId,
                };

                _commentRepository.Add(reply);
                _commentRepository.SaveChanges();

                return(PartialView("_CommentFormSuccess", model));
            }

            return(PartialView("_CommentForm", model));
        }
Beispiel #5
0
        public int SummarizeComment(CommentForm form)
        {
            var tComment   = View <UserComment>();
            var tSummarize = Table <Summarize>();

            var summarize = tSummarize.GetOrAdd(w => w.SourceID == form.SourceID && w.SourceTable == form.SourceTable);

            MapProperty(form, summarize);
            UpdateAuditFields(summarize, form.ByUserID);
            summarize.CommentCount = summarize.CommentCount + 1;

            // save
            SaveChanges();

            // walk up the chain and increase comment count
            if (form.SourceTable == R.SourceTable.COMMENT)
            {
                var commentForm = tComment.Where(w => w.ID == form.SourceID).Select(s => new CommentForm
                {
                    SourceID    = s.SourceID,
                    SourceTable = s.SourceTable
                }).SingleOrDefault();

                SummarizeComment(commentForm);
            }

            return(summarize.CommentCount);
        }
Beispiel #6
0
        public ActionResult DeleteConfirmed(int id)
        {
            CommentForm commentForm = db.CommentForms.Find(id);

            db.CommentForms.Remove(commentForm);
            db.SaveChanges();
            return(RedirectToAction("Index"));
        }
Beispiel #7
0
        public void CreatesEmptyCommentFromInvalidForm()
        {
            var formMock    = new Mock <IFormCollection>();
            var commentForm = new CommentForm(formMock.Object);
            var result      = commentForm.TryCreateComment();

            Assert.NotEmpty(result.Errors);
        }
Beispiel #8
0
        public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
        {
            var form = new CommentForm {
                Comments = value as string[]
            };

            return(form.ShowDialog() == DialogResult.OK ? form.Comments : value);
        }
        public async Task <Comment> CreateCommentAsync(CommentForm commentForm)
        {
            // Init comment
            var comment = new Comment();

            // Perform checks based on comment type
            if (commentForm.ParentType == ParentType.ModerationItem)
            {
                if (!_ctx.ModerationItems.Any(x => x.Id == commentForm.ParentId))
                {
                    throw new ParentNotFoundException("Moderation Item not found");
                }

                comment.ModerationItemId = commentForm.ParentId;
            }
            else if (commentForm.ParentType == ParentType.Submission)
            {
                if (!_ctx.Submissions.Any(x => x.Id == commentForm.ParentId))
                {
                    throw new ParentNotFoundException("Submission not found");
                }

                comment.SubmissionId = commentForm.ParentId;
            }
            else if (commentForm.ParentType == ParentType.Comment)
            {
                if (!_ctx.Comments.Any(x => x.Id == commentForm.ParentId))
                {
                    throw new ParentNotFoundException("Comment not found");
                }

                comment.ParentId = commentForm.ParentId;
            }

            comment.Content = commentForm.Content;
            comment.UserId  = _userId;

            // Assign original commentForm content that's being processed via LINQ, to Html comment content
            comment.HtmlContent = _tagMatch
                                  .Matches(commentForm.Content)
                                  .Aggregate(commentForm.Content, (content, match) =>
            {
                // Extract from regex <tag> group and grab the value => string
                var tag = match.Groups["tag"].Value;

                return(content.Replace(tag, $"<a href=\"{tag}-user-link\">{tag}</a>"));
            });

            _ctx.Add(comment);
            await _ctx.SaveChangesAsync();

            // Assign User to Comment
            comment.User = _ctx.Users.AsNoTracking().FirstOrDefault(u => u.Id == _userId);

            return(comment);
        }
Beispiel #10
0
        // GET: CommentForm
        public ActionResult Index()
        {
            CommentForm formObj = new CommentForm
            {
                UserName    = "",
                UserComment = ""
            };

            return(View(formObj));
        }
Beispiel #11
0
 public ActionResult Edit([Bind(Include = "CommentID,Name,Comment,Priority,ProcedureID")] CommentForm commentForm)
 {
     if (ModelState.IsValid)
     {
         db.Entry(commentForm).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     ViewBag.ProcedureID = new SelectList(db.Procedures, "ProcedureID", "Details", commentForm.ProcedureID);
     return(View(commentForm));
 }
Beispiel #12
0
        public int SaveChanges(CommentForm form)
        {
            var tComment = Table <UserComment>();

            var comment = tComment.GetOrAdd(w => w.ID == form.ID);

            MapProperty(form, comment, form.InlineEditProperty);
            UpdateAuditFields(comment, form.ByUserID);
            // save
            SaveChanges();

            return(comment.ID);
        }
Beispiel #13
0
        public void CreatesCommentFromValidForm()
        {
            var formMock = new Mock <IFormCollection>();

            formMock.Setup(x => x["postId"]).Returns("this-is-a-post-slug");
            formMock.Setup(x => x["message"]).Returns("This is the message");
            formMock.Setup(x => x["name"]).Returns("My Name");

            var commentForm = new CommentForm(formMock.Object);
            var result      = commentForm.TryCreateComment();

            Assert.Empty(result.Errors);
        }
Beispiel #14
0
        public async Task <IActionResult> Comment(int?id, CommentFormVM Comment)
        {
            if (string.IsNullOrEmpty(Comment.Name))
            {
                ModelState.AddModelError("", "The Form was't sent correctly");
                return(RedirectToAction("BlogDetails"));
            }
            if (string.IsNullOrEmpty(Comment.Email))
            {
                ModelState.AddModelError("", "The Form was't sent correctly");
                return(RedirectToAction("BlogDetails"));
            }
            if (string.IsNullOrEmpty(Comment.Massage))
            {
                ModelState.AddModelError("", "The Form was't sent correctly");
                return(RedirectToAction("BlogDetails"));
            }
            if (string.IsNullOrEmpty(Comment.Subject))
            {
                ModelState.AddModelError("", "The Form was't sent correctly");
                return(RedirectToAction("BlogDetails"));
            }
            if (id == null)
            {
                return(NotFound());
            }

            Blog blog = await _db.Blogs.FindAsync(id);

            if (blog == null)
            {
                return(NotFound());
            }

            blog.CommentCount++;

            CommentForm commentForm = new CommentForm
            {
                BlogId  = (int)id,
                Email   = Comment.Email,
                Massage = Comment.Massage,
                Name    = Comment.Name,
                Subject = Comment.Subject
            };

            await _db.CommentForms.AddAsync(commentForm);

            await _db.SaveChangesAsync();

            return(RedirectToAction(nameof(Index)));
        }
Beispiel #15
0
        public void EmailIsValidated()
        {
            var invalidEmail = "InvalidEmail";
            var formMock     = new Mock <IFormCollection>();

            formMock.Setup(x => x["postId"]).Returns("this-is-a-post-slug");
            formMock.Setup(x => x["message"]).Returns("This is the message");
            formMock.Setup(x => x["name"]).Returns("My Name");
            formMock.Setup(x => x["email"]).Returns(invalidEmail);

            var commentForm = new CommentForm(formMock.Object);

            Assert.Single(commentForm.Errors);
        }
Beispiel #16
0
        // GET: CommentForms/Delete/5
        public ActionResult Delete(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            CommentForm commentForm = db.CommentForms.Find(id);

            if (commentForm == null)
            {
                return(HttpNotFound());
            }
            return(View(commentForm));
        }
 protected override void Seed(ApplicationDbContext context)
 {
     if (!context.Comments.Any())
     {
         for (int i = 0; i < 18; i++)
         {
             var currentComment = new CommentForm
             {
                 Title       = $"Comment{i}",
                 Description = $"Automaticly Generated Description Lorem ipsum dolor color {i}",
             };
             context.Comments.Add(currentComment);
         }
         context.SaveChanges();
     }
     if (!context.Tables.Any())
     {
         for (int i = 1; i <= 10; i++)
         {
             var currentTable = new Table
             {
                 Id             = i,
                 NumberOfChairs = 2,
                 IsTaken        = false
             };
             context.Tables.Add(currentTable);
         }
         for (int i = 10; i <= 20; i++)
         {
             var currentTable = new Table
             {
                 Id             = i,
                 NumberOfChairs = 4,
                 IsTaken        = false
             };
             context.Tables.Add(currentTable);
         }
         for (int i = 20; i <= 30; i++)
         {
             var currentTable = new Table
             {
                 Id             = i,
                 NumberOfChairs = 6,
                 IsTaken        = false
             };
             context.Tables.Add(currentTable);
         }
         context.SaveChanges();
     }
 }
Beispiel #18
0
        public async Task <IActionResult> CreateCommentAsync([FromBody] CommentForm form, CancellationToken ct)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(new ApiError(ModelState)));
            }

            var comment = await _repository.CreateCommentAsync(form, ct);

            return(Created(
                       Url.Link(nameof(GetCommentAsync), new { commentId = comment.Id }),
                       comment
                       ));
        }
Beispiel #19
0
        // GET: CommentForms/Edit/5
        public ActionResult Edit(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            CommentForm commentForm = db.CommentForms.Find(id);

            if (commentForm == null)
            {
                return(HttpNotFound());
            }
            ViewBag.ProcedureID = new SelectList(db.Procedures, "ProcedureID", "Details", commentForm.ProcedureID);
            return(View(commentForm));
        }
Beispiel #20
0
        public void InvalidFormShouldHaveErrors(
            MemberDataSerializer <IEnumerable <KeyValuePair <string, string> > > testCase)
        {
            var formMock = new Mock <IFormCollection>();

            foreach (var fieldValuePair in testCase.TestCase)
            {
                formMock.Setup(x => x[fieldValuePair.Key]).Returns(fieldValuePair.Value);
            }

            var commentForm = new CommentForm(formMock.Object);

            Assert.True(
                commentForm.HasErrors,
                $"Comment form should have errors. Errors: {FormatErrors(commentForm.Errors)}");
        }
Beispiel #21
0
        public void AddCommentToEvent_UserAddsCommentToOwnEventWithFormWithEmptyContentAndEventExists_CommentNotAdded()
        {
            var userId  = Guid.NewGuid();
            var tracker = EntityMaker.CreateSomeTracker(userId, _mockTrackerRepository);

            tracker.Customizations.Add(CustomizationType.Comment);
            _mockTrackerRepository.Update(tracker);
            var @event = EntityMaker.CreateSomeEvent(tracker.Id, _mockEventRepository);
            var form   = new CommentForm("");

            _customizationService.AddCommentToEvent(userId, @event.Id, form);

            var comments = _mockCommentRepository.GetAll();

            Assert.AreEqual(0, comments.Count);
        }
Beispiel #22
0
        public void FailingTypeConversionOnOptionalFieldReturnsError()
        {
            // UriTypeConverter will fail, if the uri string is longer than 65519 characters

            var formMock = new Mock <IFormCollection>();

            formMock.Setup(x => x["postId"]).Returns("this-is-a-post-slug");
            formMock.Setup(x => x["message"]).Returns("This is the message");
            formMock.Setup(x => x["name"]).Returns("My Name");
            formMock.Setup(x => x["url"]).Returns(new string('A', 65520));

            var commentForm = new CommentForm(formMock.Object);

            Assert.NotEmpty(commentForm.Errors);
            Assert.Single(commentForm.Errors);
        }
        public async Task <Comment> CreateAsync(CommentForm commentForm)
        {
            var comment = new Comment();

            if (commentForm.ParentType == ParentType.ModerationItem)
            {
                if (!_ctx.ModerationItems.Any(x => x.Id == commentForm.ParentId))
                {
                    throw new ParentNotFoundException("Moderation Item not found");
                }
                comment.ModerationItemId = commentForm.ParentId;
            }
            else if (commentForm.ParentType == ParentType.Submission)
            {
                if (!_ctx.Submissions.Any(x => x.Id == commentForm.ParentId))
                {
                    throw new ParentNotFoundException("Submission not found");
                }
                comment.SubmissionId = commentForm.ParentId;
            }
            else if (commentForm.ParentType == ParentType.Comment)
            {
                if (!_ctx.Comments.Any(x => x.Id == commentForm.ParentId))
                {
                    throw new ParentNotFoundException("Comment not found");
                }
                comment.ParentId = commentForm.ParentId;
            }

            comment.Content     = commentForm.Content;
            comment.UserId      = _userId;
            comment.HtmlContent = _tagMatch.Matches(commentForm.Content)
                                  .Aggregate(commentForm.Content,
                                             (content, match) =>
            {
                var tag = match.Groups["tag"].Value;
                return(content
                       .Replace(tag, $"<a href=\"{tag}-user-link\">{tag}</a>"));
            });

            _ctx.Add(comment);
            await _ctx.SaveChangesAsync();

            comment.User = _ctx.Users.AsNoTracking().FirstOrDefault(x => x.Id == _userId);

            return(comment);
        }
        public async Task <IActionResult> Create(
            [FromBody] CommentForm commentForm,
            [FromServices] CommentCreationContext commentCreationContext)
        {
            try
            {
                var comment = await commentCreationContext
                              .Setup(UserId)
                              .CreateAsync(commentForm);

                return(Ok(CommentViewModel.Create(comment)));
            }
            catch (CommentCreationContext.ParentNotFoundException e)
            {
                return(BadRequest(e.Message));
            }
        }
Beispiel #25
0
        public int AddComment(CommentForm commentForm)
        {
            using (var uow = UnitOfWorkFactory.Create <NovelContext>())
            {
                var service = new CommentService(uow);
                var id      = service.SaveChanges(commentForm);

                // new comment, increase comment count
                if (commentForm.ID == 0)
                {
                    var userActionService = new UserActionService(uow);
                    userActionService.SummarizeComment(commentForm);
                }

                return(id);
            }
        }
Beispiel #26
0
        public IActionResult SaveComment([FromBody] CommentForm commentForm)
        {
            var user = _userRepository.Users.FirstOrDefault(u => u.UserName == User.Identity.Name);

            if (user == null)
            {
                return(NotFound("User not found"));
            }

            var post = _postRepository.Posts.FirstOrDefault(p => p.Id == commentForm.PostId);

            if (post == null)
            {
                return(NotFound("Post not found"));
            }

            Comment parentComment = null;

            if (commentForm.CommentId != null)
            {
                parentComment = _commentRepository.Comments.FirstOrDefault(c => c.Id == commentForm.CommentId);
                if (parentComment == null)
                {
                    return(NotFound("Parent comment not found"));
                }
            }

            var comment = new Comment()
            {
                Post          = post,
                User          = user,
                Content       = commentForm.Content,
                ParentComment = parentComment
            };

            _commentRepository.SaveComment(comment);

            return(Ok(new ItemViewData <Comment>
            {
                Item = comment,
                Comments = 0,
                Likes = 0,
                IsLiked = false
            }));
        }
        public IActionResult Comment([FromBody] CommentForm commentForm)
        {
            var userId = User.CurrentUserId();

            if (commentForm.postId < 0)
            {
                return(BadRequest("PostId invalid, cannot find PostID"));
            }

            var p = db.Post.Where(r => r.Id == commentForm.postId).FirstOrDefault();

            if (p == null)
            {
                return(BadRequest("PostId invalid, cannot find PostID"));
            }

            Comment comment = new Comment();

            comment.PostId = commentForm.postId;
            comment.UserId = userId;
            var commentContent = commentForm.commentContent;

            if (String.IsNullOrEmpty(commentContent))
            {
                comment.Content = "";
            }

            if (commentContent.Length < 100)
            {
                comment.Content = commentForm.commentContent;
            }

            if (commentContent.Length >= 100)
            {
                return(BadRequest("Your comment is too long. Comment's content is limited within 100 characters."));
            }

            comment.CreateDate = DateTime.Now;
            db.Comment.Add(comment);
            db.SaveChanges();
            return(Ok("Leave comment successfully"));
        }
Beispiel #28
0
        public async Task <IActionResult> Post([FromBody] CommentForm model)
        {
            if (ModelState.IsValid)
            {
                var user = await _workContext.GetCurrentUser();

                var comment = new Comment
                {
                    ParentId      = model.ParentId,
                    CommentText   = model.CommentText,
                    CommenterName = user.FullName,
                    Status        = CommentStatus.Approved,
                    EntityId      = model.EntityId,
                    EntityTypeId  = model.EntityTypeId,
                    UserId        = user.Id
                };

                if (!User.IsInRole("admin"))
                {
                    var isCommentsRequireApproval = _config.GetValue <bool>("Catalog.IsCommentsRequireApproval");
                    comment.Status = isCommentsRequireApproval ? CommentStatus.Pending : CommentStatus.Approved;
                }

                _commentRepository.Add(comment);
                await _commentRepository.SaveChangesAsync();

                var commentItem = new CommentItem
                {
                    Id            = comment.Id,
                    CommentText   = comment.CommentText,
                    CommenterName = comment.CommenterName,
                    CreatedOn     = comment.CreatedOn,
                    Status        = comment.Status.ToString()
                };

                return(Ok(commentItem));
            }

            return(BadRequest(ModelState));
        }
Beispiel #29
0
        public ActionResult Create(CommentFormViewModel comment)
        {
            if (this.User.Identity.IsAuthenticated)
            {
                var newComment = new CommentForm
                {
                    Title       = comment.Title,
                    Description = comment.Description,
                    AuthorId    = this.User.Identity.GetUserId()
                };
                this.feedbacks.Add(newComment);
                this.feedbacks.SaveChanges();
                this.TempData["Notification"] = "Thank you for your Feedback";
            }
            else
            {
                this.TempData["Notification"] = "You must be logged in to live a comment";
            }


            return(this.Redirect("Create"));
        }
        private void BtnViewComments_Click(object sender, EventArgs e)
        {
            CommentForm comments = new CommentForm(Ticket);

            comments.ShowDialog();
        }