Exemplo n.º 1
0
        public IHttpActionResult PutComment(int id, CommentRequestModel commentRequest)
        {
            Comment comment;

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

            try
            {
                comment = repository.GetById(id);
            }
            catch (Exception)
            {
                throw;
            }

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

            comment.UpdatedAt = DateTime.Now;
            comment.Content   = commentRequest.Content;

            repository.Update(comment);

            return(Ok());
        }
        public CommentResponseModel AddCommentToEstate(string userId, CommentRequestModel comment)
        {
            var user = this.users
                .GetById(userId);
            var newComment = new Comment()
            {
                Content = comment.Content,
                CreatedOn = DateTime.Now,
                EstateId = comment.RealEstateId,
                UserId = userId,
                User = user
            };

            user.Comments.Add(newComment);
            this.users.SaveChanges();

            var responseModel = new CommentResponseModel()
            {
                Content = newComment.Content,
                CreatedOn = newComment.CreatedOn,
                UserName = newComment.User.UserName
            };

            return responseModel;
        }
Exemplo n.º 3
0
        public IHttpActionResult CreateArtileComment(int id, CommentRequestModel model)
        {
            var user       = this.User.Identity.Name;
            var newComment = this.articleService.AddComment(id, model.Content, user);

            return(this.Created("api/articles/" + id, newComment));
        }
        [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);
        }
Exemplo n.º 5
0
        public IHttpActionResult Post(int photoId, CommentRequestModel comment)
        {
            if (!this.ModelState.IsValid)
            {
                return(this.BadRequest(this.ModelState));
            }

            var photo = this.photos
                        .All()
                        .FirstOrDefault(p => p.Id == photoId);

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

            var commentToAdd = new Comment()
            {
                Content = comment.Content,
                UserId  = comment.UserId
            };

            photo.Comments.Add(commentToAdd);
            this.photos.SaveChanges();

            return(this.Ok("Comment successfully added."));
        }
Exemplo n.º 6
0
        public IHttpActionResult Put(int id, CommentRequestModel comment)
        {
            if (!this.ModelState.IsValid)
            {
                return(this.BadRequest(this.ModelState));
            }

            var currentComment = this.comments
                                 .All()
                                 .FirstOrDefault(c => c.Id == id);

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

            if (currentComment.User.UserName != this.User.Identity.Name)
            {
                return(this.Unauthorized());
            }

            currentComment.Content = comment.Content;

            this.comments.Update(currentComment);
            this.comments.SaveChanges();

            return(this.Ok("Comment updated"));
        }
        public IHttpActionResult Comment(int id, CommentRequestModel model)
        {
            var suggestion = this.suggestions
                             .GetSuggestionById(id)
                             .SingleOrDefault();

            if (suggestion == null)
            {
                return(this.BadRequest("Suggestion does not exist"));
            }

            if (!this.suggestions.UserIsEligibleToGetSuggestion(suggestion, this.User.IsInRole(UserConstants.AdminRole)))
            {
                return(this.BadRequest("You do not have permission to comment that suggestion!"));
            }

            var newComment = this.comments
                             .AddComment(id, this.User.Identity.GetUserId(), Mapper.Map <Comment>(model));

            var updatedSuggestion = this.suggestions
                                    .UpdateSuggestionCommentsCount(suggestion, suggestion.CommentsCount + 1);

            var result = Mapper.Map <CommentResponseModel>(newComment);

            return(this.Ok(result));
        }
        public async Task <ApiBaseResponse> FavoritePostAsync(CommentRequestModel comment)
        {
            var userId = Guid.Parse(_httpContextAccessor?.HttpContext?.User?.Identity?.Name);

            BlogStatsItem statsItem = new BlogStatsItem();

            if (await _blogStatsItemRepository.ExistsAsync(c => c.PostId == comment.PostId))
            {
                statsItem = await _blogStatsItemRepository.GetAsync(c => c.PostId == comment.PostId);

                statsItem.FavouriteCount = statsItem.FavouriteCount + 1;
                statsItem.Favorites.Add(new Favorite {
                    Id = Guid.NewGuid(), UserId = userId
                });
                await _blogStatsItemRepository.UpdateAsync(statsItem);
            }
            else
            {
                statsItem = new BlogStatsItem
                {
                    Id             = Guid.NewGuid(),
                    PostId         = comment.PostId,
                    FavouriteCount = 1,
                    CommentCount   = 0
                };
                statsItem.Favorites.Add(new Favorite {
                    Id = Guid.NewGuid(), UserId = userId
                });
                await _blogStatsItemRepository.AddAsync(statsItem);
            }
            return(new ApiBaseResponse(HttpStatusCode.OK, ApplicationStatusCode.Success, null, "Succesfully favorited."));
        }
        public IHttpActionResult AddComment(CommentRequestModel model)
        {
            if (model == null || !this.ModelState.IsValid)
            {
                return this.BadRequest(InvalidModelMessage);
            }

            var entity = new Comment
            {
                Content = model.Content,
                UserName = this.identityProvider.GetIdentity().GetUserId(),
                CreatedOn = DateTime.Now,
                RealEstateId = model.RealEstateId
            };

            this.comments.Add(entity);

            CommentResponseModel response = this.comments
                .All()
                .Where(x => x.RealEstateId == entity.RealEstateId & x.Content == entity.Content)
                .ProjectTo<CommentResponseModel>()
                .FirstOrDefault();

            return this.Created("api/Comments", response);
        }
Exemplo n.º 10
0
        public IActionResult GetByPostId([FromBody] CommentRequestModel model)
        {
            if (!_accountDomainService.CheckIfUserExistsFromHeader(HttpContext.Request))
            {
                return(Unauthorized());
            }
            else
            {
                var comments = _commentRepository.GetAll()
                               .Where(p => p.PostId == model.PostId)
                               .Include(q => q.Creator)
                               .OrderBy(p => p.CreatedAt)
                               .Skip((model.Page - 1) * model.Size)
                               .Take(model.Size)
                               .ToList();

                var outputModel = comments.Select(p => new CommentOutputModel
                {
                    Id          = p.Id,
                    Content     = p.Content,
                    PostId      = p.PostId,
                    CreatorName = p.Creator.Name,
                    CreatorId   = p.CreatorId,
                    CreatedAt   = p.CreatedAt
                }).ToList();

                return(Ok(outputModel));
            }
        }
Exemplo n.º 11
0
        public async Task <IActionResult> Post([FromBody] CommentRequestModel model)
        {
            Comment newComment = null;

            if (ModelState.IsValid)
            {
                InitUserCredentials();

                newComment = _mapper.Map(model, new Comment
                {
                    Guid             = Guid.NewGuid(),
                    UserGuid         = UserGuid,
                    CompanyGuid      = CompanyGuid,
                    CreationTime     = DateTime.UtcNow,
                    CreationUserGuid = UserGuid
                }
                                         );

                try
                {
                    await _commentService.Save(newComment);
                }
                catch (Exception e)
                {
                    Log.Error(e.StackTrace);
                    throw;
                }
            }

            return(CreatedAtAction(nameof(Post), _mapper.Map(newComment, new CommentResponseModel())));
        }
        public IHttpActionResult CreateArtileComment(int id, CommentRequestModel model)
        {
            var user = this.User.Identity.Name;
            var newComment = this.articleService.AddComment(id, model.Content, user);

            return this.Created("api/articles/" + id, newComment);
        }
Exemplo n.º 13
0
        public IActionResult AddComment([FromBody] CommentRequestModel model)
        {
            var user = this.User.FindFirst(ClaimTypes.NameIdentifier).Value;

            PostDAL.AddComment(model, user);

            return(new OkResult());
        }
        public Comment UpdateComment(Comment commentToUpdate, CommentRequestModel model)
        {
            commentToUpdate.Content = model.Content;

            this.comments.SaveChanges();

            return(commentToUpdate);
        }
Exemplo n.º 15
0
        public async Task <IHttpActionResult> Edit(CommentRequestModel comment)
        {
            var edittedComment = await this.commentsService.EditComment(comment.Id, comment.CommentText, this.CurrentUser.UserName, this.CurrentUser.IsAdmin);

            var model = this.mappingService.Map <CommentResponseModel>(edittedComment);

            return(this.Data(model));
        }
        public IHttpActionResult AddCommentToEstate(CommentRequestModel model)
        {
            var loggedUserId = this.User.Identity.GetUserId();

            var addedComment = this.comments
                .AddCommentToEstate(loggedUserId, model);

            return this.Ok(addedComment);
        }
Exemplo n.º 17
0
        public IHttpActionResult Post(CommentRequestModel model)
        {
            var newComment = Mapper.Map <Comment>(model);
            var id         = this.comments.AddNew(newComment, this.User.Identity.GetUserId());

            var result = this.comments
                         .GetById(id)
                         .ProjectTo <CommentResponseModel>()
                         .FirstOrDefault();

            return(this.Created($"/api/Comments/{id}", result));
        }
        public IHttpActionResult Post(CommentRequestModel model)
        {
            var newComment = Mapper.Map<Comment>(model);
            var id = this.comments.AddNew(newComment, this.User.Identity.GetUserId());

            var result = this.comments
                .GetById(id)
                .ProjectTo<CommentResponseModel>()
                .FirstOrDefault();

            return this.Created($"/api/Comments/{id}", result);
        }
Exemplo n.º 19
0
        public async Task <IHttpActionResult> Post(int id, CommentRequestModel comment)
        {
            var postedComment = await this.commentsService.AddNew(id, comment.CommentText, this.CurrentUser.UserName);

            var model = await this.commentsService
                        .CommentById(postedComment.Id)
                        .Project()
                        .To <CommentResponseModel>()
                        .FirstOrDefaultAsync();

            return(this.Data(model));
        }
        public async Task <IActionResult> Comments([FromBody] CommentRequestModel model, Guid id)
        {
            var response = new APIResponse <CommentResponseModel>()
            {
                Success = true
            };

            try
            {
                if (ModelState.IsValid)
                {
                    var check = await _accountCtx.Citations.ForAccount(CommonAccount.Id).AsNoTracking().AnyAsync(x => x.Id == id);

                    if (check)
                    {
                        var user = await _accountCtx.AccountUsers.AsNoTracking().AnyAsync(x => x.Id == model.CreatedUserId);

                        if (user)
                        {
                            var result = await _citationSvc.SaveComment(CommonAccount.Id, id, model.CommentId, model.Comment, model.IsPublic, model.CreatedUserId);

                            response.Message = "Comment Saved Successfully.";
                        }
                        else
                        {
                            response.Success = false;
                            response.Errors.Add(new Error {
                                Code = 0, Message = "Invalid Created User Id"
                            });
                        }
                    }
                    else
                    {
                        response.Success = false;
                        response.Errors.Add(new Error {
                            Code = 0, Message = "Invalid Citation Id "
                        });
                    }
                }
                else
                {
                    response.Success = false;
                    response.Errors.AddRange(ModelState.ToErrors());
                }
            }
            catch (Exception ex)
            {
                response.Success = false;
                response.Message = ex.Message;
            }
            return(Ok(response));
        }
Exemplo n.º 21
0
        public IHttpActionResult PostSubComment(int id, [FromBody] CommentRequestModel model)
        {
            if (!this.ModelState.IsValid)
            {
                return(this.BadRequest(this.ModelState));
            }

            var dataModel = Mapper.Map <Comment>(model);

            var commentId = this.comments.AddSubComment(id, dataModel, this.User.Identity.Name);

            return(this.Ok(commentId));
        }
Exemplo n.º 22
0
        public IHttpActionResult PostComment(CommentRequestModel model)
        {
            if (!this.ModelState.IsValid)
            {
                return this.BadRequest(this.ModelState);
            }

            var dataModel = Mapper.Map<Comment>(model);

            var commentId = this.comments.Add(dataModel, this.User.Identity.Name);

            return this.Ok(commentId);
        }
        public IHttpActionResult Post(CommentRequestModel model)
        {
            var comment = this.comments
                          .CreateComment(content: model.Content, realEstateId: model.RealEstateId, userId: this.User.Identity.GetUserId());

            var commentResult = this.comments
                                .GetCommentDetails(comment.Id)
                                .ProjectTo <CommentResponseModel>()
                                .FirstOrDefault();

            var location = string.Format("api/comments/{0}", comment.Id);

            return(this.Created(location, commentResult));
        }
Exemplo n.º 24
0
        public static void AddComment(CommentRequestModel model, string userId)
        {
            var comment = new CommentModel
            {
                Content = model.Content,
                UserId  = userId,
                PostId  = model.PostId
            };

            using (var ctx = new AppDbContext())
            {
                ctx.Add(comment);
                ctx.SaveChanges();
            }
        }
Exemplo n.º 25
0
        public void PutWithInvalidModelShouldReturnInvalidModelStateResult()
        {
            var controller = ControllerMockFactory.GetCommentsController(this.comments, this.photos);

            controller.ModelState.AddModelError("content", "Invalid content!");

            var updatedComment       = new CommentRequestModel();
            var result               = controller.Put(0, updatedComment);
            var expectedUpdatedCount = 0;
            var expectedSaveChanges  = 0;

            Assert.IsNotNull(result);
            Assert.IsInstanceOfType(result, typeof(InvalidModelStateResult));
            Assert.AreEqual(expectedUpdatedCount, this.comments.UpdatedEntities.Count);
            Assert.AreEqual(expectedSaveChanges, this.comments.NumberOfSaves);
        }
Exemplo n.º 26
0
        public void PostWithInvalidModelShouldReturnInvalidModelStateResult()
        {
            var controller = ControllerMockFactory.GetCommentsController(this.comments, this.photos);

            controller.ModelState.AddModelError("content", "Invalid content!");

            var commentToBeAdded = new CommentRequestModel();
            var result           = controller.Post(0, commentToBeAdded);
            var expectedNumberOfCommentsAdded = 0;
            var expectedSaveChanges           = 0;

            Assert.IsNotNull(result);
            Assert.IsInstanceOfType(result, typeof(InvalidModelStateResult));
            Assert.AreEqual(expectedNumberOfCommentsAdded, this.photos.GetById(0).Comments.Count);
            Assert.AreEqual(expectedSaveChanges, this.photos.NumberOfSaves);
        }
Exemplo n.º 27
0
        public IHttpActionResult PutComment(int id, CommentRequestModel commentRequest)
        {
            Comment comment;
            var     userData = GetCurrentUser(db);

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

            try
            {
                comment = repository.GetById(id);
            }
            catch (Exception)
            {
                throw;
            }

            if (userData.Id.Equals(comment.UserId))
            {
                if (id != comment.Id)
                {
                    return(BadRequest());
                }
                //
                commentRequest.Id          = comment.Id;
                commentRequest.LostStuffId = comment.LostStuffId;
                //

                comment.UpdatedAt = DateTime.Now;
                comment.Content   = commentRequest.Content;

                repository.Update(comment);

                return(Ok("The comment was edited " +
                          new { comment.Id,
                                comment.Content,
                                comment.LostStuffId,
                                comment.UserId,
                                comment.UserName }));
            }
            else
            {
                return(BadRequest("You do not have permissions to edit!"));
            }
        }
Exemplo n.º 28
0
        public void PutWithInvalidUserShouldReturnUnauthorisedResult()
        {
            var controller = ControllerMockFactory.GetCommentsController(this.comments, this.photos, false);

            var updatedComment = new CommentRequestModel()
            {
                Content = "Edited Content"
            };
            var result = controller.Put(TestConstants.DefaultNonExistingModelId, updatedComment);
            var expectedUpdatedCount = 0;
            var expectedSaveChanges  = 0;

            Assert.IsNotNull(result);
            Assert.IsInstanceOfType(result, typeof(NotFoundResult));
            Assert.AreEqual(expectedUpdatedCount, this.comments.UpdatedEntities.Count);
            Assert.AreEqual(expectedSaveChanges, this.comments.NumberOfSaves);
        }
Exemplo n.º 29
0
        public void PostWithInvalidPhotoIdShouldReturnNotFoundResult()
        {
            var controller = ControllerMockFactory.GetCommentsController(this.comments, this.photos);

            var commentToBeAdded = new CommentRequestModel()
            {
                Content = TestConstants.ValidContent,
                UserId  = TestConstants.ValidUserId
            };
            var result = controller.Post(TestConstants.DefaultNonExistingModelId, commentToBeAdded);
            var expectedNumberOfCommentsAdded = 0;
            var expectedSaveChanges           = 0;

            Assert.IsNotNull(result);
            Assert.IsInstanceOfType(result, typeof(NotFoundResult));
            Assert.AreEqual(expectedNumberOfCommentsAdded, this.photos.GetById(0).Comments.Count);
            Assert.AreEqual(expectedSaveChanges, this.photos.NumberOfSaves);
        }
Exemplo n.º 30
0
        public void PutWithValidDataShouldReturnOkResult()
        {
            var controller = ControllerMockFactory.GetCommentsController(this.comments, this.photos);

            var updatedComment = new CommentRequestModel()
            {
                Content = "Edited Content"
            };
            var result               = controller.Put(0, updatedComment);
            var actual               = result as OkNegotiatedContentResult <string>;
            var expectedContent      = "Comment updated";
            var expectedUpdatedCount = 1;
            var expectedSaveChanges  = 1;

            Assert.IsNotNull(result);
            Assert.AreEqual(expectedContent, actual.Content);
            Assert.AreEqual(expectedUpdatedCount, this.comments.UpdatedEntities.Count);
            Assert.AreEqual(expectedSaveChanges, this.comments.NumberOfSaves);
        }
Exemplo n.º 31
0
        public IHttpActionResult PostNewComment(CommentRequestModel model)
        {
            if (!this.ModelState.IsValid)
            {
                return(this.BadRequest(this.ModelState));
            }

            var userId = this.User.Identity.GetUserId();

            var newComment = Mapper.Map <Comment>(model);

            newComment.UserId = userId;

            this.commentsService.AddNewComment(newComment);

            var createdCommentResponse = Mapper.Map <CommentEstateDetailsResponseModel>(newComment);

            return(this.Created("api/comments", createdCommentResponse));
        }
Exemplo n.º 32
0
        public void PostWithValidDataShouldReturnOkResult()
        {
            var controller = ControllerMockFactory.GetCommentsController(this.comments, this.photos);

            var commentToBeAdded = new CommentRequestModel()
            {
                Content = TestConstants.ValidContent,
                UserId  = TestConstants.ValidUserId
            };
            var result                        = controller.Post(0, commentToBeAdded);
            var actual                        = result as OkNegotiatedContentResult <string>;
            var expectedContent               = "Comment successfully added.";
            var expectedSaveChanges           = 1;
            var expectedNumberOfCommentsAdded = 1;

            Assert.IsNotNull(result);
            Assert.AreEqual(expectedContent, actual.Content);
            Assert.AreEqual(expectedNumberOfCommentsAdded, this.photos.GetById(0).Comments.Count);
            Assert.AreEqual(expectedSaveChanges, this.photos.NumberOfSaves);
        }
Exemplo n.º 33
0
        public IHttpActionResult Post(int id, CommentRequestModel comment)
        {
            if (!ModelState.IsValid)
            {
                return(this.BadRequest());
            }

            var currentUserId = this.User.Identity.GetUserId();

            var commentToAdd = new Comment
            {
                ArticleId = id,
                Content   = comment.Content,
                UserId    = currentUserId
            };

            this.comments.Add(commentToAdd);

            return(this.Ok("Comment added!"));
        }
Exemplo n.º 34
0
        public IHttpActionResult Put(int id, CommentRequestModel model)
        {
            var comment = this.comments
                          .GetCommentById(id)
                          .SingleOrDefault();

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

            if (!this.comments.UserIsEligibleToModifyComment(comment, this.User.Identity.GetUserId(), this.User.IsInRole(UserConstants.AdminRole)))
            {
                return(this.BadRequest("You are not allowed to modify this comment!"));
            }

            var updatedComment = this.comments
                                 .UpdateComment(comment, model);

            return(this.Ok(Mapper.Map <CommentResponseModel>(updatedComment)));
        }
Exemplo n.º 35
0
        public async Task <IActionResult> Put([FromBody] CommentRequestModel model, Guid guid)
        {
            if (ModelState.IsValid)
            {
                if (guid == Guid.Empty)
                {
                    return(new BadRequestResult());
                }

                Comment comment = await _commentService.Get(guid);

                if (comment == null)
                {
                    return(new NoContentResult());
                }

                InitUserCredentials();

                if (comment.UserGuid != UserGuid)
                {
                    return(new UnauthorizedResult());
                }

                var mapped = _mapper.Map(model, comment);
                mapped.LastUpdateUserGuid = UserGuid;
                mapped.LastUpdateTime     = DateTime.Now;

                try
                {
                    await _commentService.Save(mapped);
                }
                catch (Exception e)
                {
                    Log.Error(e.StackTrace);
                    throw;
                }
            }

            return(new OkResult());
        }
Exemplo n.º 36
0
        public async Task <IActionResult> Post(Guid deviceId, [FromBody] CommentRequestModel commentString)
        {
            try
            {
                var commentId = await _commentService.CreateAsync(Token, deviceId, commentString.Comment);

                return(Created(HttpContext.Request.GetEncodedUrl(), commentId));
            }
            catch (ArgumentNullException ex)
            {
                _logger.LogError(ex.Message);
                return(BadRequest(ex.Message));
            }
            catch (ArgumentException ex)
            {
                _logger.LogError(ex.Message);
                return(BadRequest(ex.Message));
            }
            catch (ApplicationException ex)
            {
                _logger.LogError(ex.Message);
                return(BadRequest(ex.Message));
            }
        }
        public void PutWithInvalidModelShouldReturnInvalidModelStateResult()
        {
            var controller = ControllerMockFactory.GetCommentsController(this.comments, this.photos);
            controller.ModelState.AddModelError("content", "Invalid content!");

            var updatedComment = new CommentRequestModel();
            var result = controller.Put(0, updatedComment);
            var expectedUpdatedCount =0;
            var expectedSaveChanges = 0;

            Assert.IsNotNull(result);
            Assert.IsInstanceOfType(result, typeof(InvalidModelStateResult));
            Assert.AreEqual(expectedUpdatedCount, this.comments.UpdatedEntities.Count);
            Assert.AreEqual(expectedSaveChanges, this.comments.NumberOfSaves);
        }
Exemplo n.º 38
0
        public IHttpActionResult Put(int id, CommentRequestModel comment)
        {
            if (!this.ModelState.IsValid)
            {
                return this.BadRequest(this.ModelState);
            }

            var currentComment = this.comments
                .All()
                .FirstOrDefault(c => c.Id == id);

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

            if (currentComment.User.UserName != this.User.Identity.Name)
            {
                return this.Unauthorized();
            }

            currentComment.Content = comment.Content;

            this.comments.Update(currentComment);
            this.comments.SaveChanges();

            return this.Ok("Comment updated");
        }
        public void PostWithInvalidModelShouldReturnInvalidModelStateResult()
        {
            var controller = ControllerMockFactory.GetCommentsController(this.comments, this.photos);
            controller.ModelState.AddModelError("content", "Invalid content!");

            var commentToBeAdded = new CommentRequestModel();
            var result = controller.Post(0, commentToBeAdded);
            var expectedNumberOfCommentsAdded = 0;
            var expectedSaveChanges = 0;

            Assert.IsNotNull(result);
            Assert.IsInstanceOfType(result, typeof(InvalidModelStateResult));
            Assert.AreEqual(expectedNumberOfCommentsAdded, this.photos.GetById(0).Comments.Count);
            Assert.AreEqual(expectedSaveChanges, this.photos.NumberOfSaves);
        }
        public void PostWithInvalidPhotoIdShouldReturnNotFoundResult()
        {
            var controller = ControllerMockFactory.GetCommentsController(this.comments, this.photos);

            var commentToBeAdded = new CommentRequestModel()
            {
                Content = TestConstants.ValidContent,
                UserId = TestConstants.ValidUserId
            };
            var result = controller.Post(TestConstants.DefaultNonExistingModelId, commentToBeAdded);
            var expectedNumberOfCommentsAdded = 0;
            var expectedSaveChanges = 0;

            Assert.IsNotNull(result);
            Assert.IsInstanceOfType(result, typeof(NotFoundResult));
            Assert.AreEqual(expectedNumberOfCommentsAdded, this.photos.GetById(0).Comments.Count);
            Assert.AreEqual(expectedSaveChanges, this.photos.NumberOfSaves);
        }
Exemplo n.º 41
0
        public IHttpActionResult Post(int photoId, CommentRequestModel comment)
        {
            if (!this.ModelState.IsValid)
            {
                return this.BadRequest(this.ModelState);
            }

            var photo = this.photos
                .All()
                .FirstOrDefault(p => p.Id == photoId);

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

            var commentToAdd = new Comment()
            {
                Content = comment.Content,
                UserId = comment.UserId
            };

            photo.Comments.Add(commentToAdd);
            this.photos.SaveChanges();

            return this.Ok("Comment succesfully added.");
        }
        public void PutWithInvalidUserShouldReturnUnauthorisedResult()
        {
            var controller = ControllerMockFactory.GetCommentsController(this.comments, this.photos, false);

            var updatedComment = new CommentRequestModel()
            {
                Content = "Edited Content"
            };
            var result = controller.Put(TestConstants.DefaultNonExistingModelId, updatedComment);
            var expectedUpdatedCount = 0;
            var expectedSaveChanges = 0;

            Assert.IsNotNull(result);
            Assert.IsInstanceOfType(result, typeof(NotFoundResult));
            Assert.AreEqual(expectedUpdatedCount, this.comments.UpdatedEntities.Count);
            Assert.AreEqual(expectedSaveChanges, this.comments.NumberOfSaves);
        }
        public void PutWithValidDataShouldReturnOkResult()
        {
            var controller = ControllerMockFactory.GetCommentsController(this.comments, this.photos);

            var updatedComment = new CommentRequestModel()
            {
                Content = "Edited Content"
            };
            var result = controller.Put(0, updatedComment);
            var actual = result as OkNegotiatedContentResult<string>;
            var expectedContent = "Comment updated";
            var expectedUpdatedCount = 1;
            var expectedSaveChanges = 1;

            Assert.IsNotNull(result);
            Assert.AreEqual(expectedContent, actual.Content);
            Assert.AreEqual(expectedUpdatedCount, this.comments.UpdatedEntities.Count);
            Assert.AreEqual(expectedSaveChanges, this.comments.NumberOfSaves);
        }
        public void PostWithValidDataShouldReturnOkResult()
        {
            var controller = ControllerMockFactory.GetCommentsController(this.comments, this.photos);

            var commentToBeAdded = new CommentRequestModel()
            {
                Content = TestConstants.ValidContent,
                UserId = TestConstants.ValidUserId
            };
            var result = controller.Post(0, commentToBeAdded);
            var actual = result as OkNegotiatedContentResult<string>;
            var expectedContent = "Comment succesfully added.";
            var expectedSaveChanges = 1;
            var expectedNumberOfCommentsAdded = 1;

            Assert.IsNotNull(result);
            Assert.AreEqual(expectedContent, actual.Content);
            Assert.AreEqual(expectedNumberOfCommentsAdded, this.photos.GetById(0).Comments.Count);
            Assert.AreEqual(expectedSaveChanges, this.photos.NumberOfSaves);
        }
        public IHttpActionResult Post(CommentRequestModel model)
        {
            var userId = this.User.Identity.GetUserId();
            var realEstate = this.data.RealEstates.GetById(model.RealEstateId);
            if (realEstate == null)
            {
                return this.BadRequest("No such realEstate with the provided id");
            }

            var comment = new Comment()
            {
                RealEstateId = model.RealEstateId,
                Content = model.Content,
                CreatedOn = DateTime.UtcNow,
                UserId = userId
            };
            this.data.Comments.Add(comment);
            this.data.SaveChanges();

            var response = this.data.Comments.All()
                .Where(c => c.Id == comment.Id)
                .ProjectTo<CommentResponseModel>()
                .FirstOrDefault();

            return this.Created("api/Comments", response);
        }