public IHttpActionResult AddComment(int postId, CommentBindingModel model) { var post = this.Data.Posts.All().FirstOrDefault(p => p.Id == postId); if (post == null) { return this.BadRequest(String.Format("there is no post with id {0}", postId)); } if (post.IsPostHidden) { return this.NotFound(); } if (!this.ModelState.IsValid) { return this.BadRequest(this.ModelState); } var currentUserId = this.User.Identity.GetUserId(); var loggedUser = this.Data.ApplicationUsers.All().FirstOrDefault(u => u.Id == currentUserId); bool isFriend = loggedUser.Friends.Any(f => f.Id == post.WallOwnerId || f.Id == post.OwnerId); // You can comment only your friends posts or comment posts on your friends wall if (!isFriend && currentUserId != post.WallOwnerId) { return this.BadRequest("You can comment only friend posts"); } var comment = new Comment() { Content = model.Content, PostId = postId, CreatedOn = DateTime.Now, CommentOwner = loggedUser, PostOwner = post.Owner }; this.Data.Comments.Add(comment); this.Data.SaveChanges(); var postedComment = this.Data.Comments.All() .Where(c => c.Id == comment.Id) .Select(CommentViewModel.Create) .FirstOrDefault(); return this.Ok(postedComment); }
public static CommentViewModel Create1(Comment c) { return new CommentViewModel() { Id = c.Id, Content = c.Content, CreatedOn = c.CreatedOn, CommentOwner = new OwnerViewModel() { Id = c.CommentOwner.Id, Username = c.CommentOwner.UserName }, PostOwner = new OwnerViewModel() { Id = c.PostOwner.Id, Username = c.PostOwner.UserName }, Likes = new LikeViewModel() { Likes = c.Likes.Count } }; }
public static CommentViewModel CreateCommentAndUser(Comment c, ApplicationUser currentUser) { return new CommentViewModel() { Id = c.Id, Author = new UserViewModelMinified() { Id = c.CommentOwner.Id, Gender = c.CommentOwner.Gender, Name = c.CommentOwner.Name, ProfileImageData = c.CommentOwner.ProfileImageData, Username = c.CommentOwner.UserName }, LikesCount = c.Likes.Count, Content = c.Content, CreatedOn = c.CreatedOn, IsLiked = c.Likes.Any(l => l.UserId == currentUser.Id) }; }