public async Task UpdatePostAsync(UpdatePostDTO dto) { var post = await FindPostAsync(dto.Post.Id); var updatedPost = _mapper.Map <Post>(dto.Post); //Update the values for the post _mapper.Map(updatedPost, post); //Update the users set to the given post. foreach (var username in dto.UserNames) { var updateUserPostsDto = new UpdateUserPostsDTO { UserName = username, PostIds = new int[] { post.Id } }; await SetUserPostsAsync(updateUserPostsDto); } //Update the roles given to the post. var modDto = new ModifyPostRolesDTO() { Id = dto.Post.Id, Roles = dto.Roles }; await SetPostRolesAsync(modDto); if (!await _postRepository.SaveAll()) { throw new ApplicationException("Could not update the given post."); } }
public async Task <UserToReturnDTO> SetUserPostsAsync(UpdateUserPostsDTO dto) { var user = await _userManager.FindByNameAsync(dto.UserName); if (user == null) { throw new ArgumentNullException(null, "Could not find a user with the given username."); } // Clear current post membership: var currentPosts = await GetUserPostsAsync(user.Id); foreach (var post in currentPosts) { post.Users .Remove(post.Users .FirstOrDefault(p => p.UserId == user.Id )); } if (currentPosts.Count() != 0) { if (!await _postRepository.SaveAll()) { throw new ApplicationException("Something went wrong clearing the posts from the given user."); } } // Add the user to the new posts: foreach (var postId in dto.PostIds) { var newPost = await FindPostAsync(postId); newPost.Users.Add(new UserPost { UserId = user.Id, PostId = postId }); } if (!await _postRepository.SaveAll()) { throw new ApplicationException("Something went wrong clearing the posts from the given user."); } return(await RefreshUserPostRolesAsync(user.Id)); }
public async Task <UserToReturnDTO> ClearUserFromPosts(string userName) { var user = await _userManager.FindByNameAsync(userName); if (user == null) { throw new ApplicationException("Could not find a user with the given username."); } var dto = new UpdateUserPostsDTO { UserName = userName, PostIds = new int[] {} }; await SetUserPostsAsync(dto); var userToReturn = _mapper.Map <UserToReturnDTO>(user); return(userToReturn); }
public async Task <IActionResult> AddUserToPosts(UpdateUserPostsDTO dto) { var updatedUser = await _postService.SetUserPostsAsync(dto); return(Ok(updatedUser)); }