private async void OnNewComment() { if (ActiveUser.IsActive == true && !String.IsNullOrWhiteSpace(NewComment)) { CreateCommentDTO createCommentDTO = new CreateCommentDTO() { Text = NewComment, CardId = cardId }; BasicCommentDTO basicCommentDTO = await CommentService.CreateComment(ActiveUser.Instance.LoggedUser.Token, createCommentDTO); if (basicCommentDTO != null) { var comment = new ReadComment(basicCommentDTO); Comments.Add(comment); NewComment = ""; } else { ShowMessageBox(null, "Error creating list."); } } else { ShowMessageBox(null, "Error getting user."); } }
public static async Task <BasicCommentDTO> CreateComment(string accessToken, CreateCommentDTO createCommentDTO) { using (HttpClient client = new HttpClient()) { try { string json = JsonConvert.SerializeObject(createCommentDTO); var buffer = System.Text.Encoding.UTF8.GetBytes(json); var byteContent = new ByteArrayContent(buffer); byteContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); client.DefaultRequestHeaders.Add("Authorization", accessToken); var response = await client.PostAsync("http://localhost:52816/api/Comment/", byteContent); if (response.StatusCode == System.Net.HttpStatusCode.OK) { var jsonString = await response.Content.ReadAsStringAsync(); var comment = JsonConvert.DeserializeObject <BasicCommentDTO>(jsonString); return(comment); } else { return(null); } } catch (Exception e) { Debug.WriteLine(e.Message); return(null); } } }
public BasicCommentDTO InsertComment(string username, CreateCommentDTO dto) { Comment comment = CreateCommentDTO.FromDTO(dto); BasicCommentDTO commentDTO = null; using (UnitOfWork uw = new UnitOfWork()) { Card card = uw.CardRepository.GetById(dto.CardId); User user = uw.UserRepository.GetUserByUsername(username); if (card != null && user != null) { comment.Card = card; comment.User = user; uw.CommentRepository.Insert(comment); if (uw.Save()) { NotificationService notif = new NotificationService(); notif.CreateChangeNotification(new CreateNotificationDTO() { CardId = dto.CardId, UserId = user.UserId, NotificationType = NotificationType.Change }); commentDTO = new BasicCommentDTO(comment); RabbitMQService.PublishToExchange(card.List.Board.ExchangeName, new MessageContext(new CommentMessageStrategy(commentDTO, username))); BoardNotificationService.ChangeBoardNotifications(card.List.Board.BoardId); } } } return(commentDTO); }
public IActionResult AddCommentToMeanOfTransport(Guid idMeanOfTransport, [FromBody] CreateCommentDTO comment) { if (idMeanOfTransport.Equals(Guid.Empty)) { return(BadRequest()); } if (comment == null) { return(BadRequest()); } var meanOfTransport = _repository.GetById(idMeanOfTransport); if (meanOfTransport == null) { return(NotFound()); } var com = Comment.Create(meanOfTransport.Id, comment.UserId, DateTime.Now, comment.Text, 0, 0); _commentRepository.Add(com); return(NoContent()); }
private Comment _createComment(CreateCommentDTO dto, User user) { var comment = new Comment(); comment.Text = dto.Text; comment.User = user; return(comment); }
public CommentDetailDTO Create(CreateCommentDTO dto) { var comment = _commentMapper.ToComment(dto); _pizzaService.AddComment(dto.PizzaId, comment); _context.Comment.Add(comment); _context.SaveChanges(); return(_commentMapper.ToCommentDetail(comment)); }
public async Task <IActionResult> AddComment(CreateCommentDTO createCommentDto) { var email = GetEmailFromHttpContextAsync(); await _commentService.AddComment(createCommentDto, email); _logger.LogInfo($"Add comment for t-shirt with id: {createCommentDto.ShirtId}."); return(Ok()); }
public IActionResult Post([FromBody] CreateCommentDTO createCommentDTO) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var commentDetail = _commentService.Create(createCommentDTO); return(StatusCode(201, commentDetail)); }
public async Task <MessageModel <Commment> > Post([FromBody] CreateCommentDTO commment) { var model = _mapper.Map <Commment>(commment); var result = await _service.Add(model); return(new MessageModel <Commment>() { response = result }); }
public Comment ToComment(CreateCommentDTO dto) { return(new Comment() { Id = Guid.NewGuid(), Text = dto.Text, Score = dto.Score, Date = DateTime.Now, User = _userService.FindById(dto.UserId) }); }
public void CreateComment(CreateCommentDTO comment) { var newComment = new Comment() { Name = comment.Name, Text = comment.Text, Bike = GetBikeById(comment.BikeId) }; _context.Comments.Add(newComment); _context.SaveChanges(); }
public async Task <ActionResult> PostComment([FromBody] CreateCommentDTO createComment) { var comment = _mapper.Map <Comment>(createComment); _context.Add(comment); await _context.SaveChangesAsync(); var commentDTO = _mapper.Map <CommentDTO>(comment); return(CreatedAtAction("GetComment", new { id = commentDTO.Id }, commentDTO)); }
public async Task CreateAsync(CreateCommentDTO comment) { var commentEntity = new Comment { CommentatorId = comment.CommentatorId, CommentedUserId = comment.CommentedUserId, Content = comment.Content, }; await this.commentRepository.AddAsync(commentEntity); await this.commentRepository.SaveChangesAsync(); }
public async Task <ActionResult <CreateCommentDTO> > CreateComment(CreateCommentDTO commentDTO) { if (!ModelState.IsValid) { return(this.NoContent()); } _logger.LogInfo("Creating a new comment..."); await this._commentService.CreateComment(commentDTO); _logger.LogInfo($"Comment with content {commentDTO.Comment} successfully created."); return(this.CreatedAtAction("CreateComment", new { text = commentDTO.Comment })); }
public async Task <IActionResult> PutComment(int Id, CreateCommentDTO updateCommentDTO) { var commentDB = await _context.Comments.FirstOrDefaultAsync(x => x.Id == Id); if (commentDB == null) { return(NotFound()); } commentDB = _mapper.Map(updateCommentDTO, commentDB); await _context.SaveChangesAsync(); return(NoContent()); }
public IActionResult CreateComment(/*[FromForm]*/ CreateCommentDTO comment) { if (ModelState.IsValid) { try { _commentService.CreateComment(comment); } catch (Exception e) { return(BadRequest(e.Message)); } return(Ok()); } return(BadRequest("Ошибка входных данных")); }
public async Task AddComment(CreateCommentDTO createCommentDTO, string email) { var user = await _userManager.FindByEmailAsync(email); var commentDTO = new CommentDTO { AuthorName = user.DisplayName, ShirtId = createCommentDTO.ShirtId, Text = createCommentDTO.Text }; var comment = _mapper.Map <Comment>(commentDTO); _repositoryManager.Comment.CreateComment(comment); await _repositoryManager.SaveAsync(); await _hub.Clients.All.SendAsync("Add", commentDTO); }
public ReadCommentDTO CreateComment(CreateCommentDTO dto) { // buscar el user var user = _context.User.Find(dto.UserId); // buscar la pizza var pizza = _context.Pizza.Find(dto.PizzaId); // crear comentario var comment = _createComment(dto, user); // añadir comentario a la pizza //guardar el comentario _context.Comment.Add(comment); // guardar y dispose del context _context.SaveChanges(); _context.Dispose(); // devolver readCommentDTO return(_createReadCommentDTO(comment)); }
public async Task <OperationResult <CommentInfoDTO> > CreateCommentAsync(CreateCommentDTO model) { try { var operRes = new OperationResult <CommentInfoDTO>(true); var user = await _userManager.FindByIdAsync(model.UserId.ToString()); if (user == null) { operRes.AddErrorMessage("UserId", $"Не удалось найти пользователя с id = {model.UserId}"); } using (var connection = _factory.CreateConnection()) { connection.ConnectionString = _connectionString; await connection.OpenAsync(); var pic = await uow.Pictures.FindByIdAsync(connection, model.PictureId); if (pic == null) { operRes.AddErrorMessage("PictureId", $"Не удалось найти картину с id = {model.PictureId}"); } if (!operRes.Succeeded) { return(operRes); } var entity = _mapper.Map <Comment>(model); entity.DateOfCreation = DateTime.Now; entity = await uow.Comments.CreateAsync(connection, entity); var result = _mapper.Map <CommentInfoDTO>(entity); result.UserName = user.UserName; result.Avatar = user.Avatar; operRes.Results.Add(result); return(operRes); } } catch (Exception ex) { throw new DatabaseException("Не удалось добавить данные", ex.Message); } }
public void CreateCommentForBlog_WithCorrectData_ShouldCreateCommentSuccessfully() { string errorMessagePrefix = "CommentService CreateCommentForBlog() method does not work properly."; var commentRepo = new Mock <IRepository <Comment> >(); var userRepo = new Mock <IRepository <ApplicationUser> >(); var blogRepo = new Mock <IRepository <Blog> >(); var activityRepo = new Mock <IRepository <UserActivity> >(); commentRepo.Setup(x => x.All()).Returns(this.GetTestData().AsQueryable()); userRepo.Setup(x => x.All()).Returns(new List <ApplicationUser>() { new ApplicationUser() { Id = "1", Activity = new List <UserActivity>() } }.AsQueryable); blogRepo.Setup(x => x.All()).Returns(new List <Blog>() { new Blog() { Id = 1 } }.AsQueryable); this._commentService = new CommentService(commentRepo.Object, null, userRepo.Object, null, blogRepo.Object, activityRepo.Object); var commentDto = new CreateCommentDTO() { Action = "blog", Comment = "Something", Id = 1, UserId = "1" }; var isCompleted = this._commentService.CreateComment(commentDto, true).IsCompletedSuccessfully; Assert.True(isCompleted, errorMessagePrefix); }
public async Task <IActionResult> Add(CreateCommentInputModel comment) { var commentatorId = this.User.FindFirst(ClaimTypes.NameIdentifier).Value; var commentedUserId = this.usersService.GetByUsername <UsersListItemViewModel>(comment.CommentedUserUserName).Id; var sanitizedCommentContent = this.htmlSanitizer.Sanitize(comment.Content); if (sanitizedCommentContent.Length < 5) { return(this.BadRequest()); } var commentDTO = new CreateCommentDTO { CommentatorId = commentatorId, CommentedUserId = commentedUserId, Content = sanitizedCommentContent, }; await this.commentsService.CreateAsync(commentDTO); return(this.Ok()); }
public async Task CreateComment_WithIncorrectUserId_ShouldThrowInvalidOperationException() { var userRepo = new Mock <IRepository <ApplicationUser> >(); userRepo.Setup(x => x.All()).Returns(new List <ApplicationUser>() { new ApplicationUser() { Id = "1" } }.AsQueryable); this._commentService = new CommentService(null, null, userRepo.Object, null, null, null); var commentDto = new CreateCommentDTO() { Action = "hero", Comment = "Something", Id = 1, UserId = "-1" }; await Assert.ThrowsAsync <InvalidOperationException>(() => this._commentService.CreateComment(commentDto)); }
public async Task CreateComment_WithIncorrectData_ShouldThrowInvalidOperationException(string action, string comment, string userId, int heroId) { var commentRepo = new Mock <IRepository <Comment> >(); var userRepo = new Mock <IRepository <ApplicationUser> >(); var heroRepo = new Mock <IRepository <Hero> >(); var activityRepo = new Mock <IRepository <UserActivity> >(); commentRepo.Setup(x => x.All()).Returns(this.GetTestData().AsQueryable()); userRepo.Setup(x => x.All()).Returns(new List <ApplicationUser>() { new ApplicationUser() { Id = "1", Activity = new List <UserActivity>() } }.AsQueryable); heroRepo.Setup(x => x.All()).Returns(new List <Hero>() { new Hero() { Id = 1 } }.AsQueryable); this._commentService = new CommentService(commentRepo.Object, heroRepo.Object, userRepo.Object, null, null, activityRepo.Object); var commentDto = new CreateCommentDTO() { Action = action, Comment = comment, Id = heroId, UserId = userId }; await Assert.ThrowsAsync <InvalidOperationException>(() => this._commentService.CreateComment(commentDto)); }
public async Task <IActionResult> CreateComment([FromBody] CreateCommentDTO model) { var res = await _service.CreateCommentAsync(model); return(this.GetResult(res, true)); }
public Task <HttpResponseMessage> CreateComment(CreateCommentDTO model) { return(_client.PostAsJsonAsync("/api/Comment", model)); }
public async Task CreateComment(CreateCommentDTO commentDto, bool skipMethodForTest = false) { var userObj = this._userRepository.All().Single(x => x.Id == commentDto.UserId); if (string.IsNullOrEmpty(commentDto.Action) || string.IsNullOrEmpty(commentDto.Comment) || string.IsNullOrEmpty(commentDto.UserId)) { throw new InvalidOperationException("Invalid data."); } if (commentDto.Action.ToLower() == "hero") { var heroObj = this._heroRepository.All().Single(x => x.Id == commentDto.Id); var commentObj = new Comment { Text = commentDto.Comment, UserName = userObj.UserName, ProfileImage = userObj.ProfileImage, HeroId = heroObj.Id, UserId = userObj.Id }; var activity = new UserActivity { Action = $"Added comment to hero '{heroObj.Name}'", RegisteredOn = DateTime.Now, UserId = userObj.Id, User = userObj }; if (!skipMethodForTest) { await _hubContext.Clients.All.BroadcastComment(commentObj); } heroObj.Comments.Add(commentObj); userObj.Comments.Add(commentObj); await this._userActivityRepository.AddAsync(activity); userObj.Activity.Add(activity); await this._heroRepository.SaveChangesAsync(); } else { var blogObj = this._blogRepository.All().Single(x => x.Id == commentDto.Id); var commentObj = new Comment { Text = commentDto.Comment, UserName = userObj.UserName, ProfileImage = userObj.ProfileImage, BlogId = blogObj.Id, UserId = userObj.Id }; var activity = new UserActivity { Action = $"Added comment to post with title '{blogObj.Title}'", RegisteredOn = DateTime.Now, UserId = userObj.Id, User = userObj }; if (!skipMethodForTest) { await _hubContext.Clients.All.BroadcastComment(commentObj); } blogObj.Comments.Add(commentObj); userObj.Comments.Add(commentObj); await this._userActivityRepository.AddAsync(activity); userObj.Activity.Add(activity); await this._blogRepository.SaveChangesAsync(); } }
// POST: api/Comment public BasicCommentDTO Post([FromBody] CreateCommentDTO comment) { return(service.InsertComment(User.Identity.Name, comment)); }