public int Save(string Id) { var postId = int.Parse(Id); var ipAddress = Context.GetHttpContext().Request.HttpContext.Connection.RemoteIpAddress.ToString(); var Likes = _repository.GetByArticleId(postId); var liked = new ArticleLike { IPAddress = ipAddress, ArticleId = postId, UserLike = true }; var exist = Likes.FirstOrDefault(c => c.IPAddress == liked.IPAddress); if (exist == null) { _repository.Add(liked).Wait(); } else { exist.UserLike = !exist.UserLike; _repository.Update(exist).Wait(); } Likes = _repository.GetByArticleId(postId); return(Likes.Count(e => e.UserLike)); }
public async Task <IActionResult> PutArticleLike(int id, ArticleLike ArticleLike) { if (id != ArticleLike.Id) { return(BadRequest()); } _context.Entry(ArticleLike).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!ArticleLikeExists(id)) { return(NotFound()); } else { throw; } } return(NoContent()); }
protected void LikeControl_Like(object sender, LikeEventArgs e) { var articleData = this.data.Articles.Find(articleId); if (e.LikeValue) { ArticleLike like = new ArticleLike() { ArticleID = articleId, UserID = loggedUserId }; this.data.ArticleLikes.Add(like); } else { var currentUserLike = articleData.Likes.FirstOrDefault(l => l.UserID == loggedUserId); if (currentUserLike == null) { return; } this.data.ArticleLikes.Delete(currentUserLike); } this.data.SaveChanges(); var control = sender as Likes; control.Value = articleData.Likes.Count; control.UserVote = e.LikeValue; control.mustUpdate = true; }
public ActionResult DeleteConfirmed(int id) { ArticleLike articleLike = db.ArticleLikes.Find(id); db.ArticleLikes.Remove(articleLike); db.SaveChanges(); return(RedirectToAction("Index")); }
public ArticleLikeViewModel(ArticleLike like) { if (like != null) { ID = like.ID; Author = new UserViewModel(like.Author); } }
/// <summary> /// Likes the article specified by the <paramref name="like" /> in the database. /// </summary> /// <param name="like">The <see cref="ArticleLike"/>.</param> /// <returns> /// A <see cref="Task" /> that represents the asynchronous operation. /// </returns> public async Task LikeArticleAsync(ArticleLike like) { if (like == null) { throw new ArgumentNullException("like"); } _context.ArticleLikes.Add(like); await _context.SaveChangesAsync(); }
public void LikeSave(int id, string email) { ArticleLike articleLike = new ArticleLike(); articleLike.Email = email; articleLike.Article_Id = id; articleLike.Dislike = false; articleLike.Like = true; _db.ArticleLikes.Add(articleLike); _db.SaveChanges(); }
public void AddLike(ArticleLike like) { var index = like.ArticleId; if (Articles[index].Likes == null) { Articles[index].Likes = new List <ArticleLike>(); } Articles[index].Likes.Add(like); }
public ActionResult Edit([Bind(Include = "id,ArticleId,DateTime,UserId,IP")] ArticleLike articleLike) { if (ModelState.IsValid) { db.Entry(articleLike).State = EntityState.Modified; db.SaveChanges(); return(RedirectToAction("Index")); } ViewBag.ArticleId = new SelectList(db.articles, "id", "title", articleLike.ArticleId); ViewBag.UserId = new SelectList(db.Users, "id", "Name", articleLike.UserId); return(View(articleLike)); }
public void GetArticleById_ReturnValue() { var like = new ArticleLike { Id = 1, Article_Id = 2, Dislike = false, Email = "*****@*****.**", Like = true }; _articleLikeRepositoryMock.Setup(a => a.Get(like.Id, like.Email)).Returns(like); var result = _service.Get(like.Id, like.Email).Id; NUnit.Framework.Assert.AreEqual(1, result); }
public ArticleLike IsArticleDisliked(int id, string email) { ArticleLike articleLike = new ArticleLike() { Article_Id = id, Email = email, Dislike = true, Like = false, }; _articleLikeRepository.SaveLikeDislike(articleLike); return(articleLike); }
// GET: ArticleLike/Details/5 public ActionResult Details(int?id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } ArticleLike articleLike = db.ArticleLikes.Find(id); if (articleLike == null) { return(HttpNotFound()); } return(View(articleLike)); }
public JsonResult LikeArticle(int articleID) { //prevent anonymous users from liking var username = HttpContext.Session.GetString("SessionKeyEmail"); if (String.IsNullOrWhiteSpace(username)) { return(Json(new { result = false, errorMessage = "Please login first!" })); } //check if user liked before? var isLiked = _context.ArticleLike.Where(a => a.ArticleID == articleID && a.EmployeeEmail == username && a.Like == true).Any(); if (isLiked) { return(Json(new { result = false, errorMessage = "You have already liked this article!" })); } //exists check: maybe commented but not liked before var articleLike = _context.ArticleLike.Where(a => a.ArticleID == articleID && a.EmployeeEmail == username).FirstOrDefault(); if (articleLike != null) { articleLike.Like = true; //update database _context.Update(articleLike); _context.SaveChanges(); } else { //create new record for ArticleLike table ArticleLike entity = new ArticleLike { ArticleID = articleID, EmployeeEmail = username, Like = true, Comment = null }; //update database _context.ArticleLike.Add(entity); _context.SaveChanges(); } //return success message return(Json(new { result = true })); }
public async Task <Tuple <bool, string> > UnlikeArticle(ArticleLike articleLike) { _appContext.ArticleLikes.Remove(articleLike); try { await _appContext.SaveChangesAsync(); } catch (DbUpdateException e) { return(Tuple.Create(false, e.Message)); } return(Tuple.Create(true, string.Empty)); }
// GET: ArticleLike/Edit/5 public ActionResult Edit(int?id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } ArticleLike articleLike = db.ArticleLikes.Find(id); if (articleLike == null) { return(HttpNotFound()); } ViewBag.ArticleId = new SelectList(db.articles, "id", "title", articleLike.ArticleId); ViewBag.UserId = new SelectList(db.Users, "id", "Name", articleLike.UserId); return(View(articleLike)); }
public IActionResult LikeArticle(long id) { var article = ArticleService.Get(id); if (article == null) { return(NotFound(new ResponseModel { Success = false, Message = "Статья не найдена" })); } User user = null; if (User.Identity.Name != null) { user = UserService.Get(long.Parse(User.Identity.Name)); } if (user == null) { return(NotFound(new ResponseModel { Success = false, Message = "Пользователь не найден" })); } var like = ArticleLikeService.GetAll() .FirstOrDefault(x => x.Article == article && x.Author == user); if (like != null) { ArticleLikeService.Delete(like); } else { ArticleLikeService.Create(like = new ArticleLike { Article = article, Author = user }); } return(Ok(new ResponseModel())); }
public void GivenALikeIsClicked_AddLike_AddsLikeToArticleInArticleList() { var like = new ArticleLike { ArticleId = 1 }; var articles = new List <Article>() { _article0, _article1 }; var expected = articles[1].Likes.Count; _controller.AddLike(like); var actualArticles = _controller.GetArticles(); var actual = actualArticles[1].Likes.Count; Assert.AreEqual(expected, actual); }
//[Route("articles/like/{aritcleId}")] public ActionResult Like(int?articleId) { if (!User.Identity.IsAuthenticated) { Response.StatusCode = 403; return(Json(new { Message = "You must log in to be able to like." })); } bool success = false; string message = string.Empty; if (articleId == null) { message = "You have passed an invalid article."; } else { bool likedBefore = IsArticleLikedBefore(articleId.Value); if (!likedBefore) { bool likeNumberExceeded = IsArticleLikeCountExceededForUser(); if (!likeNumberExceeded) { ArticleLike newLike = db.Likes.Create(); newLike.ArticleId = articleId.Value; newLike.UserId = User.Identity.Name; newLike.Date = DateTime.Now; db.Likes.Add(newLike); db.SaveChanges(); success = true; } else { message = "You have exceeded total number of likesfor today"; } } else { message = "You have liked this article before"; } } return(Json(new { Success = success, Message = message }, JsonRequestBehavior.AllowGet)); }
public async Task <int> insertAsync(ArticleLike data) { try { var like = new ArticleLike { ArticleID = data.ArticleID, UserCreated = data.UserCreated }; await _context.ArticleLikes.AddAsync(like); await _context.SaveChangesAsync(); return(like.ID); } catch (Exception ex) { throw ex; } }
public async Task <ActionResult <ArticleLike> > PostArticleLike([FromBody] ArticleLikeViewModel vm) { ArticleLike like = new ArticleLike(); var userId = User.FindFirst(ClaimTypes.NameIdentifier).Value; var user = _context.Users.Find(userId); like.User = user; like.Article = _context.Articles.Find(vm.ArticleId); like.LikeDateTime = DateTime.Now; if (_context.ArticleLikes.Where(x => x.User == user && x.Article == like.Article).Count() == 0) { _context.ArticleLikes.Add(like); } else { _context.ArticleLikes.RemoveRange(_context.ArticleLikes.Where(x => x.User == user && x.Article == like.Article).ToList()); } await _context.SaveChangesAsync(); return(CreatedAtAction("GetArticleLike", new { id = like.Id }, like)); }
public async Task Post([FromBody] Article article) { var userId = Guid.Parse(User.Claims.Single(c => c.Type == ClaimTypes.NameIdentifier).Value); var user = new DummyUser(); user.Id = userId; _db.Article.Attach(article); _db.Users.Attach(user); if (_db.ArticleLike.Any(al => al.Article.Id == article.Id && al.User.Id == userId)) { return; } var articleLike = new ArticleLike { Article = article, User = user, DateCreated = DateTime.UtcNow }; _db.ArticleLike.Add(articleLike); await _db.SaveChangesAsync(); }
public ArticleLikeDto AddLike(ArticleLikeInput input) { ArticleLike articleLike = ArticleManager.AddLike(InfrastructureSession.UserId.Value, input.Id, input.LikeType); return(articleLike.MapTo <ArticleLikeDto>()); }
public static async Task Initialize(IServiceProvider provider) { var context = provider.GetRequiredService <ApplicationDbContext>(); await context.Database.EnsureCreatedAsync(); var userManager = provider.GetRequiredService <UserManager <ApplicationUser> >(); var roleManager = provider.GetRequiredService <RoleManager <IdentityRole> >(); // Create Publisher Role : if (!await roleManager.RoleExistsAsync("Publisher")) { var publisherRole = new IdentityRole("Publisher"); await roleManager.CreateAsync(publisherRole); } // Create Reader Role : if (!await roleManager.RoleExistsAsync("Reader")) { var readerRole = new IdentityRole("Reader"); await roleManager.CreateAsync(readerRole); } // Create User Scott Pressfor (Publisher) : const string email1 = "*****@*****.**"; if (await userManager.FindByEmailAsync(email1) == null) { var user = new ApplicationUser() { UserName = email1, Email = email1, FirstName = "Scott", LastName = "Pressford", MaxLikesCount = 3, SecurityStamp = Guid.NewGuid().ToString() }; var result = await userManager.CreateAsync(user, "Password2018!"); if (result.Succeeded && !await userManager.IsInRoleAsync(user, "Publisher")) { await userManager.AddToRoleAsync(user, "Publisher"); } } // Create User Alan Turing (Reader) : const string email2 = "*****@*****.**"; if (await userManager.FindByEmailAsync(email2) == null) { var user = new ApplicationUser() { UserName = email2, Email = email2, FirstName = "Alan", LastName = "Turing", MaxLikesCount = 3, SecurityStamp = Guid.NewGuid().ToString() }; var result = await userManager.CreateAsync(user, "Password2018!"); if (result.Succeeded && !await userManager.IsInRoleAsync(user, "Reader")) { await userManager.AddToRoleAsync(user, "Reader"); } } // Create Articles + Likes + Comments : if (context.Articles.Any()) { return; } // Article 1 { var article = new Article() { Title = "A humanist approach to teaching kids", Author = await userManager.FindByEmailAsync(email1), CreationDate = new DateTime(2018, 03, 13) }; article.Body = Pressford.Properties.Resources.ArticleHtml1; await context.Articles.AddAsync(article); await context.SaveChangesAsync(); var alanTuring = await userManager.FindByEmailAsync("*****@*****.**"); var comment = new ArticleComment() { Article = article, Commenter = alanTuring, Text = "Great article !! Thanks for sharing !", TimeStamp = DateTime.Now }; await context.ArticleComments.AddAsync(comment); await context.SaveChangesAsync(); var like = new ArticleLike() { Article = article, Liker = alanTuring, TimeStamp = DateTime.UtcNow }; await context.ArticleLikes.AddAsync(like); await context.SaveChangesAsync(); } // Article 2 { var article = new Article() { Title = "5 amazing books I read this year", Author = await userManager.FindByEmailAsync(email1), CreationDate = new DateTime(2017, 12, 04) }; article.Body = Pressford.Properties.Resources.ArticleHtml2; await context.Articles.AddAsync(article); await context.SaveChangesAsync(); var alanTuring = await userManager.FindByEmailAsync("*****@*****.**"); var comment = new ArticleComment() { Article = article, Commenter = alanTuring, Text = "Great article again !! Thanks for sharing !", TimeStamp = DateTime.Now }; await context.ArticleComments.AddAsync(comment); await context.SaveChangesAsync(); var like = new ArticleLike() { Article = article, Liker = alanTuring, TimeStamp = DateTime.UtcNow }; await context.ArticleLikes.AddAsync(like); await context.SaveChangesAsync(); } // Article 3 { var article = new Article() { Title = "Strength in Numbers", Author = await userManager.FindByEmailAsync(email1), CreationDate = new DateTime(2018, 04, 18) }; article.Body = Pressford.Properties.Resources.ArticleHtml3; await context.Articles.AddAsync(article); await context.SaveChangesAsync(); var alanTuring = await userManager.FindByEmailAsync("*****@*****.**"); var comment = new ArticleComment() { Article = article, Commenter = alanTuring, Text = "Wonderful !! Thanks for sharing !", TimeStamp = DateTime.Now }; await context.ArticleComments.AddAsync(comment); await context.SaveChangesAsync(); var like = new ArticleLike() { Article = article, Liker = alanTuring, TimeStamp = DateTime.UtcNow }; await context.ArticleLikes.AddAsync(like); await context.SaveChangesAsync(); } }
public ActionResult CreateLike(ArticleLike like) { AddLike(like); return(RedirectToAction("Index")); }
public ArticleLike SaveLikeDislike(ArticleLike articleLike) { _db.ArticleLikes.Add(articleLike); _db.SaveChanges(); return(articleLike); }