public PostReaction MakePostReaction(PostReaction postReaction) { EntityEntry <PostReaction> newlyAdded = DataContext.PostReactions.Add(postReaction); DataContext.SaveChanges(); return(newlyAdded.Entity); }
public async Task ReactAsync(ReactionType reactionType, int postId, string authorId) { var postReaction = await this.db.PostReactions .FirstOrDefaultAsync(pr => pr.PostId == postId && pr.AuthorId == authorId); if (postReaction == null) { postReaction = new PostReaction { ReactionType = reactionType, PostId = postId, AuthorId = authorId, CreatedOn = this.dateTimeProvider.Now() }; await this.db.PostReactions.AddAsync(postReaction); } else { postReaction.ModifiedOn = this.dateTimeProvider.Now(); postReaction.ReactionType = postReaction.ReactionType == reactionType ? ReactionType.Neutral : reactionType; } await this.db.SaveChangesAsync(); }
public IActionResult AddPostReaction([FromRoute] int postId, int userId, string reactionName) { if (_context.Posts.Find(postId) == null) { return(NotFound("Post with this postId does not exist")); } if (_context.Users.Find(userId) == null) { return(NotFound("User with this userId does not exist")); } if (!_context.Reactions.Where(x => x.Value == reactionName).Any()) { return(NotFound("Reaction with this name does not exist")); } var allPostsReactions = _context.PostReactions.Where(x => x.PostId == postId).ToList(); foreach (var item in allPostsReactions) { if (item.UserId == userId) { return(BadRequest("Reaction to this post already exists from this user")); } } var postReaction = new PostReaction { PostId = postId, ReactionId = _context.Reactions.Where(x => x.Value == reactionName).First().Idreaction, UserId = userId }; _context.PostReactions.Add(postReaction); _context.SaveChanges(); return(Ok()); }
public List <PostReaction> GetPostReactionsByPostId(int id) { using (SqlConnection conn = Connection) { conn.Open(); using (SqlCommand cmd = conn.CreateCommand()) { cmd.CommandText = @"SELECT r.Id, r.PostId, r.ReactionId, r.UserProfileId FROM PostReaction r LEFT JOIN Post p ON p.Id = r.PostId LEFT JOIN Reaction e ON e.Id = r.ReactionId LEFT JOIN UserProfile u ON u.Id = r.UserProfileId WHERE r.PostId = @id"; cmd.Parameters.AddWithValue("@id", id); SqlDataReader reader = cmd.ExecuteReader(); List <PostReaction> reactions = new List <PostReaction>(); while (reader.Read()) { PostReaction reaction = new PostReaction { Id = reader.GetInt32(reader.GetOrdinal("Id")), PostId = reader.GetInt32(reader.GetOrdinal("PostId")), ReactionId = reader.GetInt32(reader.GetOrdinal("ReactionId")), UserProfileId = reader.GetInt32(reader.GetOrdinal("UserProfileId")) }; reactions.Add(reaction); } reader.Close(); return(reactions); } } }
public IActionResult AddPostReaction([FromBody] ReactionCommand model) { if (_context.Posts.Find(model.PostID) == null) { return(NotFound("Post with this postId does not exist")); } if (_context.Users.Find(model.UserID) == null) { return(NotFound("User with this userId does not exist")); } if (!_context.Reactions.Where(x => x.Value == model.ReactionName).Any()) { return(NotFound("Reaction with this name does not exist")); } var allPostsReactions = _context.PostReactions.Where(x => x.PostId == model.PostID).ToList(); foreach (var item in allPostsReactions) { if (item.UserId == model.UserID) { return(BadRequest("Reaction to this post already exists from this user")); } } var postReaction = new PostReaction { PostId = model.PostID, ReactionId = _context.Reactions.Where(x => x.Value == model.ReactionName).First().Idreaction, UserId = model.UserID }; _context.PostReactions.Add(postReaction); _context.SaveChanges(); return(Ok()); }
public async Task <PostReactionDto> AddPostReactionAsync(Guid postId, PostReactionToAddDto postReaction) { _logger.LogDebug("Trying to add reaction {postReaction}.", postReaction); if (postReaction is null) { throw new ArgumentNullException(nameof(PostReaction)); } if (postId == Guid.Empty || postReaction.FromWho == Guid.Empty) { throw new ArgumentNullException(nameof(Guid)); } try { PostReaction reactionToAdd = _mapper.Map <PostReaction>(postReaction); reactionToAdd.PostId = postId; PostReaction addedReaction = await _postReactionRepository.AddAsync(reactionToAdd); await _postReactionRepository.SaveAsync(); return(_mapper.Map <PostReactionDto>(addedReaction)); } catch (Exception ex) { _logger.LogError(ex, "Error occured during adding the reaction."); throw; } }
//if reaction id exists in previous post reaction.reactionId then increment count on previous post reaction //if reaction id does not exist in previous post reaction then create a new post reaction with a count of 1 public List <PostReaction> GetAllReactionsCountedByPostId(int id) { using (var conn = Connection) { conn.Open(); using (var cmd = conn.CreateCommand()) { cmd.CommandText = @" SELECT pr.Id As PostReactionId, pr.PostId, pr.ReactionId, pr.UserProfileId AS UserProfileIdReactingToPost, r.Id, r.Name, r.ImageLocation FROM PostReaction pr JOIN Reaction r ON pr.ReactionId = r.Id WHERE pr.PostId = @id "; cmd.Parameters.AddWithValue("@id", id); var postReactions = new List <PostReaction>(); var reader = cmd.ExecuteReader(); while (reader.Read()) { PostReaction postReaction = new PostReaction { Id = reader.GetInt32(reader.GetOrdinal("PostReactionId")), PostId = reader.GetInt32(reader.GetOrdinal("PostId")), ReactionId = reader.GetInt32(reader.GetOrdinal("ReactionId")), UserProfileId = reader.GetInt32(reader.GetOrdinal("UserProfileIdReactingToPost")), Reaction = new Reaction { Id = reader.GetInt32(reader.GetOrdinal("Id")), Name = reader.GetString(reader.GetOrdinal("Name")), ImageLocation = reader.GetString(reader.GetOrdinal("ImageLocation")), ReactionCount = 1 } }; var reactionId = reader.GetInt32(reader.GetOrdinal("ReactionId")); var anotherPostReaction = postReactions.Find(pr => pr.ReactionId == reactionId); if (anotherPostReaction == null) { postReactions.Add(postReaction); } else { int initalReactionIndex = postReactions.FindIndex(pr => pr.ReactionId == reactionId); postReactions[initalReactionIndex].Reaction.ReactionCount = postReactions[initalReactionIndex].Reaction.ReactionCount + 1; } } reader.Close(); return(postReactions); } } }
public async Task <bool> TryUpdatePostReactionAsync(Guid reactionId, JsonPatchDocument <PostReactionToUpdateDto> patchDocument) { _logger.LogDebug("Trying to update post reaction: {id}.", reactionId); try { PostReaction reactionFromRepo = _postReactionRepository.GetById(reactionId); if (reactionFromRepo == null) { return(false); } PostReactionToUpdateDto reactionToPatch = _mapper.Map <PostReactionToUpdateDto>(reactionFromRepo); patchDocument.ApplyTo(reactionToPatch); if (!ValidatorHelper.ValidateModel(reactionToPatch)) { return(false); } _mapper.Map(reactionToPatch, reactionFromRepo); _postReactionRepository.Update(reactionFromRepo); await _postReactionRepository.SaveAsync(); _logger.LogDebug("Reaction: {id} has been updated.", reactionId); return(true); } catch (Exception ex) { _logger.LogError(ex, "Error occured during updating the post reaction."); throw; } }
public ActionResult React(int postId, int reactionId) { PostReaction postReaction = new PostReaction(); postReaction.PostId = postId; postReaction.ReactionId = reactionId; postReaction.UserProfileId = GetCurrentUserId(); _postReactionRepository.AddPostReaction(postReaction); return(RedirectToAction("Details", "Post", new { id = postId })); }
public async Task <bool> UpdatePostReaction(PostReaction postReaction) { String postReactionAsJson = JsonSerializer.Serialize(postReaction); StringContent stringContent = new StringContent( postReactionAsJson, Encoding.UTF8, "application/json" ); HttpResponseMessage responseMessage = await Client.PatchAsync("http://localhost:5002/feedle/posts/reaction", stringContent); return(responseMessage.IsSuccessStatusCode); }
private async Task CreatePostReaction(SetPostReactionViewModel model) { var postReactions = _dataService.GetSet <PostReaction>(); var newReaction = new PostReaction { User = model.User, PostId = model.PostId, Type = model.Type }; await postReactions.AddAsync(newReaction); await _dataService.SaveDbAsync(); }
private async Task UpdatePostReaction(SetPostReactionViewModel model, PostReaction userPostReaction) { var postReactions = _dataService.GetSet <PostReaction>(); if (userPostReaction.Type == model.Type) { postReactions.Remove(userPostReaction); } else { userPostReaction.Type = model.Type; } await _dataService.SaveDbAsync(); }
public IActionResult Post(PostReaction postReaction) { var previousReactions = _postReactionRepository.GetAllReactionsByPostId(postReaction.PostId); var existingReactionFromUserProfile = previousReactions.Find(previousReaction => previousReaction.UserProfileId == postReaction.UserProfileId); if (existingReactionFromUserProfile == null) { _postReactionRepository.AddPostReaction(postReaction); return(CreatedAtAction(nameof(GetAllPostReactions), new { id = postReaction.Id }, postReaction)); } else { return(Ok()); } }
public ActionResult React(FormCollection collection) { User user = getAuthUser(); if (user == null) { return(HttpNotFound()); } int postid = int.Parse(collection["PostID"] ?? Request.Form["PostID"]); int reactionid = int.Parse(collection["ReactionId"] ?? Request.Form["ReactionId"]); PostReaction reaction = null; if (db.PostReactions.Any(p => p.PostID == postid && p.UserID == user.UserId)) { reaction = db.PostReactions.Single(p => p.PostID == postid && p.UserID == user.UserId); if (reaction.ReactionID == reactionid) { db.PostReactions.Remove(reaction); db.SaveChanges(); return(Json(new { message = "unreacted", status = "success" })); } else { return(Json(new { status = "error", message = "you already reacted to that post" })); } } else { /*[Bind(Include = "ReactionId,PostID")] PostReaction reaction*/ reaction = new PostReaction() { ReactionID = reactionid, PostID = postid, UserID = user.UserId, PostReactionId = 0 }; //db.PostReactions.Attach( reaction ); db.PostReactions.Add(reaction); db.SaveChanges(); } db.Dispose(); db = new DB(); string format = Request?["format"]; //if (format == "json") return(Json(new { message = "reacted", status = "success" })); //return RedirectToAction("Details", new { id = reaction.PostID }); }
public List <PostReaction> GetAllReactionsByPostId(int id) { using (var conn = Connection) { conn.Open(); using (var cmd = conn.CreateCommand()) { cmd.CommandText = @" SELECT pr.Id, pr.PostId, pr.ReactionId, pr.UserProfileId AS UserProfileIdReactingToPost, r.Id, r.Name, r.ImageLocation FROM PostReaction pr JOIN Reaction r ON pr.ReactionId = r.Id WHERE pr.PostId = @id "; cmd.Parameters.AddWithValue("@id", id); var postReactions = new List <PostReaction>(); var reader = cmd.ExecuteReader(); while (reader.Read()) { PostReaction postReaction = new PostReaction { Id = reader.GetInt32(reader.GetOrdinal("Id")), PostId = reader.GetInt32(reader.GetOrdinal("PostId")), ReactionId = reader.GetInt32(reader.GetOrdinal("ReactionId")), UserProfileId = reader.GetInt32(reader.GetOrdinal("UserProfileIdReactingToPost")), Reaction = new Reaction { Id = reader.GetInt32(reader.GetOrdinal("Id")), Name = reader.GetString(reader.GetOrdinal("Name")), ImageLocation = reader.GetString(reader.GetOrdinal("ImageLocation")) } }; postReactions.Add(postReaction); } reader.Close(); return(postReactions); } } }
public async Task SwitchReaction(int postId, string userId, PostReactionType type) { var existingReaction = await _postReactionRepo.GetOneByCondition(r => r.PostId == postId && r.UserId == userId); if (existingReaction != null) { _postReactionRepo.Remove(existingReaction); return; } var postReaction = new PostReaction { PostId = postId, UserId = userId, Type = type }; await _postReactionRepo.Add(postReaction); }
public async Task ReactMethodShouldAddReactionInDatabaseIfNotExistsAlready(string title, string description, ReactionType type) { var guid = Guid.NewGuid().ToString(); var options = new DbContextOptionsBuilder <ForumDbContext>() .UseInMemoryDatabase(guid) .Options; var db = new ForumDbContext(options); var dateTimeProvider = new Mock <IDateTimeProvider>(); dateTimeProvider.Setup(dtp => dtp.Now()).Returns(new DateTime(2020, 3, 27)); var post = new Post { Id = 1, Title = title, Description = description, CategoryId = 1, AuthorId = guid, CreatedOn = dateTimeProvider.Object.Now() }; await db.Posts.AddAsync(post); await db.SaveChangesAsync(); var postReactionsService = new PostReactionsService(db, dateTimeProvider.Object); var result = await postReactionsService.ReactAsync(type, 1, guid); var actual = await db.PostReactions.FirstOrDefaultAsync(); var expected = new PostReaction { Id = 1, PostId = 1, Post = post, AuthorId = guid, ReactionType = type, CreatedOn = dateTimeProvider.Object.Now() }; actual.Should().BeEquivalentTo(expected); result.Should().BeOfType <ReactionsCountServiceModel>(); }
public PostReactionDto GetPostReaction(Guid reactionId) { _logger.LogDebug("Trying to get reaction: {reactionId}", reactionId); if (reactionId == Guid.Empty) { throw new ArgumentNullException(nameof(Guid)); } try { PostReaction reactionFromRepo = _postReactionRepository.GetById(reactionId); return(_mapper.Map <PostReactionDto>(reactionFromRepo)); } catch (Exception ex) { _logger.LogError(ex, "Error occured during getting the reaction."); throw; } }
public async Task ReactMethodShouldChangeReactionToNeutralIfReactionIsClickedTwice(ReactionType type) { var guid = Guid.NewGuid().ToString(); var options = new DbContextOptionsBuilder <ForumDbContext>() .UseInMemoryDatabase(guid) .Options; var db = new ForumDbContext(options); var dateTimeProvider = new Mock <IDateTimeProvider>(); dateTimeProvider.Setup(dtp => dtp.Now()).Returns(new DateTime(2020, 3, 27)); var postReaction = new PostReaction { Id = 1, PostId = 1, AuthorId = guid, ReactionType = type, CreatedOn = dateTimeProvider.Object.Now() }; await db.PostReactions.AddAsync(postReaction); await db.SaveChangesAsync(); var postReactionsService = new PostReactionsService(db, dateTimeProvider.Object); var result = await postReactionsService.ReactAsync(type, 1, guid); var actual = await db.PostReactions.FirstOrDefaultAsync(); var expected = new PostReaction { Id = 1, PostId = 1, AuthorId = guid, ReactionType = ReactionType.Neutral, CreatedOn = dateTimeProvider.Object.Now(), ModifiedOn = dateTimeProvider.Object.Now() }; actual.Should().BeEquivalentTo(expected); result.Should().BeOfType <ReactionsCountServiceModel>(); }
public async Task GetTotalCountMethodShouldReturnAllPostReactionsCount() { var guid = Guid.NewGuid().ToString(); var options = new DbContextOptionsBuilder <ForumDbContext>() .UseInMemoryDatabase(guid) .Options; var db = new ForumDbContext(options); var dateTimeProvider = new Mock <IDateTimeProvider>(); dateTimeProvider.Setup(dtp => dtp.Now()).Returns(new DateTime(2020, 3, 27)); var post = new Post { Id = 1, Title = "Test title", Description = "Test description", CategoryId = 1, AuthorId = guid, CreatedOn = dateTimeProvider.Object.Now() }; var postReaction = new PostReaction { Id = 1, PostId = 1, AuthorId = guid, ReactionType = ReactionType.Like, CreatedOn = dateTimeProvider.Object.Now() }; await db.Posts.AddAsync(post); await db.PostReactions.AddAsync(postReaction); await db.SaveChangesAsync(); var postReactionsService = new PostReactionsService(db, dateTimeProvider.Object); var count = await postReactionsService.GetTotalCountAsync(); count.Should().Be(1); }
public void AddPostReaction(PostReaction postReaction) { using (var conn = Connection) { conn.Open(); using (var cmd = conn.CreateCommand()) { cmd.CommandText = @"INSERT INTO PostReaction (PostId, ReactionId, UserProfileId) OUTPUT INSERTED.ID VALUES (@postId, @reactionId, @userProfileId)"; cmd.Parameters.AddWithValue("@postId", postReaction.PostId); cmd.Parameters.AddWithValue("@reactionId", postReaction.ReactionId); cmd.Parameters.AddWithValue("@userProfileId", postReaction.UserProfileId); int id = (int)cmd.ExecuteScalar(); postReaction.Id = id; } } }
public async Task DeletePostReactionAsync(Guid postReactionId) { _logger.LogDebug("Trying to remove reaction: {postReaction}.", postReactionId); if (postReactionId == Guid.Empty) { throw new ArgumentNullException(nameof(postReactionId)); } try { PostReaction reactionToRemove = _postReactionRepository.GetById(postReactionId); if (reactionToRemove != null) { _postReactionRepository.Remove(reactionToRemove); await _postReactionRepository.SaveAsync(); _logger.LogDebug("Reaction {postReaction} has been removed.", reactionToRemove); } } catch (Exception ex) { _logger.LogError(ex, "Error occured during removing the reaction."); throw; } }
public PostReaction UpdatePostReaction(PostReaction postReaction) { bool tracking = DataContext.ChangeTracker.Entries <PostReaction>() .Any(x => x.Entity.PostReactionId == postReaction.PostReactionId); if (!tracking) { EntityEntry <PostReaction> updated = DataContext.Update(postReaction); DataContext.SaveChanges(); return(updated.Entity); } var reactionToUpdate = DataContext.PostReactions.FirstOrDefault(p => p.PostReactionId == postReaction.PostReactionId); if (reactionToUpdate != null) { reactionToUpdate.Status = postReaction.Status; DataContext.SaveChanges(); return(reactionToUpdate); } return(null); }
public void Add(PostReaction pr) { _context.Add(pr); _context.SaveChanges(); }
public IHttpActionResult UpdateReact(React React) { var reactions = _context.PostReactions.ToList(); int found = 0; foreach (var reaction in reactions) { if (reaction.clientId == React.clientId && reaction.postId == React.postId && React.reactType == "Like") { reaction.Reaction = 1; found++; _context.SaveChanges(); } else if (reaction.clientId == React.clientId && reaction.postId == React.postId && React.reactType == "RemoveLike") { reaction.Reaction = 0; found++; _context.SaveChanges(); } else if (reaction.clientId == React.clientId && reaction.postId == React.postId && React.reactType == "DisLike") { reaction.Reaction = 2; found++; _context.SaveChanges(); } else if (reaction.clientId == React.clientId && reaction.postId == React.postId && React.reactType == "RemoveDislike") { reaction.Reaction = 0; found++; _context.SaveChanges(); } } if (found == 0 && React.reactType == "Like") { var reaction = new PostReaction { clientId = React.clientId, postId = React.postId, Reaction = 1 }; _context.PostReactions.Add(reaction); _context.SaveChanges(); found++; } if (found == 0 && React.reactType == "DisLike") { var reaction = new PostReaction { clientId = React.clientId, postId = React.postId, Reaction = 2 }; _context.PostReactions.Add(reaction); _context.SaveChanges(); found++; } var reacts = _context.PostReactions.Where(c => c.postId == React.postId).ToList(); int like = 0; int dlike = 0; foreach (var re in reacts) { if (re.Reaction == 1) { like++; } if (re.Reaction == 2) { dlike++; } } var numOfReactionVM = new ViewModels.NumberOfReactions { Likes = like, disLikes = dlike }; return(Ok(numOfReactionVM)); //return Ok(); }
public void Update(PostReaction pr) { _context.Entry(pr).State = EntityState.Modified; _context.SaveChanges(); }
public IActionResult Post(PostReaction postReaction) { _postReactionRepository.Add(postReaction); return(CreatedAtAction("Get", new { id = postReaction.Id }, postReaction)); }
private void buttonComment_Click(object sender, EventArgs e) { Comment comment = commentBindingSource.Current as Comment; PostReaction.CommentOnPost(comment.UserComment, comment.Id); }
public Task <bool> UpdatePostReaction(PostReaction postReaction) { throw new NotImplementedException(); }
public IActionResult EditPostReaction(PostReaction pr) { _postReactionRepository.Update(pr); return(Ok(pr)); }