private async Task ProcessRatingButton(PostRating ratingByCurrentUser, RatingValue ratingValue) { if (ratingByCurrentUser.Value == ratingValue) { await _ratingRepository.Delete(ratingByCurrentUser.Id); } else { ratingByCurrentUser.Value = ratingValue; await _ratingRepository.Update(ratingByCurrentUser); } }
public async Task <Response> Handle(Request request, CancellationToken cancellationToken) { var userId = _tools.CurrentUserId(); var postToRate = await _tools.Query.Of <Post>() .Where(p => p.Id == request.PostId) .FirstOrDefaultAsync(cancellationToken); if (postToRate == null) { return(Responses.Failure("Post not found")); } if (postToRate.AuthorId == userId) { return(Responses.Failure("User cant rate his own post")); } var rating = await _tools.Query.Of <PostRating>() .Where(r => r.PostId == request.PostId && r.UserId == userId) .FirstOrDefaultAsync(cancellationToken); if (rating == null) { var newRating = new PostRating { PostId = request.PostId, UserId = userId, Type = request.RatingType }; _tools.UnitOfWork.Add(newRating); await _tools.UnitOfWork.PersistChanges(); return(Responses.Success(newRating)); } else { if (rating.Type == request.RatingType) { return(Responses.Failure("Attempt to rate post by the same user with the same rating type")); } rating.Type = request.RatingType; _tools.UnitOfWork.Update(rating); await _tools.UnitOfWork.PersistChanges(); return(Responses.Success(rating)); } }
public void Execute() { int postId = int.Parse(this.Parameters[0]); Post postFromDb = DbContext.Posts.FirstOrDefault(post => post.Id == postId); if (postFromDb == null || postFromDb.IsDeleted) { this.ConsoleWriter.Write(Constants.ConsoleForumOutputPrefix); this.ConsoleWriter.ErrorLine(NoSuchPostMessage); Thread.Sleep(Constants.NotificationDelay); } else if (postFromDb.Ratings.Any(rating => rating.User.Id == this.Principal.User.Id)) { PostRating ratingFromDb = postFromDb.Ratings.First(rating => rating.User.Id == this.Principal.User.Id); if (ratingFromDb.IsPositive) { this.ConsoleWriter.Write(Constants.ConsoleForumOutputPrefix); this.ConsoleWriter.ErrorLine(CannotLikeAgainMessage); Thread.Sleep(Constants.NotificationDelay); } else { ratingFromDb.Toggle(); this.ConsoleWriter.Write(Constants.ConsoleForumOutputPrefix); this.ConsoleWriter.SuccessLine(SuccessLikeMessage, postId); Thread.Sleep(Constants.NotificationDelay); } } else { PostRating rating = new PostRating(PostRatingChoice.Positive) { User = this.Principal.User, Post = postFromDb }; DbContext.Add(rating); this.Principal.User.Ratings.Add(rating); postFromDb.Ratings.Add(rating); this.ConsoleWriter.Write(Constants.ConsoleForumOutputPrefix); this.ConsoleWriter.SuccessLine(SuccessLikeMessage, postId); Thread.Sleep(Constants.NotificationDelay); } }
}//end title property public int CompareTo(Object aplha) { if (aplha == null) { throw new ArgumentNullException(); } Post rightOp = aplha as Post; if (rightOp != null) { return(PostRating.CompareTo(rightOp.PostRating)); //This might have to be switched around } else { throw new ArgumentException("[Post]:CompareTo argument is not a Post Object."); } }
public void CreatePost(NewPostViewModel postVm, string userId) { Guard.WhenArgument(userId, "userId").IsNullOrEmpty().Throw(); var bookVm = postVm.Book; var book = new Book() { Id = Guid.NewGuid(), Author = bookVm.Author, CategoryId = Guid.Parse(bookVm.Category), Image = this.fileConverter.PostedToByteArray(bookVm.Image), PublishedOn = bookVm.PublishedOn, Publisher = bookVm.Publisher, Title = bookVm.Title }; var post = new Post() { Id = Guid.NewGuid(), Book = book, CreatedOn = this.dateTimeProvider.Now(), IsActive = true, PublisherId = userId, Description = postVm.Description, Price = postVm.Price }; var publisherRating = new PostRating() { Id = Guid.NewGuid(), Post = post, Rating = postVm.Rating, UserId = userId }; post.PostRatings.Add(publisherRating); this.context.Books.Add(book); this.context.Posts.Add(post); this.context.SaveChanges(); }
public async Task If_current_user_is_author_should_throw_exception() { var ratingModel = new RatingModel { PostId = 1, Value = RatingButtonPosition.ThumbsUp }; var rating = new PostRating(); var users = new List <User>() { new User { Id = 1, Email = "email" } }; _mockUserRepository.Setup(repo => repo.Get(It.IsAny <Func <User, bool> >())). Returns((Func <User, bool> predicate) => users.Where(predicate).ToList()); _mockPostRepository.Setup(repo => repo.FindById(1)).ReturnsAsync(new Post { UserId = 1 }); await Assert.ThrowsAsync <RatingFailedException>(async() => await _ratingService.Set(ratingModel, "email")); }
} // End of the constructor #endregion #region Insert methods /// <summary> /// Add one post /// </summary> /// <param name="post">A reference to a post</param> public static void Add(PostRating post) { // Create the connection and the sql statement string connection = Tools.GetConnectionString(); string sql = "INSERT INTO dbo.posts_ratings (post_id, administrator_id, language_id, rating_date, rating) " + "VALUES (@post_id, @administrator_id, @language_id, @rating_date, @rating);"; // The using block is used to call dispose automatically even if there are is a exception. using (SqlConnection cn = new SqlConnection(connection)) { // The using block is used to call dispose automatically even if there are is a exception. using (SqlCommand cmd = new SqlCommand(sql, cn)) { // Add parameters cmd.Parameters.AddWithValue("@post_id", post.post_id); cmd.Parameters.AddWithValue("@administrator_id", post.administrator_id); cmd.Parameters.AddWithValue("@language_id", post.language_id); cmd.Parameters.AddWithValue("@rating_date", post.rating_date); cmd.Parameters.AddWithValue("@rating", post.rating); // The Try/Catch/Finally statement is used to handle unusual exceptions in the code to // avoid having our application crash in such cases try { // Open the connection cn.Open(); // Execute the insert cmd.ExecuteNonQuery(); } catch (Exception e) { throw e; } } } } // End of the Add method
} // End of the Add method #endregion #region Update methods /// <summary> /// Update a post /// </summary> /// <param name="post">A reference to a post</param> public static void Update(PostRating post) { // Create the connection and the sql statement string connection = Tools.GetConnectionString(); string sql = "UPDATE dbo.posts_ratings SET rating_date = @rating_date, rating = @rating WHERE post_id = @post_id " + "AND administrator_id = @administrator_id AND language_id = @language_id;"; // The using block is used to call dispose automatically even if there is a exception. using (SqlConnection cn = new SqlConnection(connection)) { // The using block is used to call dispose automatically even if there is a exception. using (SqlCommand cmd = new SqlCommand(sql, cn)) { // Add parameters cmd.Parameters.AddWithValue("@post_id", post.post_id); cmd.Parameters.AddWithValue("@administrator_id", post.administrator_id); cmd.Parameters.AddWithValue("@language_id", post.language_id); cmd.Parameters.AddWithValue("@rating_date", post.rating_date); cmd.Parameters.AddWithValue("@rating", post.rating); // The Try/Catch/Finally statement is used to handle unusual exceptions in the code to // avoid having our application crash in such cases. try { // Open the connection. cn.Open(); // Execute the update cmd.ExecuteNonQuery(); } catch (Exception e) { throw e; } } } } // End of the Update method
/// <summary> /// Constructor that SHOULD be used for images /// </summary> /// <param name="post"></param> /// <param name="isUIImage"></param> public BasePost(BasePost post, bool isUIImage = false) { _cache = new ImageCache(); ImageRating = post.ImageRating; FullPictureURL = post.FullPictureURL; if (isUIImage) { _extension = UtilityFunctions.GetUrlExtension(post.PreviewURL); urlStore = PreviewURL = _cache.GetImage(post.FileMD, post.PreviewURL, LateFilePath, null, false); } else urlStore = PreviewURL = post.PreviewURL; FileMD = post.FileMD; Tags = post.Tags.Trim(); _width = post._width; _height = post._height; PostId = post.PostId; IsVisible = true; Dimensions = "Resolution " + _width + "x" + _height + "\n" + "Tags: " + "\n" + Tags; }
public IReadOnlyCollection <PostAction> GetAllowedPostActionsForUser(string userId, Post post, PostRating currentRating) { var ret = new HashSet <PostAction>(); bool hasDisliked = false, hasLiked = false; switch (currentRating?.Type) { case PostRatingType.Like: hasLiked = true; break; case PostRatingType.Dislike: hasDisliked = true; break; } if (CanPublish(userId)) { ret.Add(PostAction.Publish); } if (CanEdit(userId, post)) { ret.Add(PostAction.Edit); } if (CanDelete(userId, post)) { ret.Add(PostAction.Delete); } if ((!hasLiked || !hasDisliked) && post.AuthorId != userId) { ret.Add(PostAction.Like); } if ((!hasLiked || !hasDisliked) && post.AuthorId != userId) { ret.Add(PostAction.Dislike); } if (hasLiked && post.AuthorId != userId) { ret.Add(PostAction.UnLike); } if (hasDisliked && post.AuthorId != userId) { ret.Add(PostAction.UnDislike); } ret.Add(PostAction.View); return(ret); }
} // End of the GetCountByPostId method #endregion #region Get methods /// <summary> /// Get one rating by id /// </summary> /// <param name="postId">The post id</param> /// <param name="administratorId">The administrator id</param> /// <param name="languageId">The language id</param> /// <returns>A reference to a post</returns> public static PostRating GetOneById(Int32 postId, Int32 administratorId, Int32 languageId) { // Create the post to return PostRating post = null; // Create the connection and the sql statement string connection = Tools.GetConnectionString(); string sql = "SELECT * FROM dbo.posts_ratings WHERE post_id = @post_id AND administrator_id = @administrator_id " + "AND language_id = @language_id;"; // The using block is used to call dispose automatically even if there are an exception. using (SqlConnection cn = new SqlConnection(connection)) { // The using block is used to call dispose automatically even if there are an exception. using (SqlCommand cmd = new SqlCommand(sql, cn)) { // Add parameters cmd.Parameters.AddWithValue("@post_id", postId); cmd.Parameters.AddWithValue("@administrator_id", administratorId); cmd.Parameters.AddWithValue("@language_id", languageId); // Create a MySqlDataReader SqlDataReader reader = null; // The Try/Catch/Finally statement is used to handle unusual exceptions in the code to // avoid having our application crash in such cases. try { // Open the connection. cn.Open(); // Fill the reader with one row of data. reader = cmd.ExecuteReader(); // Loop through the reader as long as there is something to read and add values while (reader.Read()) { post = new PostRating(reader); } } catch (Exception e) { throw e; } finally { // Call Close when done reading to avoid memory leakage. if (reader != null) reader.Close(); } } } // Return the post return post; } // End of the GetOneById method
private void TriggerRatePost(PostRating r) { OnRatePost?.Invoke(this, new RatePostEventArgs(r)); }
} // End of the GetSignedInAdministrator method #endregion #region Delete methods /// <summary> /// Delete a administrator post on id /// </summary> /// <param name="id">The id of the administrator post</param> /// <returns>An error code</returns> public static Int32 DeleteOnId(Int32 id) { // Delete post comments by administrator id PostComment.DeleteOnAdministratorId(id); // Delete post ratings by administrator id List <PostRating> postRatings = PostRating.GetAllByAdministratorId(id); for (int i = 0; i < postRatings.Count; i++) { PostRating.DeleteOnId(postRatings[i].post_id, postRatings[i].administrator_id, postRatings[i].language_id); Post.UpdateRating(postRatings[i].post_id, postRatings[i].language_id); } // Delete posts by administrator id List <Post> posts = Post.GetAllByAdministratorId(id); for (int i = 0; i < posts.Count; i++) { Post.DeleteOnId(posts[i].id); } // Create the connection and the sql statement string connection = Tools.GetConnectionString(); string sql = "DELETE FROM dbo.administrators_detail WHERE administrator_id = @id;DELETE FROM dbo.administrators WHERE id = @id;"; // The using block is used to call dispose automatically even if there is a exception. using (SqlConnection cn = new SqlConnection(connection)) { // The using block is used to call dispose automatically even if there is a exception. using (SqlCommand cmd = new SqlCommand(sql, cn)) { // Add parameters cmd.Parameters.AddWithValue("@id", id); // The Try/Catch/Finally statement is used to handle unusual exceptions in the code to // avoid having our application crash in such cases. try { // Open the connection. cn.Open(); // Execute the update cmd.ExecuteNonQuery(); } catch (SqlException e) { // Check for a foreign key constraint error if (e.Number == 547) { return(5); } else { throw e; } } catch (Exception e) { throw e; } } } // Return the code for success return(0); } // End of the DeleteOnId method
public ActionResult delete(Int32 id = 0, Int32 administratorId = 0, Int32 languageId = 0, string returnUrl = "/admin_ratings") { // Get the current domain Domain currentDomain = Tools.GetCurrentDomain(); ViewBag.CurrentDomain = currentDomain; // Get query parameters ViewBag.QueryParams = new QueryParams(returnUrl); // Get the signed in administrator Administrator administrator = Administrator.GetSignedInAdministrator(); // Get the post rating PostRating postRating = PostRating.GetOneById(id, administratorId, languageId); // Check if the administrator is authorized if (Administrator.IsAuthorized(new string[] { "Administrator" }) == true) { ViewBag.AdminSession = true; } else if (administrator != null && administrator.admin_role == "Author" && (postRating == null || postRating.administrator_id == administrator.id)) { ViewBag.AdminSession = true; } else if (Administrator.IsAuthorized(Administrator.GetAllAdminRoles()) == true) { ViewBag.AdminSession = true; ViewBag.AdminErrorCode = 1; ViewBag.TranslatedTexts = StaticText.GetAll(currentDomain.back_end_language, "id", "ASC"); return View("index"); } else { // Redirect the user to the start page return RedirectToAction("index", "admin_login"); } // Get the rating post PostRating rating = PostRating.GetOneById(id, administratorId, languageId); // Create an error code variable Int32 errorCode = 0; // Make sure that the rating not is null if (rating != null) { // Delete the rating errorCode = PostRating.DeleteOnId(id, administratorId, languageId); // Check if there is an error if (errorCode != 0) { ViewBag.AdminErrorCode = errorCode; ViewBag.TranslatedTexts = StaticText.GetAll(currentDomain.back_end_language, "id", "ASC"); return View("index"); } // Update the post rating Post.UpdateRating(rating.post_id, rating.language_id); } // Redirect the user to the list return Redirect(returnUrl); } // End of the delete method
public bool CanDislike(string userId, Post post, PostRating usersRating = null) { return(CanRate(userId, post, usersRating)); }
public ActionResult edit(FormCollection collection) { // Get the current domain Domain currentDomain = Tools.GetCurrentDomain(); ViewBag.CurrentDomain = currentDomain; // Get all the form values Int32 post_id = Convert.ToInt32(collection["hiddenPostId"]); Int32 administrator_id = Convert.ToInt32(collection["hiddenAdministratorId"]); Int32 language_id = Convert.ToInt32(collection["hiddenLanguageId"]); decimal rating = 0; decimal.TryParse(collection["userVote"].Replace(",", "."), NumberStyles.Any, CultureInfo.InvariantCulture, out rating); string returnUrl = collection["returnUrl"]; // Get query parameters ViewBag.QueryParams = new QueryParams(returnUrl); // Get the signed in administrator Administrator administrator = Administrator.GetSignedInAdministrator(); // Get the post rating PostRating postRating = PostRating.GetOneById(post_id, administrator_id, language_id); // Check if the administrator is authorized if (Administrator.IsAuthorized(new string[] { "Administrator", "Editor" }) == true) { ViewBag.AdminSession = true; } else if (administrator != null && administrator.admin_role == "Author" && (postRating == null || postRating.administrator_id == administrator.id)) { ViewBag.AdminSession = true; } else if (Administrator.IsAuthorized(Administrator.GetAllAdminRoles()) == true) { ViewBag.AdminSession = true; ViewBag.AdminErrorCode = 1; ViewBag.TranslatedTexts = StaticText.GetAll(currentDomain.back_end_language, "id", "ASC"); return View("index"); } else { // Redirect the user to the start page return RedirectToAction("index", "admin_login"); } // Update the post rating if (postRating != null) { // Update the rating for the post postRating.rating = rating; PostRating.Update(postRating); // Update the rating sum for the post Post.UpdateRating(post_id, language_id); } // Redirect the user to the list return Redirect(returnUrl); } // End of the edit method
public ActionResult edit_rating(FormCollection collection) { // Make sure that the user is signed in Administrator user = Administrator.GetSignedInAdministrator(); // Get the current domain Domain domain = Tools.GetCurrentDomain(); // Get the translated texts KeyStringList tt = StaticText.GetAll(domain.front_end_language, "id", "ASC"); // Check if the post request is valid if (user == null || collection == null) { return RedirectToAction("login", "user"); } // Get the form data Int32 post_id = Convert.ToInt32(collection["hiddenPostId"]); Int32 language_id = Convert.ToInt32(collection["hiddenLanguageId"]); decimal userVote = 0; decimal.TryParse(collection["userVote"], NumberStyles.Any, CultureInfo.InvariantCulture, out userVote); // Get the post Post post = Post.GetOneById(post_id, language_id); // Try to get a saved rating PostRating postRating = PostRating.GetOneById(post_id, user.id, language_id); // Add or update the rating if (postRating != null && postRating.administrator_id == user.id) { // Update values postRating.rating_date = DateTime.UtcNow; postRating.rating = userVote; // Update the rating PostRating.Update(postRating); } else { // Create a new rating postRating = new PostRating(); // Update values postRating.post_id = post_id; postRating.administrator_id = user.id; postRating.language_id = language_id; postRating.rating_date = DateTime.UtcNow; postRating.rating = userVote; // Add the rating PostRating.Add(postRating); } // Send a email to the administrator of the website string subject = tt.Get("rating") + " - " + domain.website_name; string message = tt.Get("post") + ": " + postRating.post_id.ToString() + "<br />" + tt.Get("language") + ": " + postRating.language_id.ToString() + "<br />" + tt.Get("user_name") + ": " + user.admin_user_name + "<br />" + tt.Get("rating") + ": " + postRating.rating.ToString(); Tools.SendEmailToHost("", subject, message); // Update the rating for the post Post.UpdateRating(postRating.post_id, postRating.language_id); // Redirect the user to the post return Redirect("/home/post/" + post.page_name + "#comments"); } // End of the edit_rating method
public ActionResult edit_rating(FormCollection collection) { // Make sure that the user is signed in Administrator user = Administrator.GetSignedInAdministrator(); // Get the current domain Domain domain = Tools.GetCurrentDomain(); // Get the translated texts KeyStringList tt = StaticText.GetAll(domain.front_end_language, "id", "ASC"); // Check if the post request is valid if (user == null || collection == null) { return RedirectToAction("login", "user"); } // Get the form data Int32 post_id = Convert.ToInt32(collection["hiddenPostId"]); Int32 language_id = Convert.ToInt32(collection["hiddenLanguageId"]); decimal userVote = 0; decimal.TryParse(collection["userVote"], NumberStyles.Any, CultureInfo.InvariantCulture, out userVote); // Get the post Post post = Post.GetOneById(post_id, language_id); // Try to get a saved rating PostRating postRating = PostRating.GetOneById(post_id, user.id, language_id); // Add or update the rating if (postRating != null && postRating.administrator_id == user.id) { // Update values postRating.rating_date = DateTime.UtcNow; postRating.rating = userVote; // Update the rating PostRating.Update(postRating); } else { // Create a new rating postRating = new PostRating(); // Update values postRating.post_id = post_id; postRating.administrator_id = user.id; postRating.language_id = language_id; postRating.rating_date = DateTime.UtcNow; postRating.rating = userVote; // Add the rating PostRating.Add(postRating); } // Send a email to the administrator of the website string subject = tt.Get("rating") + " - " + domain.website_name; string message = tt.Get("post") + ": " + postRating.post_id.ToString() + "<br />" + tt.Get("language") + ": " + postRating.language_id.ToString() + "<br />" + tt.Get("user_name") + ": " + user.admin_user_name + "<br />" + tt.Get("rating") + ": " + postRating.rating.ToString(); Tools.SendEmailToHost("", subject, message); // Update the rating for the post Post.UpdateRating(postRating.post_id, postRating.language_id); // Redirect the user to the post return Redirect("/home/post/" + post.page_name + "#comments"); } // End of the edit_rating method
public bool CanUndislike(string userId, Post post, PostRating usersRating = null) { var hasUndisliked = usersRating != null && usersRating.Type == PostRatingType.Dislike; return(post.AuthorId != userId && hasUndisliked); }
public bool CanUnlike(string userId, Post post, PostRating usersRating = null) { var hasLikedAllready = usersRating != null && usersRating.Type == PostRatingType.Like; return(post.AuthorId != userId && hasLikedAllready); }
public bool CanRate(string userId, Post post, PostRating usersRating = null) { return(post.AuthorId != userId && usersRating != null); }
public static PostRating Add(PostRating postRating) { postRating.Id = ratings.Count; ratings.Add(postRating); return(postRating); }
public void AddRating(PostRating rating) { context.PostsRating.Add(rating); }