public void Execute(EditPostDto request) { var type = _context.Posts.Find(request.Id); if (type == null) { throw new EntityNotFoundException(request.Id, typeof(Post)); } var id = type.Id; var slike = new Picture { Id = request.Id, Name = request.Pictures, IdPost = id }; type.pictures.Add(slike); type.Id = request.Id; type.Name = request.Name; type.Description = request.Text; _context.SaveChanges(); }
public async Task <IActionResult> EditPost(int id, [FromBody] EditPostDto editPostDto) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value); var postFromRepo = await _repo.GetPost(id); if (currentUserId != postFromRepo.UserId) { return(Unauthorized()); } _mapper.Map(editPostDto, postFromRepo); if (await _repo.SaveAll()) { return(NoContent()); } throw new Exception($"Updating post {id} failed on save"); }
public IActionResult Edit([FromBody] EditPostDto model, Guid id) { if (model == null) { return(BadRequest()); } if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var userId = Guid.Parse(HttpContext.User.GetUserId()); var post = _repository.GetPostForUser(userId, id); if (post == null) { return(NotFound()); } else { _repository.EditPost(post, model.Description, model.Tags); } if (!_repository.Save()) { throw new Exception($"Updating post likes {id} failed on save."); } return(NoContent()); }
private async Task Save() { try { IsBusy = true; string[] tags = null; if (Tags != null) { tags = new string[Tags.Count]; Tags.CopyTo(tags, 0); } if (_photoStream != null) { byte[] byteImage; using (MemoryStream ms = new MemoryStream()) { _photoStream.CopyTo(ms); byteImage = ms.ToArray(); } CreatePostDto newPost = new CreatePostDto { Description = Description, ImageData = byteImage, Tags = tags }; await _postService.CreatePost(newPost, _runtimeContext.Token); await _navigationService.NavigateAsync <PostsViewModel>(); } //Edit if (_postId != default(Guid)) { EditPostDto newPost = new EditPostDto { Description = Description, Tags = tags }; await _postService.EditPost(newPost, _postId, _runtimeContext.Token); await _navigationService.NavigateAsync <PostsViewModel>(); } } catch (Exception ex) { await Application.Current.MainPage.DisplayAlert("Error", ex.Message, "OK"); } finally { IsBusy = false; } }
public IActionResult EditPost([FromBody] EditPostDto editPostDto) { if (editPostDto == null || editPostDto.PostId == 0) { return(Json(new { statusCode = ResponseStatus.ValidationError })); } Post post = facebookDataContext.UsersPosts.Include(x => x.Post).FirstOrDefault(x => x.PostId == editPostDto.PostId).Post; post.PostContent = editPostDto.PostContent; try { facebookDataContext.SaveChanges(); } catch { return(Json(new { statusCode = ResponseStatus.Error })); } return(Json(new { statusCode = ResponseStatus.Success })); }
public IActionResult UpdatePost([FromBody] EditPostDto vm) { var mappedPost = _mapper.Map <Post>(vm); var validation = _postService.ValidatePost(mappedPost); if (!validation.IsValid) { return(StatusCode(validation.StatusCodeAsIntegar, validation.Message)); } _postService.UpdatePost(mappedPost); return(Ok()); }
public async Task <bool> EditPost(EditPostDto post, Guid id, string token) { UriBuilder builder = new UriBuilder(_runtimeContext.BaseEndpoint) { Path = $"api/posts/{id}" }; if (await _authenticationService.IsTokenExpired(token)) { await _authenticationService.RenewSession(_runtimeContext.UserId, _runtimeContext.RefreshToken); } await _requestService.PutAsync <EditPostDto, string>(builder.Uri, post, token); return(await Task.FromResult(true)); }
public async Task EditPostServiceTest() { //Arrange string token = "Token"; Guid postId = new Guid("8e864dcc-5e0e-49c2-9f66-b3da6cee735f"); var expectedUri = new Uri($"{_runtimeContextMock.Object.BaseEndpoint}/api/posts/{postId}"); EditPostDto editPostDto = new EditPostDto { Description = "Test description", Tags = null }; //Act var result = await _postService.EditPost(editPostDto, postId, token); //Assert Assert.IsTrue(result); _requestServiceMock.Verify(x => x.PutAsync <EditPostDto, string>(expectedUri, editPostDto, token), Times.Once); }
public void Execute(EditPostDto request) { var post = _context.Posts.Include(p => p.Photo).FirstOrDefault(p => p.Id == request.Id); if (post == null) { throw new EntityNotFoundException(request.Id, typeof(Post)); } if (post.CreatedBy != _actor.Id && _actor.RoleType != RoleType.Administrator && _actor.RoleType != RoleType.Moderator) { throw new NotAllowedException(UseCase.getUseCase(this.Id), _actor, $"You can only edit posts created by you."); } _validator.ValidateAndThrow(request); _mapper.Map <EditPostDto, Post>(request, post); _context.SaveChanges(_actor.Id); }
public bool Edit(EditPostDto editInfo) { try { var article = this.context.Articles.Find(editInfo.Id); if (article == null) { return(false); } article.Title = editInfo.Title; article.Body = editInfo.Body; article.Summary = editInfo.Summary; this.context.Articles.Update(article); this.context.SaveChanges(); return(true); } catch { return(false); } }
public void Edit_ReturnsFalseIfNotFound() { // Arrange var context = this.ServiceProvider.GetRequiredService <WmipDbContext>(); var article = new Article { Id = 1, Title = "art1" }; context.Articles.Add(article); context.SaveChanges(); var articlesService = new ArticlesService(context); var editInfo = new EditPostDto() { Id = 2, Title = "aaaararar" }; // Act var result = articlesService.Edit(editInfo); //Assert Assert.False(result); }
public void Should_Throw_If_Post_To_Be_Edited_Does_Not_Exist() { // Setup // ReSharper disable once CollectionNeverUpdated.Local var posts = new List <Post>(); _postsDbSet.SetDbSetDataForAsync(posts.AsQueryable()); var editPostDto = new EditPostDto { Id = 1, MessageBody = "edited post", UserId = "user3", OrganizationId = 2 }; // Act // Assert var ex = Assert.ThrowsAsync <ValidationException>(async() => await _postService.EditPostAsync(editPostDto)); Assert.AreEqual(ErrorCodes.ContentDoesNotExist, ex.ErrorCode); }
public async Task <IActionResult> PutPost(string id, EditPostDto updatedPost) { if (id != updatedPost.PostId) { return(BadRequest()); } var userId = HttpContext.User.FindFirstValue(ClaimTypes.NameIdentifier); var post = await _context.Posts.FindAsync(id); if (userId != post.UserId && post.User.Role != Role.Admin) { return(Unauthorized()); } var topic = await _context.Topics.FirstAsync(topic => topic.Name == updatedPost.Topic); post.Title = updatedPost.Title; post.TopicId = topic.TopicId; post.Body = updatedPost.Body; post.UpdatedAt = DateTime.Now; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!PostExists(id)) { return(NotFound()); } else { throw; } } return(NoContent()); }
public void Should_Throw_If_User_Edits_Other_User_Post() { // Setup var wall = new Wall { Id = 1, OrganizationId = 2 }; var posts = new List <Post> { new Post { Id = 1, Wall = wall, MessageBody = "post", AuthorId = "user1" } }; _postsDbSet.SetDbSetDataForAsync(posts.AsQueryable()); var wallModerators = new List <WallModerator> { new WallModerator { WallId = wall.Id, UserId = "user2" } }; _wallModeratorsDbSet.SetDbSetDataForAsync(wallModerators.AsQueryable()); var editPostDto = new EditPostDto { Id = 1, MessageBody = "edited post", UserId = "user3", OrganizationId = 2 }; _permissionService.UserHasPermissionAsync(editPostDto, AdministrationPermissions.Post).Returns(false); // Act // Assert Assert.ThrowsAsync <UnauthorizedException>(async() => await _postService.EditPostAsync(editPostDto)); }
public void Edit_ChangesProperties() { // Arrange var context = this.ServiceProvider.GetRequiredService <WmipDbContext>(); var article = new Article { Id = 1, Title = "art1" }; context.Articles.Add(article); context.SaveChanges(); var articlesService = new ArticlesService(context); var editInfo = new EditPostDto() { Id = 1, Title = "aaaararar" }; // Act var result = articlesService.Edit(editInfo); //Assert Assert.True(result); Assert.Equal(editInfo.Title, context.Articles.First().Title); }
public IActionResult Put(int id, [FromForm] AddPost p) { var ext = Path.GetExtension(p.Image.FileName); if (!FileUpload.AllowedExtensions.Contains(ext)) { return(UnprocessableEntity("Image extension is not allowed.")); } try { var newFileName = Guid.NewGuid().ToString() + "_" + p.Image.FileName; var filePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "images", newFileName); p.Image.CopyTo(new FileStream(filePath, FileMode.Create)); var post = new EditPostDto { Id = p.Id, Name = p.Name, Text = p.Text, Pictures = newFileName }; _editPost.Execute(post); return(StatusCode(201)); } catch (EntityNotFoundException n) { return(NotFound()); } catch (Exception e) { return(StatusCode(500, "An error has occured.")); } }
public async Task EditPostAsync(EditPostDto editPostDto) { await _postDeleteLock.WaitAsync(); try { var post = await _postsDbSet .Include(x => x.Wall) .FirstOrDefaultAsync(x => x.Id == editPostDto.Id && x.Wall.OrganizationId == editPostDto.OrganizationId); if (post == null) { throw new ValidationException(ErrorCodes.ContentDoesNotExist, "Post not found"); } var isWallModerator = await _moderatorsDbSet.AnyAsync(x => x.UserId == editPostDto.UserId && x.WallId == post.WallId) || post.CreatedBy == editPostDto.UserId; var isAdministrator = await _permissionService.UserHasPermissionAsync(editPostDto, AdministrationPermissions.Post); if (!isAdministrator && !isWallModerator) { throw new UnauthorizedException(); } post.MessageBody = editPostDto.MessageBody; post.PictureId = editPostDto.PictureId; post.LastEdit = DateTime.UtcNow; await _uow.SaveChangesAsync(editPostDto.UserId); } finally { _postDeleteLock.Release(); } }
public Task <bool> EditPost(EditPostDto post, Guid id, string token) { //$"api/posts/{id}" throw new NotImplementedException(); }
public IHttpActionResult EditRentalPost(int id, EditPostDto editPostDto) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (editPostDto.AccommodationPictures.Count < 3) { return(BadRequest("Please upload at least 3 picture.")); } var address = editPostDto.Accommodation.Address; var ward = _context.Wards .Include(w => w.District.Province) .SingleOrDefault(w => w.Id == address.WardId); if (ward == null || ward.DistrictId != address.DistrictId || ward.District.ProvinceId != address.ProvinceId) { return(BadRequest("Address does not exist.")); } var rentalPostInDb = _context.AccommodationRentalPosts .Include(p => p.Status) .Include(p => p.Accommodation.Address) .Include(p => p.AccommodationPictures) .SingleOrDefault(p => p.Id == id); if (rentalPostInDb == null) { return(BadRequest("Post not found.")); } if (rentalPostInDb.Status.Name != RentalPostStatusName.PendingApproval) { return(BadRequest("Can not edit post. Post status: " + rentalPostInDb.Status.Name)); } rentalPostInDb.Title = editPostDto.Title; rentalPostInDb.Content = editPostDto.Content; rentalPostInDb.AccommodationPictures .ToList() .ForEach(p => _context.AccommodationPictures.Remove(p)); foreach (var accommodationPictureDto in editPostDto.AccommodationPictures) { _context.AccommodationPictures .Add(new AccommodationPicture() { PictureLink = accommodationPictureDto.PictureLink, AccommodationRentalPostId = id }); } editPostDto.Accommodation.StatusId = rentalPostInDb.Accommodation.StatusId; editPostDto.Accommodation.AddressId = rentalPostInDb.Accommodation.AddressId; editPostDto.Accommodation.OwnerId = rentalPostInDb.Accommodation.OwnerId; rentalPostInDb.Accommodation = Mapper.Map <AccommodationDto, Accommodation>(editPostDto.Accommodation); if (User.IsInRole(RoleName.Admin)) { rentalPostInDb.StatusId = _context.RentalPostStatuses.Single(s => s.Name == RentalPostStatusName.Approved).Id; } _context.SaveChanges(); return(Ok("Post has been edited.")); }
public async Task <ActionResult <PostDto> > Put([FromBody] EditPostDto post, [FromRoute] string id) { var updatedPost = await _mediator.Send(new EditPostCommand(id, post)); return(Ok(updatedPost)); }
public IActionResult Put(int id, [FromBody] EditPostDto request, [FromServices] IEditPostCommand command) { request.Id = id; _executor.ExecuteCommand(command, request); return(StatusCode(StatusCodes.Status204NoContent)); }
public IActionResult editPost([FromBody] EditPostDto T, int id) { return(Ok(socialMediaRepository.EditPost(T, id, _env))); }