public async Task <IActionResult> CreatePost(PostCreateDTO postCreateDTO) { if (ModelState.IsValid) { var user = await _userManager.FindByNameAsync(User.Identity.Name); var categories = await _categoryService.GetAllAsync(); var languages = await _languageService.GetAllAsync(); var category = categories.First(); var language = languages.First(); var post = _mapper.Map <Post>(postCreateDTO); post.UserId = user.Id; post.Created = DateTime.Now; post.CreatedBy = user.UserName; post.PostStatus = PostStatus.Posted; post.CategoryId = category.Id; post.LanguageId = language.Id; var newPost = await _postService.CreateAsync(post); if (postCreateDTO.Files != null) { List <Picture> pictures = AddFiles(postCreateDTO.Files, newPost.Id, user.UserName); foreach (var picture in pictures) { await _pictureService.CreateAsync(picture); } } var usersForNotification = await _userService.GetUsersForNitificationAsync(); if (usersForNotification != null) { var usersVoewDTO = _mapper.Map <List <UserViewDto> >(usersForNotification); var postViewDTO = _mapper.Map <PostViewDTO>(post); var userViewDTO = _mapper.Map <UserViewDto>(user); postViewDTO.UserViewDto = userViewDTO; var viewPostLink = Url.Action( "PostDetails", "Post", new { id = postViewDTO.Id }, protocol: HttpContext.Request.Scheme); var stringForm = await _razorViewToStringRenderer.RenderToStringAsync("Post/PostForEmailNotification", postViewDTO); await _automaticEmailNotificationService.SentAutomaticNotificationAsync(EmailNotificationSettings.subject, EmailNotificationSettings.CteateMessage(postViewDTO, stringForm, viewPostLink), usersVoewDTO); } return(RedirectToAction("Index", "Home")); } return(View(postCreateDTO)); }
public IActionResult CreatePost([FromBody] PostCreateDTO postCreateDTO) { if (postCreateDTO == null) { return(BadRequest()); } if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var post = this._mapper.Map <Post>(postCreateDTO); // Insert tag from list tag id PostUtilities.InsertTagsInPost(this._unitOfWork, post, postCreateDTO.TagsGuid); this._unitOfWork.PostRepository.Add(post); if (this._unitOfWork.SaveChanges() == 0) { ModelState.AddModelError("error", $"Some thing wrong"); return(StatusCode(StatusCodes.Status500InternalServerError, ModelState)); } return(CreatedAtRoute("GetPostById", new { id = post.Id }, postCreateDTO)); }
async public Task <ActionResult> storePost( [FromServices] IUserRepository userContext, [FromServices] IPostRepository postContext, [FromBody] PostCreateDTO model ) { var username = this.User.Identity.Name; var user = await userContext.findByUsername(username); if (user == null) { return(BadRequest("user not found")); } var post = new Post { title = model.title, description = model.description, UserId = user.id, date = new DateTime() }; postContext.AddAsync(post); post.User = user; return(Ok(post)); }
public async Task <IActionResult> CreatePost() { var category = await _categoryService.GetAllAsync(); var categoryVieDTOs = _mapper.Map <List <CategoryViewDTO> >(category); PostCreateDTO postCreateDTO = new PostCreateDTO(); postCreateDTO.CategoryViewDTOs = categoryVieDTOs; return(View(postCreateDTO)); }
//public static Expression<Func<User, UserDTO>> ToDTO() //{ // Expression<Func<User, UserDTO>> exp = // u => new UserDTO // { // Uemail = u.Uemail, // Ufname = u.Ufname, // Ulname = u.Ulname, // Created = u.Created, // UID = u.UID, // Uimg = u.Uimg // }; // return exp; //} public static Post PostCreateDTOToPost(PostCreateDTO p) { return(new Post { Created = DateTime.Now, AuthorId = Helper.IsNumeric(p.AuthorId)?p.AuthorId : -1, Content = p.Content, Deleted = false, Excerpt = p.Excerpt, Title = p.Title, Public = true }); }
public ActionResult <PostReadDTO> CreatePost(PostCreateDTO createPost) { var postmodel = _mapper.Map <Post>(createPost); _repository.CreatePost(postmodel); _repository.SaveChanges(); var postread = _mapper.Map <PostReadDTO>(postmodel); postread.PostedBy = _mapper.Map <UserReadDTO>(_repository.GetUserById(postread.UserId)); return(CreatedAtRoute(nameof(GetPostById), new { id = postread.PostID }, postread)); }
public async Task <ActionResult <string> > Create([Microsoft.AspNetCore.Mvc.FromBody] PostCreateDTO post) //PostOperationCreateData { await Task.Yield(); /*IOperation<PostCreateDTO, PostModelDTO, Dictionary<string, object>> operation = * new Operation<PostCreateDTO, PostModelDTO, Dictionary<string, object>>(logger); * * operation =*/ operation.Make <PostCreateOperationProtocol <PostCreateDTO, PostModelDTO, Dictionary <string, object> > >(post); // should pass http request IOperationAction <PostCreateDTO, PostModelDTO, Dictionary <string, object> > action = operation.Execute(); return(operation.Return(action)); }
public async Task <PostDTO> CreatePost(PostCreateDTO postDto) { var postEntity = _mapper.Map <Post>(postDto); _context.Posts.Add(postEntity); await _context.SaveChangesAsync(); var createdPost = await _context.Posts .Include(post => post.Author) .ThenInclude(author => author.Avatar) .FirstAsync(post => post.Id == postEntity.Id); var createdPostDTO = _mapper.Map <PostDTO>(createdPost); await _postHub.Clients.All.SendAsync("NewPost", createdPostDTO); return(createdPostDTO); }
public async Task <IActionResult> Create([FromBody] PostCreateDTO postCreateDTO) { var userId = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier).Value; if (userId == null) { return(Unauthorized()); } var post = new Post { UserId = userId, Description = postCreateDTO.Description }; this.repository.Insert(post); return(Ok()); }
public async Task <IActionResult> Posts(PostCreateDTO postCreateDTO) { int userid = Convert.ToInt32(User.Claims.Where(x => x.Type == "UserId").FirstOrDefault()?.Value); var post = Mapper.PostCreateDTOToPost(postCreateDTO); post.AuthorId = Convert.ToInt32(userid); _postRepo.Add(post); if (await _postRepo.SaveAll()) { //return Created("/",""); return(Ok(post)); } else { return(BadRequest()); } }
public void Check_If_Create_Post_Throws_Error_When_User_Is_Null() { // Arrange var postService = new PostService(dbContext, mapper); var postData = new PostCreateDTO() { CategoryId = 1, CreatedOn = DateTime.Now, Description = "Random Description", Title = "Random Description", TagId = 2 }; //Assert and Act Assert.ThrowsException <InvalidOperationException>(() => postService.CreatePost(postData, null)); }
/// <summary> /// Creates a new post by supplying the necessary properties. /// The functionality is used when creating a post request in /posts/Create. /// </summary> /// <param name="postInfo"> /// <param name="userName"></param> /// <returns></returns> public void CreatePost(PostCreateDTO postInfo, string userName) { using (DbContext) { var userId = DbContext.Users .Where(e => e.Email == userName) .Select(e => e.Id).First(); var newPost = Mapper.Map <Post>(postInfo); newPost.UserId = userId; if (newPost.TagId != 0 && newPost.CategoryId != 0) { DbContext.Posts.Add(newPost); DbContext.SaveChanges(); } } }
public IActionResult PutPost(int goalId, int postId, [FromBody] PostCreateDTO model) { try { var postToEdit = GoalsMockData.Current.Goals.SelectMany(g => g.Posts).FirstOrDefault(p => p.ID == postId); postToEdit.Header = model.Header; postToEdit.Content = model.Content; postToEdit.PictureID = model.PictureID; var goal = GoalsMockData.Current.Goals.FirstOrDefault(g => g.ID == goalId); return(Ok()); } catch (Exception) { _logger.LogError("Failed to execute PUT"); return(BadRequest()); } }
public IActionResult PatchPost(int goalId, int postId, [FromBody] JsonPatchDocument <PostCreateDTO> patchDoc) { if (patchDoc == null) { return(BadRequest()); } var goal = GoalsMockData.Current.Goals.FirstOrDefault(g => g.ID == goalId); if (goal == null) { return(NotFound()); } var post = goal.Posts.FirstOrDefault(p => p.ID == postId); if (post == null) { return(NotFound()); } var postToPatch = new PostCreateDTO() { Header = post.Header, Content = post.Content, PictureID = post.PictureID }; patchDoc.ApplyTo(postToPatch, ModelState); if (!ModelState.IsValid) { return(BadRequest(ModelState)); } post.Header = postToPatch.Header; post.Content = postToPatch.Content; post.PictureID = postToPatch.PictureID; return(NoContent()); }
public IActionResult CreatePost(int goalId, [FromBody] PostCreateDTO model) { if (model == null) { return(BadRequest("No Data has been passed")); } var goal = GoalsMockData.Current.Goals.FirstOrDefault(g => g.ID == goalId); if (goal == null) { return(NotFound("Associated Goal could not be found. GoalID :" + goalId.ToString())); } try { //DRGG: DEV only var maxId = GoalsMockData.Current.Goals.SelectMany(g => g.Posts).Max(p => p.ID); var PostToCreate = new PostDTO() { ID = ++maxId, GoaldID = goalId, Header = model.Header, Content = model.Content, PictureID = model.PictureID, DateCreated = DateTime.UtcNow }; goal.Posts.Add(PostToCreate); return(Created("GetPost" , PostToCreate)); } catch (Exception) { _logger.LogError("Failed to execute POST"); return(BadRequest()); } }
public async Task <IActionResult> CreateDraft(PostCreateDTO postCreateDTO) { if (ModelState.IsValid) { var user = await _userManager.FindByNameAsync(User.Identity.Name); var categories = await _categoryService.GetAllAsync(); var languages = await _languageService.GetAllAsync(); var category = categories.First(); var language = languages.First(); var post = _mapper.Map <Post>(postCreateDTO); post.UserId = user.Id; post.Created = DateTime.Now; post.CreatedBy = user.UserName; post.PostStatus = PostStatus.Draft; post.CategoryId = category.Id; post.LanguageId = language.Id; var newPost = await _postService.CreateAsync(post); if (postCreateDTO.Files != null) { List <Picture> pictures = AddFiles(postCreateDTO.Files, newPost.Id, user.UserName); foreach (var picture in pictures) { await _pictureService.CreateAsync(picture); } } return(RedirectToAction("Index", "Home")); } return(View(postCreateDTO)); }
public async Task <ActionResult <PostDTO> > CreatePost([FromBody] PostCreateDTO dto) { dto.AuthorId = this.GetUserIdFromToken(); return(Ok(await _postService.CreatePost(dto))); }