public IActionResult CreateComment(int cardId, [FromBody] CommentForCreationDto comment) { if (comment == null) { return(BadRequest()); } if (comment.User == comment.Description) { ModelState.AddModelError("Desctiption", "The provided Description should be different from the User."); } if (!ModelState.IsValid) { return(BadRequest()); } if (!_cardRepository.CardExists(cardId)) { return(NotFound()); } var finalComment = Mapper.Map <Comment>(comment); _cardRepository.AddComment(cardId, finalComment); if (!_cardRepository.Save()) { return(StatusCode(500, "A problem happened while handling your request")); } var createCommentToReturn = Mapper.Map <CommentDto>(finalComment); return(CreatedAtRoute("GetComment", new { cardId = cardId, commentId = createCommentToReturn.Id }, createCommentToReturn)); }
public static void UpdateCommentFromDto(Comment commentToUpdate, CommentForCreationDto commentWithUpdatedValues) { commentToUpdate.Content = commentWithUpdatedValues.Content; commentToUpdate.CreationTime = commentWithUpdatedValues.CreationTime; commentToUpdate.TaskId = commentWithUpdatedValues.TaskId; commentToUpdate.UserId = commentWithUpdatedValues.UserId; }
public ActionResult PostComment(CommentForCreationDto commentForCreation) { //Gets username from the token var username = HttpContext.User.Identity.Name; var comment = _mapper.Map <Comment>(commentForCreation); //Check if the realestate-id maps to an actual entity if (!_unitOfWork.RealEstateRepository.EntityExists(comment.RealEstateId)) { ApiErrorResponseBody errorResponse = new ApiErrorResponseBody(false); errorResponse.AddError("RealEstate", new string[] { $"Could not find a Real Estate with id {comment.RealEstateId}" }); return(NotFound(errorResponse)); } //get current users Id, and adds it to the new comment comment.UserId = _unitOfWork.UserRepository.Get(username).Id; _unitOfWork.CommentRepository.Add(comment); _unitOfWork.SaveChanges(); var commentToReturn = _mapper.Map <CommentDto>(comment); return(CreatedAtRoute( "GetComment", new { id = comment.RealEstateId }, commentToReturn)); }
public async Task <IActionResult> CreateComment(int userId, CommentForCreationDto commentForCreationDto) { var sender = await _userRepo.GetUser(userId); // for automapper magic!!!! if (sender.Id != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value)) { return(Unauthorized()); } commentForCreationDto.SenderId = userId; var blog = await _repo.GetBlog(commentForCreationDto.BlogId); // for automapper magic!!!! if (blog == null) { return(BadRequest("Could not find the blog")); } var comment = _mapper.Map <Comment>(commentForCreationDto); _repo.Add(comment); if (await _repo.SaveAll()) { var commentToReturn = _mapper.Map <CommentForReturnDto>(comment); return(CreatedAtRoute("GetComment", new { userId, id = comment.Id }, commentToReturn)); } throw new Exception("Failed to create the comment"); }
public async Task <IActionResult> CreateCommentForPost(Guid postId, [FromBody] CommentForCreationDto comment) { if (comment == null) { _logger.LogError("CommentForCreationDto object sent from client is null."); return(BadRequest("CommentForCreationDto object is null")); } if (!ModelState.IsValid) { _logger.LogError("Invalid model state for the CommentForCreationDto object"); return(UnprocessableEntity(ModelState)); } var post = await _context.Posts.GetPostAsync(postId, trackChanges : false); if (post == null) { _logger.LogInfo($"Post with id: {postId} doesn't exist in the database."); return(NotFound()); } var commentEntity = _mapper.Map <Comment>(comment); _context.Comments.CreateCommentForPost(postId, commentEntity); await _context.SaveAsync(); var commentToReturn = _mapper.Map <CommentDto>(commentEntity); return(CreatedAtRoute("GetCommentForPost", new { postId, id = commentToReturn.Id }, commentToReturn)); }
public async Task <IActionResult> CreateComment(int userId, string albumId, CommentForCreationDto commentForCreationDto) { var commenter = await this.repo.GetUser(userId); if (commenter.Id != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value)) { return(Unauthorized()); } commentForCreationDto.AlbumId = albumId; commentForCreationDto.CommenterId = userId; var album = await this.repo.GetAlbum(commentForCreationDto.AlbumId); if (album == null) { repo.AddAlbum(new Album { Id = commentForCreationDto.AlbumId }); } var comment = this.mapper.Map <Comment>(commentForCreationDto); this.repo.Add(comment); if (!await this.repo.SaveAll()) { throw new Exception("Creating the comment failed on save"); } var commentToReturn = this.mapper.Map <CommentToReturnDto>(comment); return(CreatedAtRoute("GetComment", new { userId, albumId, id = comment.Id }, commentToReturn)); }
public void AddComment_Unauthorized_ReturnsUnauth() { // Arrange int userId = 1; int postId = 2; var postFromRepo = GetFakePostList().SingleOrDefault(x => x.PostId == postId); var commentForCreation = new CommentForCreationDto { Text = "Test comment2" }; commentForCreation.CommenterId = userId; _repoMock.Setup(x => x.GetPost(postId)).ReturnsAsync(postFromRepo); _repoMock.Setup(x => x.Add(commentForCreation)); _repoMock.Setup(x => x.SaveAll()).ReturnsAsync(true); // Act var result = _postsController.AddComment(userId, postId, commentForCreation).Result; // Assert var okResult = Assert.IsType <UnauthorizedResult>(result); // var returnPost = Assert.IsType<PostsForDetailedDto>(okResult.Value); }
public void AddComment_PostNotFound_ReturnsNotFound() { // Arrange int userId = 2; int postId = 5; var postFromRepo = GetFakePostList().SingleOrDefault(x => x.PostId == postId); var userFromRepo = GetFakeUserList().SingleOrDefault(x => x.Id == userId); var commentForCreation = new CommentForCreationDto { Text = "Test comment" }; commentForCreation.CommenterId = userId; _repoMock.Setup(x => x.GetUser(userId)).ReturnsAsync(userFromRepo); _repoMock.Setup(x => x.GetPost(postId)).ReturnsAsync(postFromRepo); _repoMock.Setup(x => x.Add(commentForCreation)); _repoMock.Setup(x => x.SaveAll()).ReturnsAsync(true); // Act var result = _postsController.AddComment(userId, postId, commentForCreation).Result; // Assert var okResult = Assert.IsType <NotFoundObjectResult>(result); Assert.Equal("Post with id 5 not found", okResult.Value); }
public void AddComment_UserNoProfilePic_CommentAddedSuccessfully_ReturnsPostWithComment() { // Arrange int userId = 2; int postId = 2; var postFromRepo = GetFakePostList().SingleOrDefault(x => x.PostId == postId); var userFromRepo = GetFakeUserList().SingleOrDefault(x => x.Id == userId); var commentForCreation = new CommentForCreationDto { Text = "Test comment" }; commentForCreation.CommenterId = userId; _repoMock.Setup(x => x.GetUser(userId)).ReturnsAsync(userFromRepo); _repoMock.Setup(x => x.GetPost(postId)).ReturnsAsync(postFromRepo); _repoMock.Setup(x => x.Add(commentForCreation)); _repoMock.Setup(x => x.SaveAll()).ReturnsAsync(true); // Act var result = _postsController.AddComment(userId, postId, commentForCreation).Result; // Assert var okResult = Assert.IsType <OkObjectResult>(result); var returnPost = Assert.IsType <CommentsForReturnedDto>(okResult.Value); }
public async Task <IActionResult> CreateComment(CommentForCreationDto commentForCreationDto) { // if (creator.Id != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value)) // return Unauthorized(); var comment = _mapper.Map <Comment>(commentForCreationDto); comment.UserId = Int32.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)); var regexItem = new Regex("^[a-zA-Z0-9 ]*$"); if (!regexItem.IsMatch(comment.Description)) { throw new Exception("Description invalid"); } _repo.Add(comment); if (await _repo.SaveAll()) { var commentToReturn = _mapper.Map <CommentForReturnDto>(comment); //commentToReturn.UserName = comment.User.Username; return(CreatedAtRoute("GetComment", new { comment.TicketId, id = comment.Id }, commentToReturn)); } throw new Exception("Creating the comment failed on save"); }
public async Task <CommentDetailsDto> PostNewComment([FromRoute] int teamId, [FromRoute] int taskId, [FromBody] CommentForCreationDto dto) { dto.TasksId = taskId; dto.TeamId = teamId; return(await _mediator.Send(new CreateNewCommentCommand { CommentForCreationDto = dto })); }
public IActionResult CreateComment(int userId, int blogId, int postId, [FromBody] CommentForCreationDto comment, [FromHeader(Name = nameof(HeaderNames.Accept))] string mediaType) { if (!_weblogDataRepository.UserExists(userId) || !_weblogDataRepository.BlogExists(blogId) || !_weblogDataRepository.PostExists(postId)) { return(NotFound()); } if (!_weblogDataRepository.UserExists((int)comment.UserId)) { // adding comment with userId that doesn't exist ModelState.AddModelError(nameof(comment.UserId), "UserId does not exist."); return(ErrorHandler.UnprocessableEntity(ModelState, HttpContext)); } var emailAddress = comment.Credentials.EmailAddress; var password = comment.Credentials.Password; if (!_weblogDataRepository.Authorized((int)comment.UserId, emailAddress, password)) { return(Unauthorized()); } var commentEntity = _mapper.Map <Entities.Comment>(comment); _weblogDataRepository.AddComment(postId, commentEntity); _weblogDataRepository.Save(); var commentToReturn = _mapper.Map <CommentDto>(commentEntity); var includeLinks = MediaTypes.IncludeLinks(mediaType); if (!includeLinks) { return(CreatedAtRoute ( nameof(GetComment), new { userId, blogId, postId, commentId = commentToReturn.CommentId }, commentToReturn )); } var links = CreateLinksForComment(userId, blogId, postId, commentToReturn.CommentId, commentToReturn.UserId); var commentWithLinks = new CommentDtoWithLinks(commentToReturn, links); return(CreatedAtRoute ( nameof(GetComment), new { userId, blogId, postId, commentId = commentToReturn.CommentId }, commentWithLinks )); }
public async Task <IActionResult> PostCommentForUser(int userId, CommentForCreationDto commentForCreationDto) { if (userId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value)) { return(Unauthorized()); } return(Ok(await _commentsService.PostCommentForUser(userId, commentForCreationDto))); }
public static Comment GetCommentEntity(CommentForCreationDto commentDto) { return(new Comment() { UserId = commentDto.UserId, TaskId = commentDto.TaskId, Content = commentDto.Content, CreationTime = commentDto.CreationTime }); }
public async Task <IActionResult> AddComment(CommentForCreationDto commentForCreationDto) { if (commentForCreationDto.NickName == null) { return(BadRequest("Nie wprowadzono Nicku")); } await _commentRepository.AddComment(commentForCreationDto); return(Ok()); }
public IActionResult PostComment([FromBody] CommentForCreationDto commentFromRequest) { if (commentFromRequest == null) { return(BadRequest()); } if (!ModelState.IsValid) { return(BadRequest()); } _repo.AddComment(ModelsMapping.GetCommentEntity(commentFromRequest)); return(Ok()); }
public async Task PostComment_Authenticated_ValidComment_ShouldPostComment(int realEstateId, string content) { // Arrange var user = db.UserRepository.Get(1); if (user == null) { throw new Exception(noSampleUser); } var realestate = db.RealEstateRepository.Get(realEstateId); if (realestate == null) { throw new Exception(noSampleRealEstate); } var comment = db.CommentRepository.GetCommentByUser(user.UserName, content); if (comment != null) { throw new Exception(commentAlreadyExists); } var token = FakeToken.CreateFakeTokenByUser(user); _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); var commnetToPost = new CommentForCreationDto() { RealEstateId = 1, Content = content }; try { // Act var response = await _client.PostAsJsonAsync("", commnetToPost); // Assert response.StatusCode.Should().Be(HttpStatusCode.Created); response.Should().NotBe(""); var addedComment = db.CommentRepository.GetCommentByUser(user.UserName, content); addedComment.Should().NotBeNull(); } finally { RemoveCommentFromDb(user.UserName, content); } }
public async Task <IActionResult> AddComment([FromBody] CommentForCreationDto newComment, int id, int cityId, int placeId) { var placeFromRepo = await _repository.GetPlaceForCity(cityId, placeId); if (placeFromRepo == null) { return(NotFound()); } var commentToAdd = Mapper.Map <Comment>(newComment); commentToAdd.Date = DateTime.Now; _repository.AddCommentForPlace(commentToAdd); if (!await _repository.Save()) { throw new Exception("Failed"); } var commentsFromRepo = await _repository.GetCommentsForPlace(placeId); var avgRating = commentsFromRepo.Average(c => c.Rating); placeFromRepo.Rating = avgRating; if (!await _repository.Save()) { throw new Exception("Failed"); } var placesFromRepo = await _repository.GetPlacesForCity(cityId); avgRating = placesFromRepo.Average(p => p.Rating); var cityFromRepo = await _repository.GetCityForCountry(id, cityId); cityFromRepo.Rating = avgRating; if (!await _repository.Save()) { throw new Exception("Failed"); } var citiesFromRepo = await _repository.GetCitiesForCountry(id); avgRating = citiesFromRepo.Average(c => c.Rating); var countryFromRepo = await _repository.GetCountry(id); countryFromRepo.Rating = avgRating; if (!await _repository.Save()) { throw new Exception("Failed"); } return(NoContent()); }
public void Add_ValidObjectPassed_ReturnsCreatedAtRouteRequest() { // Arrange var commentWithMissingProperty = new CommentForCreationDto { SenderId = 5, BlogId = 1, CommentSent = DateTime.Now, Content = "Content" }; // Act var createdResponse = _controller.CreateComment(5, commentWithMissingProperty); //Assert Assert.IsType <CreatedAtRouteResult>(createdResponse); }
public async Task <IActionResult> AddNewCommentToAnEpisode(int episodeId, CommentForCreationDto newComment) { try { var episodeData = await _unitOfWork.GetRepository <Episode>().GetFirstOrDefaultAsync( selector: e => new EpisodeDto { Id = e.Id, Name = e.Name, EpisodeCode = e.EpisodeCode, ReleaseDate = e.ReleaseDate, NumberOfComments = e.EpisodeComments.Count, Created = e.Created, Modified = e.Modified }, include: source => source.Include(episode => episode.EpisodeComments), predicate: e => e.Id == episodeId ); if (episodeData is null) { return(NotFound(new JsonMessage <EpisodeDto>() { Success = false, ErrorMessage = "Episode record not found" })); } var commentEntity = new Comment { EpisodeId = episodeId, IpAddressLocation = newComment.IpAddressLocation, CommentText = newComment.CommentText, Created = DateTime.Now, Modified = DateTime.Now }; var commentRepo = _unitOfWork.GetRepository <Comment>(); commentRepo.Insert(commentEntity); await _unitOfWork.SaveChangesAsync(); return(Ok(new JsonMessage <bool>() { Success = true })); } catch (Exception ex) { //log ex return(StatusCode(StatusCodes.Status500InternalServerError, new JsonMessage <IPagedList <string> >() { Success = false, ErrorMessage = ex.Message })); } }
public async Task <IActionResult> CreateComment(int userId, int postId, CommentForCreationDto commentForCreationDto) { if (userId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value)) { return(Unauthorized()); } commentForCreationDto.UserId = userId; commentForCreationDto.PostId = postId; var comment = _mapper.Map <Comment>(commentForCreationDto); _repo.Add(comment); if (await _repo.SaveAll()) { var commentToReturn = _mapper.Map <CommentForReturnDto>(comment); return(CreatedAtRoute("GetComment", new { id = comment.Id }, commentToReturn)); } throw new Exception("Field To Create Comment"); }
public IActionResult PutComment([FromBody] CommentForCreationDto commentFromRequest, int commentId) { if (commentFromRequest == null) { return(NotFound()); } if (!ModelState.IsValid) { return(BadRequest()); } var comment = _repo.GetComment(commentId); ValuesUpdater.UpdateCommentFromDto(comment, commentFromRequest); _repo.SaveChanges(); return(Ok()); }
public void Add_IvalidObjectPassed_ReturnsBadRequest() { // Arrange var commentWithMissingProperty = new CommentForCreationDto { SenderId = 5, BlogId = 999, CommentSent = DateTime.Now }; _controller.ModelState.AddModelError("Content", "Required"); // Act var badResponse = _controller.CreateComment(5, commentWithMissingProperty); //Assert Assert.IsType <BadRequestObjectResult>(badResponse); }
public async Task <IActionResult> AddNewComment([FromForm] CommentForCreationDto newComment) { var identity = HttpContext.User.Identity as ClaimsIdentity; IEnumerable <Claim> claim = identity.Claims; var usernameClaim = claim .Where(x => x.Type == ClaimTypes.Name) .FirstOrDefault(); CommentForDisplayDto ret; if (usernameClaim != null) { ret = await _rep.AddCommentAsync(newComment.IdPosta, usernameClaim.Value, newComment.CommentText); } else { return(BadRequest()); } return(Ok(ret)); }
public async Task PostComment_Unauthenticated_ValidComment_ShouldReturnUnauthorized(int realEstateId, string content) { // Arrange var realestate = db.RealEstateRepository.Get(realEstateId); if (realestate == null) { throw new Exception(noSampleRealEstate); } var commnetToPost = new CommentForCreationDto() { RealEstateId = realEstateId, Content = content }; // Act var response = await _client.PostAsJsonAsync("", commnetToPost); // Assert response.StatusCode.Should().Be(HttpStatusCode.Unauthorized); }
public IActionResult AddComment([FromBody] CommentForCreationDto c) { var userName = User.Identity.Name; var user = db.Users.FirstOrDefault(u => u.Email == userName); var book = db.Books.FirstOrDefault(b => b.Id == c.BookId); if (book == null || user == null) { return(NotFound()); } var comment = new Comment { Book = book, User = user, Text = c.Text, CreatedOn = DateTime.Now, Rating = 0 }; db.Add(comment); db.SaveChanges(); return(Ok()); }
public async Task <IActionResult> AddComment(int userId, int postId, CommentForCreationDto commentForCreationDto) { if (userId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value)) { return(Unauthorized()); } var userFromRepo = await _recipeRepo.GetUser(userId); var usersMainPhoto = await _recipeRepo.GetMainPhotoForUser(userId); // Assign commenter id to the comment creator commentForCreationDto.CommenterId = userId; commentForCreationDto.Author = userFromRepo.UserName; commentForCreationDto.UserPhotoUrl = usersMainPhoto != null ? usersMainPhoto.Url : null; // Get post from repo var postFromRepo = await _recipeRepo.GetPost(postId); if (postFromRepo == null) { return(NotFound($"Post with id {postId} not found")); } // Map comment into CommentForCreationDto var comment = _mapper.Map <Comment>(commentForCreationDto); // Add comment into comments postFromRepo.Comments.Add(comment); if (await _recipeRepo.SaveAll()) { var commentToReturn = _mapper.Map <CommentsForReturnedDto>(comment); // return CreatedAtRoute("GetPost", new {userId = userId, id = comment.CommentId}, postToReturn); return(Ok(commentToReturn)); } throw new Exception("Creating the comment failed on save"); }
public void Create_Comment() { var controller = new CommentsController(new CommentRepositoryMock()); var commentForCreationAgent = new CommentForCreationDto() { Content = "There is an issue with this item!", TicketId = TicketRepositoryMock.TestTicket.Id }; var commentForCreationClient = new CommentForCreationDto() { Content = "There is an issue with this item!", TicketId = TicketRepositoryMock.TestTicket.Id }; var result = controller.Post(commentForCreationAgent, -1, ClientRepositoryMock.TestClient.Id); var okResult = result.Should().BeOfType <CreatedAtRouteResult>().Subject; var comment = okResult.Value.Should().BeAssignableTo <CommentWithTicketsDto>().Subject; }
public async Task <IActionResult> CreateComment([FromBody] CommentForCreationDto commentForCreationDto) { var commentToCreate = _mapper.Map <Comment>(commentForCreationDto); var userFromDb = await _userManager.GetUserAsync(this.User); if (userFromDb.Id != commentForCreationDto.CommentedById) { return(Unauthorized()); } commentToCreate.CommentedById = commentForCreationDto.CommentedById; commentToCreate.CreatedOn = DateTime.Now; commentToCreate.PostId = commentForCreationDto.PostId; _repository.Comment.CreateComment(commentToCreate); await _repository.SaveAsync(); var commentToReturn = _mapper.Map <CommentDto>(commentToCreate); //return CreatedAtAction("GetComment", new { postId, commentId = commentToReturn.Id }, commentToReturn); return(Ok(commentToReturn)); }
public async Task AddComment(CommentForCreationDto commentForCreationDto) { try { var comment = _mapper.Map <Comment>(commentForCreationDto); // wieksza kontrola nad tym co jest wprowadzane do bazy // id pobierane z tokenu // dodac required // model state i tu zrobic walidacje i zwracac w Jsonie odpowiedź _context.Comments.Add(comment); } catch { throw; } finally { await _context.SaveChangesAsync(); } }