public void AddPost(PostDTO post) { var _post = new Post { Title = post.Title, Content = post.Content, Created = DateTime.UtcNow, AuthorName = post.AuthorName, }; dbContext.Posts.Add(_post); dbContext.SaveChanges(); }
private PostDTO MapViewModelWithDTO(PostViewModel post) { Mapper.Initialize(cfg => { cfg.CreateMap <PostViewModel, PostDTO>() .ForMember(p => p.Department, opt => opt.Ignore()); cfg.CreateMap <EmployeeViewModel, EmployeeDTO>() .ForMember(e => e.BusinessTrips, opt => opt.Ignore()) .ForMember(e => e.Post, opt => opt.Ignore()); }); PostDTO pDto = Mapper.Map <PostViewModel, PostDTO>(post); return(pDto); }
public IHttpActionResult DeletePost(int postid) { try { PostDTO postDTO = forumService.GetPostById(postid); forumService.DeletePost(postid); return(Ok()); } catch (ValidationException ex) { return(NotFound()); } }
public async Task <IActionResult> GetComments(PostDTO postDTO) { var result = await service.ShowComments(postDTO.Id); if (!result.Succedeed) { System.Console.WriteLine(result.Message); return(BadRequest(result.Message)); } System.Console.WriteLine("getting comments success"); return(new OkObjectResult(result.Object)); }
public void ForumServiceAddPost_AddNewPost_PostShouldEquals() { PostDTO post = new PostDTO { ID = 4, CategoryID = 1, Title = "Post3", Body = "Post3_Category1", CreatorName = "Admin" }; var service = new ForumService(uowt); service.AddPost(post); Assert.AreEqual(post.Title, uowt.Posts.GetById(post.ID).Title); Assert.AreEqual(post.Body, uowt.Posts.GetById(post.ID).Body); }
public void ForumServiceUpdatePost_UpdateExistPost_ShouldEqulas() { PostDTO post = new PostDTO { CategoryID = 1, Title = "Post1", Body = "Post1_Category1_Update", ID = 1, CreatorName = "Admin" }; var service = new ForumService(uowt); service.UpdatePost(post); Assert.AreEqual(post.Title, uowt.Posts.GetById(post.ID).Title); Assert.AreEqual(post.Body, uowt.Posts.GetById(post.ID).Body); }
public ActionResult Update(PostDTO data) { Post post = _postRepo.GetById(data.Id); post.Header = data.Header; post.Content = data.Content; post.CategoryId = data.CategoryId; post.AppUserId = data.AppUserId; post.Status = Status.Active; post.UpdateDate = DateTime.Now; _postRepo.Update(post); return(Redirect("/Admin/Post/List")); }
/// <summary> /// Return post with specific id /// </summary> /// <param name="id">Id</param> /// <returns>Post with specific id</returns> PostDTO IPostService.GetPost(int id) { Post post = Db.PostManager.Get(id); if (post == null) { return(null); } PostDTO postDTO = Mapper.Map <Post, PostDTO>(post); postDTO.AuthorName = SetAuthorName(post.UserId); return(postDTO); }
public async Task <OperationDetails> UpdatePostAsync(PostDTO postDTO) { var post = await _database.postRepository.GetByIdAsync(postDTO.PostId); if (post == null) { return(new OperationDetails(false, "User is not found!", "Update")); } _database.postRepository.Update(_mapper.Map(postDTO, _mapper.Map <Post>(post))); await _database.SaveAsync(); return(new OperationDetails(true, "User is UPDATED", "Update")); }
private async Task <ActionResult> GetViewAsync(int?id, string viewName) { try { PostDTO pDto = await _postService.FindByIdAsync(id); PostViewModel p = MapDTOWithViewModel(pDto); return(View(viewName, p)); } catch (ValidationException ex) { _logger.Warn(ex.Message); return(View("Error", new string[] { ex.Message })); } }
public IActionResult DeletePost(Guid ownerId, Guid id) { PostDTO pdto = _postService.GetPost(ownerId, id); if (pdto == null) { return(NotFound()); } _postService.DeletePost(pdto); return(NoContent()); }
public async Task <IActionResult> DeletePost(PostDTO postDTO) { var result = await service.DeletePost(postDTO.Id); if (!result.Succedeed) { System.Console.WriteLine(result.Message); return(BadRequest(result.Message)); } System.Console.WriteLine(result.Message); return(new OkObjectResult(new { Message = result.Message })); }
public async Task <IActionResult> Create(PostDTO postDTO) { System.Console.WriteLine("trying to create post"); var result = await service.CreatePost(postDTO); if (!result.Succedeed) { System.Console.WriteLine(result.Message); return(BadRequest(result.Message)); } System.Console.WriteLine("post creating success"); return(new OkObjectResult(result.Object)); }
public static void MapPostFromPostDto(ref Post post, ref PostDTO postDTO) { post.Id = postDTO.Id; post.IsDeleted = postDTO.IsDeleted; post.Title = postDTO.Title; post.Text = postDTO.Text; post.Rate = postDTO.Rate; post.BlogId = postDTO.BlogId; post.UserCreatorId = postDTO.UserCreatorId; post.LastUserModifierId = postDTO.LastUserModifierId; post.DataCreated = postDTO.DateCreated; post.LastDateModified = postDTO.LastDateModified; }
public async Task <IActionResult> SavePost(PostDTO postDTO) { var post = _mapper.Map <Post>(postDTO); await _postService.SavePost(post); postDTO = _mapper.Map <PostDTO>(post); var response = new ApiResponse <PostDTO>(postDTO); return(Ok(response)); }
/// <summary> /// The GetPost /// </summary> /// <param name="id">The id<see cref="object"/></param> /// <param name="transaction">The transaction<see cref="TransactionalInformation"/></param> /// <returns>The <see cref="PostDTO"/></returns> public PostDTO GetPost(object id, out TransactionalInformation transaction) { transaction = new TransactionalInformation(); PostDTO postDto = new PostDTO(); try { _dataService.CreateSession(); var param = new DynamicParameters(); param.Add("@ID", id); var item = _dataService.PostRepository.GetById(PostScript.GetById, param, CommandType.Text); postDto.ID = item.ID; postDto.Name = item.Name; postDto.Alias = item.Alias; postDto.CategoryID = item.CategoryID; postDto.Image = item.Image; postDto.Description = item.Description; postDto.Content = item.Content; postDto.HomeFlag = item.HomeFlag; postDto.HotFlag = item.HotFlag; postDto.ViewCount = item.ViewCount; postDto.CreatedDate = item.CreatedDate; postDto.CreatedBy = item.CreatedBy; postDto.UpdatedDate = item.UpdatedDate; postDto.UpdatedBy = item.UpdatedBy; postDto.MetaKeyword = item.MetaKeyword; postDto.MetaDescription = item.Description; postDto.Status = item.Status; postDto.CategoryName = item.CategoryName; transaction.ReturnStatus = true; transaction.ReturnMessage.Add("successfully."); } catch (Exception ex) { string errorMessage = ex.Message; transaction.ReturnMessage.Add(errorMessage); transaction.ReturnStatus = false; } finally { _dataService.CloseSession(); } return(postDto); }
public ActionResult AddPost(PostDTO model) { if (model.PostImage[0] == null) { ViewBag.ProcessState = General.Messages.ImageMissing; } else if (ModelState.IsValid) { foreach (var item in model.PostImage) { Bitmap image = new Bitmap(item.InputStream); string ext = Path.GetExtension(item.FileName); if (ext != ".png" && ext != ".jpeg" && ext != ".jpg") { ViewBag.ProcessState = General.Messages.ExtensionError; model.Categories = CategoryBLL.GetCategoriesForDropdown(); return(View(model)); } } List <PostImageDTO> imagelist = new List <PostImageDTO>(); foreach (var postedfile in model.PostImage) { Bitmap image = new Bitmap(postedfile.InputStream); Bitmap resizeimage = new Bitmap(image, 750, 422); string filename = ""; string uniqueNumber = Guid.NewGuid().ToString(); filename = uniqueNumber + postedfile.FileName; resizeimage.Save(Server.MapPath("~/Areas/Admin/Content/PostImage/" + filename)); PostImageDTO dto = new PostImageDTO(); dto.ImagePath = filename; imagelist.Add(dto); } model.PostImages = imagelist; if (bll.AddPost(model)) { ViewBag.ProcessState = General.Messages.AddSuccess; ModelState.Clear(); model = new PostDTO(); } else { ViewBag.ProcessState = General.Messages.GeneralError; } } else { ViewBag.ProcessState = General.Messages.EmptyArea; } model.Categories = CategoryBLL.GetCategoriesForDropdown(); return(View(model)); }
public void UpdatePost_UpdateNullPost_PostShouldNotBeUpdated() { // Arrange PostDTO post = null; int countBefore = unitOfWork.PostManager.Get().Count(); // Act bool result = service.UpdatePost(post); int countAfter = unitOfWork.PostManager.Get().Count(); // Assert Assert.IsFalse(result); Assert.AreEqual(countBefore, countAfter); }
public PostDTO Get(Guid id) { Post postObj = _unitofWork.Post.GetById(id); try { PostDTO model = _mapper.Map <PostDTO>(postObj); return(model); } catch (Exception) { throw; } }
public ActionResult UpdatePost(PostDTO model) { IEnumerable <SelectListItem> selectList = CategoryBLL.GetCategoriesForDropdown(); if (ModelState.IsValid) { if (model.PostImage[0] != null) { foreach (var item in model.PostImage) { string ext = Path.GetExtension(item.FileName); if (ext != ".png" && ext != ".jpg" && ext != ".jpeg") { ViewBag.ProcessState = General.Messages.ExtensionError; model.Categories = CategoryBLL.GetCategoriesForDropdown(); return(View(model)); } } List <PostImageDTO> imageList = new List <PostImageDTO>(); foreach (HttpPostedFileBase postedFile in model.PostImage) { Bitmap image = new Bitmap(postedFile.InputStream); Bitmap resizedImage = new Bitmap(image, 750, 422); string uniqueNumber = Guid.NewGuid().ToString(); string fileName = uniqueNumber + postedFile.FileName; resizedImage.Save(Server.MapPath("~/Areas/Admin/Content/PostImages/" + fileName)); PostImageDTO dto = new PostImageDTO(); dto.ImagePath = fileName; imageList.Add(dto); } model.PostImages = imageList; if (bll.UpdatePost(model)) { ViewBag.ProcessState = General.Messages.UpdateSuccess; } else { ViewBag.ProcessState = General.Messages.GeneralError; } } } else { ViewBag.ProcessState = General.Messages.EmptyArea; } model = bll.GetPostWithID(model.ID); model.Categories = selectList; model.isUpdated = true; return(View(model)); }
public JsonResult ReplyPost(Int32 postId, String content) { Int32 accountId = Session["AccountDTO"] != null ? (Session["AccountDTO"] as AccountDTO).Id : -1; PostService.ReplyPost(accountId, postId, content); PostDTO post = PostService.GetById(postId); return(Json(new JsonMessageDTO() { Success = true, Data = post }, JsonRequestBehavior.AllowGet)); }
public override async Task FindByIdAsync_IdEqualTo2_ReturnsObjectWithIdEqualTo2() { Mock <IUnitOfWork> mock = new Mock <IUnitOfWork>(); mock.Setup(m => m.Posts.FindByIdAsync(It.IsAny <int>())).ReturnsAsync((int item_id) => new Post() { Id = item_id }); PostService ps = GetNewService(mock.Object); PostDTO result = await ps.FindByIdAsync(2); Assert.AreEqual(2, result.Id); }
public PostDTO FindPost(int id, string slug) { Post post = _post.GetAll().Include(c => c.User).Include(c => c.Comments).Include(c => c.Tags).FirstOrDefault(c => c.ID == id && c.Slug == slug); PostDTO postDto = Mapper.Map <Post, PostDTO>(post); if (post != null) { postDto.AuthorName = post.User.DisplayName; postDto.NameTag = ConvertListTag(post.Tags.ToList()); postDto.ListTagDTO = Mapper.Map <List <Tag>, List <TagDTO> >(post.Tags.ToList()); postDto.ListCommentDTO = MappingComment(post.Comments.ToList()); } return(postDto); }
public void EditPost(PostDTO post) { using (var ctx = new WebForumContext()) { var postToEdit = ctx.Posts.Find(post.Id); if (postToEdit != null) { postToEdit.Text = post.Text; ctx.Entry(postToEdit).State = EntityState.Modified; } ctx.SaveChanges(); } }
public void EditAsync_PremiumPropertyMore100000_Throws() { PostService ps = GetNewService(); PostDTO item = new PostDTO { Title = "Manager", NumberOfUnits = 3, Salary = 60000, Premium = 100001 }; Exception ex = Assert.CatchAsync(async() => await ps.EditAsync(item)); StringAssert.Contains("Надбавка должна быть в диапазоне [0, 100000]", ex.Message); }
public void CreatePost(PostDTO postDto) { Post post = new Post { Description = postDto.Description, Category = postDto.Category, UserId = postDto.UserId, Price = postDto.Price, Date = postDto.Date }; DB.Posts.Create(post); DB.Save(); }
public void AddPostToUsersStreams(PostDTO post, List <string> UsersLogins) { using (ISession session = _cluster.Connect(_keyspace)) { Cassandra.Mapping.IMapper mapper = new Cassandra.Mapping.Mapper(session); session.UserDefinedTypes.Define(new CommentProfile().Definitions); StreamDTO Stream = _StreamMapper.Map <StreamDTO>(post); var Ids = mapper.Fetch <UserDTO>("where \"User_Login\" in (?)", UsersLogins.ToArray()).ToList(); this.AddPostToUsersStreams(post, Ids.Select(p => p.User_Id).ToList()); } }
/// <summary> /// Add new post into database. /// </summary> /// <param name="postDTO">Model of post.</param> /// <returns>Id of created post, ValidationException.</returns> public int AddPost(PostDTO postDTO) { if (postDTO == null) { throw new ValidationException("PostDTO in AddPost() is null", "postDTO"); } var mapper = new MapperConfiguration(cfg => cfg.CreateMap <PostDTO, Post>()).CreateMapper(); Database.Posts.Create(mapper.Map <PostDTO, Post>(postDTO)); SaveChanges(); return(GetLastPostId(postDTO.UserName)); }
public PostDTO AddPost(PostDTO incomingPost) { incomingPost.BlogPost.Slug = incomingPost.BlogPost.Title.GenerateSlug(); if (incomingPost.BlogPost.TagList == null) { incomingPost.BlogPost.TagList = new List <string>(); } var createdPost = _repo.AddPost(incomingPost.BlogPost); var postDTO = new PostDTO { BlogPost = createdPost }; return(postDTO); }
public ICollection <PostDTO> GetPosts() { using (var db = new SovaContext()) { var posts = db.Posts.ToList(); List <PostDTO> postsDTO = new List <PostDTO>(); foreach (var post in posts) { var myPost = new PostDTO(post.Id, post.OwnerUserId, post.Body, post.PostTypeId, post.ParentId, post.Title, post.Score, post.CreationDate, post.ClosedDate, null, GetPostTypeByPostId(post.Id), GetPostTagsByPostId(post.Id), GetUserByPostId(post.Id)); postsDTO.Add(myPost); } return(postsDTO); } }