public async Task <Post> CreatePost(CreateViewModel createViewModel, ClaimsPrincipal claimsPrincipal) { Post post = createViewModel.Post; post.Author = await userManager.GetUserAsync(claimsPrincipal); post.CreatedOn = DateTime.Now; post.UpdatedOn = DateTime.Now; post = await postService.Add(post); string webRootPath = webHostEnvironment.WebRootPath; string pathToImage = $@"{webRootPath}\UserFiles\Posts\{post.Id}\HeaderImage.jpg"; EnsureFolder(pathToImage); if (createViewModel.HeaderImage is null) { return(post); } using (var fileStream = new FileStream(pathToImage, FileMode.Create)) { await createViewModel.HeaderImage.CopyToAsync(fileStream); } return(post); }
public void Integration_AddPost_ShouldBeOK() { Post post = ObjectMother.GetPost(); Post postReceived = _service.Add(post); var postVerify = _service.Get(post.Id); postVerify.Should().NotBeNull(); postVerify.Id.Should().Be(post.Id); }
public void PostService_ShouldAddIntoRepository() { _repository.Setup(x => x.Save(_post)).Returns(new Post { Id = 1 }); Post resultado = _service.Add(_post); _repository.Verify(x => x.Save(_post)); resultado.Id.Should().Be(1); }
public void TwitterIntegration_SendPost_ShouldBeOK() { Post post = ObjectMother.GetPost(); Post postReceived = _service.Add(post); postReceived.Id.Should().NotBe(null); Post postGet = _service.Get(postReceived.Id); postGet.Message.Should().Be(postReceived.Message); IEnumerable <Post> postTimeline = _service.GetAll(); postTimeline.First().Message.Should().Be(postReceived.Message); }
public async System.Threading.Tasks.Task <PartialViewResult> Post(PostViewModel data) { Post newPost = new Post(); newPost.Post_Status = 0; _viewModel = new PostViewModel(); FieldHelper.CopyNotNullValue(newPost, data); newPost.CreatedDate = DateTime.Now; if (data.Option == 0 && newPost.Id_Type == 8) { //post to fb toiec var IdPost = await _fbService.PostingToGroupFB(newPost.Content); newPost.Id_PostFB = IdPost.id; } _postService.Add(newPost); _postService.Save(); // string url = MaHoaMD5.Encrypt(newPost.Id + "#" + newPost.UpdatedDate); //Send notify ApplicationUser userPost = _service.GetUserById(newPost.Id_User); FieldHelper.CopyNotNullValue(PostViewModel, userPost); FieldHelper.CopyNotNullValue(PostViewModel, newPost); PostViewModel.TypeToString = _postTypeService.GetById(newPost.Id_Type).Name; PostVoteDetail vote = _postVoteDetailService.getVoteByIdUser(newPost.Id_User, newPost.Id); if (vote != null) { PostViewModel.Vote = vote.Vote; } //Send noti for all user register var userIDList = getUserIDListBasedOnType(newPost.Id_Type); foreach (var userID in userIDList) { var sendPostToUser = _service.GetUserById(userID); if (sendPostToUser.Id_Messenger != userPost.Id_Messenger && sendPostToUser.Id_Messenger != null && _eventService.IsFreeTime(sendPostToUser.Email)) { //Create json send............ FBPostNoti newNoti = new FBPostNoti(); newNoti.recipient.id = sendPostToUser.Id_Messenger; newNoti.message.attachment.payload.text = "```\r\n" + "💬 Bạn có một câu hỏi: " + "\r\n" + '"' + newPost.Content + '"' + "\r\n```"; NotiButton button = new NotiButton(); button.payload = "REPLAY_" + newPost.Id; newNoti.message.attachment.payload.buttons.Add(button); // ChatBotMessenger.sendRequest(JsonConvert.SerializeObject(newNoti)); } } return(PartialView("_Post", PostViewModel)); }
public void Verify_Give_Posts_When_GetPosts_Called() { //arrange var post = Helper.PostFake.GetDefaultPost(); var postAdded = _postService.Add(post); //post.Id = postAdded.Id; //act var posts = _postService.GetPosts().Result; //assert //Assert.Contains(post, posts); Assert.True(posts.Any()); }
public ActionResult Create(PostViewModels pmm, HttpPostedFileBase file) { Post p = new Post { Content = pmm.Content, DatePub = DateTime.Now, Dislike = 0, Like = 0, Picture = pmm.Picture }; ps.Add(p); ps.Commit(); return(RedirectToAction("Details")); }
public async Task <Post> CreatePost(CreateViewModel createViewModel, ClaimsPrincipal claimsPrincipal) { Post post = createViewModel.Post; post.Creator = await userManager.GetUserAsync(claimsPrincipal); post.CreatedOn = DateTime.Now; post.UpdatedOn = DateTime.Now; post = await postService.Add(post); CreateImageInCreate(createViewModel, post.Id, headerImage); CreateImageInCreate(createViewModel, post.Id, leftSideImage); return(post); }
public async Task <IActionResult> Create(NewPostViewModel newPostViewModel) { #region CREATING A NEW POST var userId = _userManager.GetUserId(User); var user = _userManager.FindByIdAsync(userId).Result; var post = _postBLL.BuildPost(newPostViewModel, user); await _postService.Add(post); #endregion #region INCREASING THE TOTAL POST AMOUNT IN FORUM var forum = _forumService.GetById(newPostViewModel.ForumId); forum.AmountTotalPost += 1; #endregion #region INSERTING NEW FORUM AMOUNT bool userFirstPostByForum = _forumService.CheckUserFirstPostByForum(userId.ToString(), newPostViewModel.ForumId); //If it is the first time that the user is creating a post related with the forum, then increase one user of the forum bcz a new user has just used the forum for the first time. if (userFirstPostByForum == true) { var model = _forumBLL.GetForumUserNewAmount(user, forum); await _forumService.AddNewUser(model); } #endregion await _forumService.Update(forum); return(RedirectToAction("Index", "Post", new { id = post.Id })); }
public async Task <IActionResult> Add([FromForm] CreatePostDto createPostDto) { try { string createdFilePath = _fileService.CreateLocalFile(createPostDto.PhotoFile, PostPhotosFolder); var user = await _userManager.GetUserAsync(User); if (user == null) { return(BadRequest()); } createPostDto.AuthorId = user.Id; CreatePostViewModel createPostViewModel = CustomMapper.GetCreatePostViewModel(createPostDto, createdFilePath); var result = await _postService.Add(createPostViewModel); if (result.IsValid) { return(Ok()); } return(BadRequest(result.Errors)); } catch (IOException) { } return(BadRequest()); }
public NewspaperMutation(IPostService postRepository, ICategoryService categoryService) { Name = "Newspaper_Mutation"; Field <PostType>( "addPost", arguments: new QueryArguments( new QueryArgument <NonNullGraphType <PostInputType> > { Name = "post", Description = "Bu bir post insert işlemidir (Acıklama yazılabilir)" }), resolve: context => { var post = context.GetArgument <Post>("post"); return(postRepository.Add(post)); } ); Field <CategoryType>( "addCategory", arguments: new QueryArguments( new QueryArgument <NonNullGraphType <CategoryInputType> > { Name = "category", Description = "Category added input" }), resolve: context => { var category = context.GetArgument <Category>("category"); return(categoryService.Add(category)); } ); }
public IActionResult Post([FromBody] Post newPost) { _postService.Add(newPost); // return a 201 Created status. This will also add a "location" header // with the URI of the new post. E.g., /api/posts/99, if the new is 99 return(CreatedAtAction("Get", new { Id = newPost.Id }, newPost)); }
public IActionResult Post([FromServices] IMapper mapper, [FromServices] IPostService service, [FromBody] PostDTO dto) { var post = mapper.Map <PostDTO, Post>(dto); service.Add(post); return(Ok(post)); }
public IHttpActionResult AddPost([FromBody] APIEditedPostModel editedPostModel) { object jsonObject; if (!ModelState.IsValid) { jsonObject = new { status = 500 }; return(Json(jsonObject)); } PostDTO postDTO = dataMapper.MapEditedPostModelToDTO(editedPostModel); if (string.IsNullOrWhiteSpace(postDTO.ThumbnailImageSrc)) { postDTO.ThumbnailImageSrc = APISettings.EMPTY_IMAGE; } bool addSuccessfully = postService.Add(postDTO); if (!addSuccessfully) { jsonObject = new { status = 500 }; } else { jsonObject = new { status = 200 }; } return(Json(jsonObject)); }
private async Task <ActionResult> AddOrEdit(PostEditViewModel model) { try { var record = await _postService.Get(model.Id); var isAdd = record == null; if (record == null) { record = PostRecord.Create(await _userService.GetUserById(_authenticationService.GetAuthenticatedUser().Identity)); } model.UpdateRecord(record, _categoryService); if (isAdd) { await _postService.Add(record); } return(this.Success()); } catch (ValidationException validationException) { return(this.Error(validationException.Message)); } }
public IActionResult Post(int blogId, [FromBody] PostModel postModel) { postModel.BlogId = blogId; var post = _postService.Add(postModel.ToDomainModel()); return(Ok(post)); }
[HttpPost("add")]//+++ public async Task <IActionResult> Add([FromForm] PostCreateDto postCreateDto) { //if (string.IsNullOrEmpty(postCreateDto.CategoryId)) return BadRequest("Kategori Seçmediniz."); if (postCreateDto.Image == null) { return(BadRequest("Resim Eklenmedi")); } string Id = Guid.NewGuid().ToString(); //resimlere guid Id şeklinde isim ataması yaptım. var resimler = Path.Combine(_environment.WebRootPath, "postImage"); //dizin bilgisi string imageName = $"{Id}.jpg"; //Db ye kaydedilecek olan resimlerin ismi var result = _postService.Add(postCreateDto, imageName); //post ekleme işlemi if (result.Success) { if (postCreateDto.Image.Length > 0) { using (var fileStream = new FileStream(Path.Combine(resimler, imageName), FileMode.Create)) { await postCreateDto.Image.CopyToAsync(fileStream); } } return(Ok(result.Message)); } return(BadRequest(result.Message)); }
public async Task <IActionResult> Create(NewTopicModel model) { if (ModelState.IsValid) { var userId = _userManager.GetUserId(User); var user = await _userManager.FindByIdAsync(userId); var topic = new Topic { Title = model.Title, Forum = _forumService.GetById(model.ForumId) }; var post = new Post { Content = model.Content, Created = DateTime.Now, User = user, Topic = topic, IsHead = true }; await _topicService.Add(topic); await _postService.Add(post); return(RedirectToAction("Topics", "Forum", new { id = model.ForumId })); } return(View(model)); }
public async Task <IActionResult> CreatePost(CreatePostViewModel viewModel) { var userId = GetUserIdFromClaims(User); if (userId == null) { return(Unauthorized(new UnauthorizedErrorViewModel())); } var post = Mapper.Map <Post>(viewModel); post.AuthorId = userId.Value; // Automatically like your own post. post.Likes = new List <Like> { new Like { UserId = userId.Value } }; post.Posted = DateTime.Now; _postService.Add(post); await _context.SaveChangesAsync(); return(CreatedAtRoute(new { id = post.Id }, null)); }
/// <summary> /// Creates a Post using the specified DTO. /// </summary> /// <param name="model"></param> /// <returns>Details of the Post if successful, otherwise a BadRequest with Detail.</returns> public IHttpActionResult CreatePost(CreatePostDto model) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (_userService.Get(model.AuthorId) == null) { return(BadRequest("User doesn't exist.")); } if (_topicService.Get(model.TopicId) == null) { return(BadRequest("Topic doesn't exist.")); } var post = _postService.Add(new Post { Id = Guid.NewGuid(), Title = model.Title, Description = model.Description, TopicId = model.TopicId, AuthorId = model.AuthorId, CreateDateTime = DateTime.Now }); return(Ok(Mapper.Map <BasicPostDto>(post))); }
public async Task <IActionResult> Create(PostCreateViewModel post) { post.Communities = GetCommunityDropdown(); try { if (!ModelState.IsValid) { return(View(post)); } var user = await _userManager.FindByNameAsync(User.Identity.Name); var newPost = new Post() { Title = post.Title, Body = post.Body, CommunityId = int.Parse(post.CommunityId), CreatedAt = DateTime.Now, CreatedBy = user.Id, }; _postService.Add(newPost); return(RedirectToAction("Index", "Home")); } catch (Exception ex) { return(View(post)); } }
public HttpResponseMessage Create(HttpRequestMessage request, PostViewModel postVm) { return(CreateHttpResponse(request, () => { HttpResponseMessage response = null; if (!ModelState.IsValid) { response = request.CreateResponse(HttpStatusCode.BadRequest, ModelState); } else { var newPost = new Post(); newPost.UpdatePost(postVm); newPost.CreatedDate = DateTime.Now; newPost.CategoryID = 1; newPost.Alias = "Don't know"; _postService.Add(newPost); _postService.Save(); var responseData = Mapper.Map <Post, PostViewModel>(newPost); response = request.CreateResponse(HttpStatusCode.Created, responseData); } return response; })); }
public async Task <IActionResult> Create(Post model, IFormFile image) { try { string path; if (image == null) { path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot\\images", "noimage.jpg"); model.ImagePath = "noimage.jpg"; } else { path = Path.GetFullPath("wwwroot\\images\\" + image.FileName); using (var stream = new FileStream(path, FileMode.Create)) { await image.CopyToAsync(stream); } model.ImagePath = image.FileName; } postService.Add(model); return(RedirectToAction("Index")); } catch (Exception) { return(View(model)); } }
public HttpResponseMessage Create(HttpRequestMessage request, PostViewModel model) { return(CreateHttpResponse(request, () => { HttpResponseMessage response = null; if (!ModelState.IsValid) { response = request.CreateResponse(HttpStatusCode.BadRequest, ModelState); } else { var newPostModel = new Post(); var identity = (ClaimsIdentity)User.Identity; IEnumerable <Claim> claims = identity.Claims; newPostModel.UpdatePost(model); newPostModel.CreatedBy = claims.FirstOrDefault().Value; newPostModel.CreatedDate = DateTime.Now; _postService.Add(newPostModel); _postService.SaveChanges(); Log log = new Log() { AppUserId = claims.FirstOrDefault().Value, Content = Notification.CREATE_POST, Created = DateTime.Now }; _logService.Create(log); _logService.Save(); var responseData = Mapper.Map <Post, PostViewModel>(newPostModel); response = request.CreateResponse(HttpStatusCode.OK, responseData); } return response; })); }
// GET: Posts/Create public IActionResult Create() { var categories = categoryService.GetAll(); ViewBag.Categories = new SelectList(categories, "Id", "CategoryName"); var userId = HttpContext.Session.GetString(UserConstants.USER_ID); var post = new PostViewModel { CreateDate = DateTime.Now, UserId = Int32.Parse(userId) }; postService.Add(post); postService.Save(); return(View(post)); }
public IActionResult CreateVirtualTrip([FromBody] VirtualTrip virtualTrip) { var identity = (ClaimsIdentity)User.Identity; var userId = identity.FindFirst("user_id").Value; virtualTrip.Id = ObjectId.GenerateNewId().ToString(); if (virtualTrip.Items == null) { virtualTrip.Items = new List <VirtualTripItem>(); } virtualTrip.Post.AuthorId = userId; virtualTrip.PostId = virtualTrip.Id; virtualTrip.Post.Id = virtualTrip.PostId; virtualTrip.Post.LikeCount = 0; virtualTrip.Post.CommentCount = 0; virtualTrip.Post.PubDate = DateTime.Now; virtualTrip.Post.IsActive = true; virtualTrip.Post.PostType = "VirtualTrip"; Post addedPost = _postService.Add(virtualTrip.Post); VirtualTrip addedVirtualTrip = _virtualTripService.Add(virtualTrip); return(Ok(addedVirtualTrip)); }
public JsonResult AddOrUpdate(PostsDTO model) { model.Status = true; var status = false; if (!ModelState.IsValid) { var errors = ModelState.Values.SelectMany(v => v.Errors); } if (ModelState.IsValid) { Post posts = new Post(); posts = AutoMapper.Mapper.Map <Post>(model); if (model.ID == 0) { status = PostService.Add(posts); } else { status = PostService.Update(posts); } PostService.Save(); } return(Json(status, JsonRequestBehavior.AllowGet)); }
public IActionResult AddPost(PostViewModel viewModel) { viewModel.UserId = User.FindFirstValue(ClaimTypes.NameIdentifier); var postId = postService.Add(viewModel); return(RedirectToAction("GetPost", new { id = postId })); }
public async Task <ActionResult> AddPost(AddPostDto model) { User currentUser = await GetCurrentUser(); if (model.UserId != currentUser.UserId) { return(BadRequest(new { message = "Authentication issue, please re-log." })); } Post post = new Post(_userService.GetById(model.UserId), model.Title, model.Text); try { _postService.Add(post); } catch (Exception e) { return(BadRequest(new { message = "Error in adding post: " + e.Message })); } PostDto postDto = new PostDto { UserDto = new UserDto(currentUser.UserId, currentUser.Email, currentUser.Username, currentUser.Firstname, currentUser.Lastname), DatePosted = post.DatePosted, PostId = post.PostId, Text = post.Text, Title = post.Title }; return(Ok(postDto)); }
public IActionResult Add(PostAddViewModel model) { if (ModelState.IsValid) { // Create new Post to add database var post = new Post { ImageUrl = UploadPostImage(model.Image), Title = model.Title, PostContent = model.PostContent, NumberOfClicks = 0, AddedDate = model.AddedDate, CategoryId = model.CategoryId, UserId = model.UserId }; _postService.Add(post); TempData["Message"] = "Yeni paylaşım başarıyla eklendi !"; TempData["MessageState"] = "warning"; return(RedirectToAction("Posts", "Admin")); } TempData["Message"] = "Paylaşım eklenirken bir hata oluştu !"; TempData["MessageState"] = "danger"; return(RedirectToAction("Posts", "Admin")); }