Пример #1
0
        public CommentViewModel AddComment(string author, string content)
        {
            if (author.IsNullOrWhiteSpace())
            {
                throw new ArgumentException("Missing author name.");
            }

            if (content.IsNullOrWhiteSpace())
            {
                throw new ArgumentException("Missing content.");
            }

            var comment = new Comment
                              {
                                  Author = author,
                                  Content = content,
                                  DateCreated = DateTime.Now,
                                  PostId = this.view.Id
                              };

            this.Data.Comments.Add(comment);
            this.Data.SaveChanges();

            var commentView = new CommentViewModel
                                  {
                                      Id = comment.Id,
                                      Content = comment.Content,
                                      Author = comment.Author,
                                      DateCreated = comment.DateCreated
                                  };

            this.view.Comments.Insert(0, commentView);

            return commentView;
        }
Пример #2
0
        public IHttpActionResult AddCommentToPost(int id, CommentBindingModel commentBindingModel)
        {
            var post = this.Data.Posts.Find(id);

            if (post == null)
            {
                return this.NotFound();
            }

            if (!this.ModelState.IsValid)
            {
                return this.BadRequest(ErrorMessagesCreator.GetErrorsAsString(ModelState));
            }

            var comment = new Comment()
            {
                Post = post,
                Body = commentBindingModel.Body,
                Author = this.Data.UserManager.FindById(User.Identity.GetUserId()),
                PostDate = DateTime.Now
            };

            post.Comments.Add(comment);

            this.Data.SaveChanges();

            return this.Ok("Comment added");
        }
Пример #3
0
        public static PostCommentModel CommentToPostCommentModel(Comment comment)
        {
            var postCommentModel = new PostCommentModel()
                {
                    Text = comment.Text,
                    PostDate = comment.PostDate,
                    CommentedBy = comment.CommentedBy == null ? null : comment.CommentedBy.DisplayName,
                };

            return postCommentModel;
        }
        public IHttpActionResult PostComment(Comment comment)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            repository.Add(comment);
            repository.SaveChanges();

            return CreatedAtRoute("DefaultApi", new { id = comment.Id }, comment);
        }
        public IHttpActionResult PutComment(int id, Comment comment)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            if (id != comment.Id)
            {
                return BadRequest();
            }

            repository.Update(comment);
            repository.SaveChanges();

            return this.Ok(comment);
        }
Пример #6
0
        public HttpResponseMessage CreateComment([ValueProvider(typeof(HeaderValueProviderFactory<string>))]string sessionKey,
            int postId, [FromBody]CreateCommentModel comment)
        {
            var responseMsg = this.PerformOperationAndHandleExceptions(
                () =>
                {
                    var context = new BlogDb();
                    using (context)
                    {

                        UserPersister.ValidateSessionKey(sessionKey);

                        var user = context.Users.FirstOrDefault(
                            usr => usr.SessionKey == sessionKey);

                        if (user == null)
                        {
                            throw new InvalidOperationException("Invalid username or password");
                        }

                        var post = context.Posts.FirstOrDefault(p => p.PostId == postId);
                        if (post == null)
                        {
                             throw new ArgumentNullException("Invalid post id");
                        }

                        Comment commToAdd = new Comment()  
                        { 
                             Content= comment.Text,
                             UserOfComment = user,
                             DateCreated = DateTime.Now
                        };

                        post.Comments.Add(commToAdd);
                        context.SaveChanges();

                        var response =
                           this.Request.CreateResponse(HttpStatusCode.OK);
                        return response;
                    }
                });
            return responseMsg;
        }
        public void TestLeaveValidComment_ShouldReturnCreated()
        {
            //Create test user
            var testUser = new UserModel()
            {
                Username = "******",
                DisplayName = "VALIDNICK",
                AuthCode = new string('b', 40)
            };
            LoggedUserModel userModel = RegisterTestUser(httpServer, testUser);
            var headers = new Dictionary<string, string>();
            headers["X-sessionKey"] = userModel.SessionKey;

            //Create test post
            var testPost = new Post()
            {
                Title = "Test post",
                Tags = new List<Tag>() { new Tag()
                        {
                            Name = "technology"
                        },
                       
                },
                Text = "this is just a test post"
            };
            var createPostResponse = httpServer.Post("api/posts", testPost, headers);
            string createPostResponseBody = createPostResponse.Content.ReadAsStringAsync().Result;
            var postResponse = JsonConvert.DeserializeObject<CreatePostResponseModel>(createPostResponseBody);

            var comment = new Comment()
                {
                    PostDate = DateTime.Now,
                    Text = "Abe kefi me toq post"
                };

            var commentCreateResponse = httpServer.Put("api/posts/" + postResponse.PostId + "/comment", comment,
                                                        headers);
            Assert.AreEqual(HttpStatusCode.Created, commentCreateResponse.StatusCode);
        }
        [HttpPut] //PUT api/posts/{postId}/comment
        public HttpResponseMessage AddCommentToPost(int id, CommentRequestModel commentModel,
                                                    [ValueProvider(typeof (HeaderValueProviderFactory<string>))] string
                                                        sessionKey)
        {
            var addCommentResponse = this.TryToExecuteOperation(() =>
            {
                if (!usersRepository.All().Any(x => x.SessionKey == sessionKey))
                {
                    throw new InvalidOperationException("Not authorized user!");
                }

                if (commentModel == null || string.IsNullOrEmpty(commentModel.Text))
                {
                    throw new InvalidOperationException("The comment or comment text can not be null!");
                }

                var user = this.usersRepository.All().FirstOrDefault(x => x.SessionKey == sessionKey);
                var post = this.postsRepository.Get(id);
                var comment = new Comment()
                    {
                        Text = commentModel.Text,
                        PostDate = DateTime.Now,
                        CommentedBy = user,
                        Post = post
                    };
                this.commentsRepository.Add(comment);

                var response = this.Request.CreateResponse(HttpStatusCode.Created);
                return response;
            });


            return addCommentResponse;
        }
Пример #9
0
        public HttpResponseMessage PutComment([FromUri]string sessionKey, [FromUri]int postId, [FromBody]CommentDto commentDto)
        {
            var responseMsg = this.PerformOperationAndHandleExceptions(
                () =>
                {
                    if (sessionKey.Length != SessionKeyLength)
                    {
                        throw new ArgumentException("Invalid session key.");
                    }

                    var db = new BlogContext();

                    var user = db.Users.Where(u => u.SessionKey == sessionKey).FirstOrDefault();

                    if (user == null)
                    {
                        throw new ApplicationException("Invalin session. Try to login.");
                    }

                    if (commentDto == null)
                    {
                        throw new ArgumentException("Comment is empty.");
                    }

                    if (commentDto.Text == null)
                    {
                        throw new ArgumentException("Comment text is empty.");
                    }

                    var postById = db.Posts.Where(p => p.Id == postId).FirstOrDefault();

                    if (postById == null)
                    {
                        throw new ApplicationException("Invalin post ID.");
                    }

                    Comment comment = new Comment() { Content = commentDto.Text, CommentDate = DateTime.Now, User = user };

                    postById.Comments.Add(comment);
                    db.SaveChanges();

                    var response = new HttpResponseMessage(HttpStatusCode.OK);
                    return response;
                });

            return responseMsg;
        }
Пример #10
0
        public HttpResponseMessage AddComent(CreateCommentModel model, int postId,
             [ValueProvider(typeof(HeaderValueProviderFactory<string>))] string sessionKey)
        {
            var responseMsg = ExceptionHandler(
            () =>
            {
                User user;
                var context = new BlogSystemContext();
                using (context)
                {
                    user = context.Users.FirstOrDefault(u => u.SessionKey == sessionKey);
                    if (user == null)
                    {
                        throw new InvalidOperationException("Invalid username or password");
                    }
                }

                var selectedPost = this.postRepository.Get(postId);

                var newComment = new Comment
                {
                    Content = model.Text,
                    CommentDate = DateTime.Now,
                    Post = selectedPost,
                    //User = user,
                };

                selectedPost.Comments.Add(newComment);
                this.postRepository.Update(selectedPost, postId, true);

                var response = this.Request.CreateResponse(HttpStatusCode.OK);

                return response;
            });

            return responseMsg;
        }
Пример #11
0
        public HttpResponseMessage PutComment(int postId, CommentNewModel model,
            [ValueProvider(typeof(HeaderValueProviderFactory<string>))] string sessionKey)
        {
            var responseMsg = this.PerformOperationAndHandleExceptions(
              () =>
              {
                  var context = new BlogSystemContext();
                  using (context)
                  {
                      var user = context.Users.FirstOrDefault(
                          usr => usr.SessionKey == sessionKey);

                      if (user == null)
                      {
                          throw new InvalidOperationException("Invalid sessionKey");
                      }

                      var post = context.Posts.FirstOrDefault(p => p.Id == postId);

                      if (post == null)
                      {
                          throw new InvalidOperationException("Invalid postId");
                      }

                      if (model.Text == null)
                      {
                          throw new ArgumentNullException("Comment text cannot be null");
                      }

                      var comment = new Comment()
                      {
                          Text = model.Text,
                          User = user,
                          PostDate = DateTime.Now,
                          Post = post
                      };

                      context.Comments.Add(comment);
                      context.SaveChanges();

                      var response =
                          this.Request.CreateResponse(HttpStatusCode.OK, "NULL");
                      return response;
                  }
              });

            return responseMsg;
        }