Beispiel #1
0
        public Dictionary <int, List <PostLikes> > GetPostLikesByPostIds(int[] ids)
        {
            List <PostLikes> likes = new List <PostLikes>();

            dataProvider.ExecuteCmd(
                "PostLikes_GetByPostIds",
                inputParamMapper: parameters =>
            {
                parameters.AddWithValue("@IdsJSON", JsonConvert.SerializeObject(ids));
            },
                singleRecordMapper: (reader, resultSetMapper) =>
            {
                PostLikes like = new PostLikes();

                like.Id     = (int)reader["Id"];
                like.PostId = (int)reader["PostId"];
                like.UserId = (int)reader["UserId"];

                likes.Add(like);
            });

            var likesDict = likes
                            .ToLookup(postLike => postLike.PostId)
                            .ToDictionary(
                o => o.Key,
                o => o.ToList()
                );

            return(likesDict);
        }
Beispiel #2
0
 public IActionResult AddImageLike([FromBody] PostLikes like)
 {
     try
     {
         return(Ok(_likesService.AddImageLike(like)));
     }
     catch (NegotiatedContentResultException)
     {
         return(StatusCode(409));
     }
 }
Beispiel #3
0
        public async Task <IActionResult> Create(PostLikes postLikes)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }

            var isCreated = await postLikesRepo.Create(postLikes);

            return(Ok(new { isCreated }));
        }
Beispiel #4
0
 public PostLikes AddImageLike(PostLikes like)
 {
     using (var db = _paintStoreContext)
     {
         if ((db.PostLikes.Any(x => x.PostId == like.PostId && x.UserId == like.UserId)))
         {
             throw new NegotiatedContentResultException();
         }
         ImagesManager.ImageLikesCountPlus(db, like.PostId);
         db.PostLikes.Add(like);
         db.SaveChanges();
         return(like);
     }
 }
Beispiel #5
0
        public ActionResult ToggleLike(int Id)
        {
            CampaignMainViewModel Model = new CampaignMainViewModel();

            if (Id > 0)
            {
                Model = IService.GetCamapign(Id);
                PostLikes pstcmt = new PostLikes();
                pstcmt.Id      = Id;
                pstcmt.isLiked = !(Model.isLiked);
                Model          = IService.ToggleLikes(pstcmt);
            }
            return(PartialView("_Like", Model));
        }
        public async Task <bool> Create(PostLikes postLikes)
        {
            var isCreated = false;

            try
            {
                await _context.PostLikes.AddAsync(postLikes);

                await _context.SaveChangesAsync();

                isCreated = true;
            }
            catch (Exception)
            {
            }

            return(isCreated);
        }
Beispiel #7
0
        public async Task <IActionResult> Like(int id = 0)
        {
            var post = dbContext.Posts.Find(id);

            if (post != null)
            {
                var user = await _userManager.GetUserAsync(User);

                bool isLiked = dbContext.PostLikes.Any(p => p.PostId == id && p.UserId == user.Id);
                if (!isLiked)
                {
                    PostLikes like = new PostLikes()
                    {
                        PostId = id,
                        UserId = user.Id
                    };
                    dbContext.PostLikes.Add(like);
                    await dbContext.SaveChangesAsync();
                }
            }
            return(RedirectToAction("Profile"));
        }
        public ActionResult LikePost(int? id)
        {
            if (id == null) return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            var post = _db.PostById((int)id);
            
            var user = GetUserModel();
            var isLiked = _db.PostLikes.Where(e => e.UserId == user.Id).FirstOrDefault(e => e.PostID == id);
            if (isLiked != null)
            {
                    _db.PostLikes.Attach(isLiked);
                    _db.Entry(isLiked).State = EntityState.Deleted;
                    _db.SaveChanges();
                    //NotificationRepository repo=new NotificationRepository();
                    //repo.AddNotification(post.UserId,user.UserFirstName+ " " + user.UserSurname +" gönderini beğendi");
                    return Json(new { success = true,liked = false, likes = _db.PostById((int)id).PostLikes.Count }, JsonRequestBehavior.AllowGet);
                }
            var postLike = new PostLikes
            {
                UserId = user.Id,
                PostID = (int) id,
                IsLiked = true
            };

            try
            {
                using (var context = new ScoutUpDB())
                {
                    context.PostLikes.Add(postLike);
                    context.UsersLastMoves.Add(new UsersLastMoves { MoveDate = DateTime.Now, UserId = user.Id, UsersLastMoveText =" bir gönderiyi beğendi.", UsersMoveLink = "/users/index/" + post.UserId + "#post" + post.PostID });
                    context.SaveChanges();
                    return Json(new { success = true,liked=true,likes =context.PostById((int)id).PostLikes.Count },JsonRequestBehavior.AllowGet);
                }
            }
            catch (Exception ex)
            {

                return Json(new { success = false, error = true, message = ex.InnerException.ToString() },JsonRequestBehavior.AllowGet);
            }
        }
        public ActionResult Like(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            else
            {
                var userid = User.Identity.GetUserId();
                var post   = mydatabase.PostsUserManager.GetById(id);

                if (post.NoOfLikes == 0)
                {
                    PostLikes like = new PostLikes
                    {
                        LikeOwnerId = userid,
                        PostId      = (int)id,
                        Posts       = post
                    };

                    mydatabase.PostsUserManager.GetById(id).NoOfLikes++;
                    mydatabase.PostLikesUserManager.Add(like);


                    //db.SaveChanges();
                }
                else
                {
                    //


                    if ((mydatabase.PostLikesUserManager.GetAll().Where(i => i.PostId == id && i.LikeOwnerId == userid).ToList()).Count == 0)
                    {
                        PostLikes like = new PostLikes
                        {
                            LikeOwnerId = userid,
                            PostId      = (int)id,
                            Posts       = post
                        };
                        mydatabase.PostsUserManager.GetById(id).NoOfLikes++;
                        mydatabase.PostLikesUserManager.Add(like);


                        //db.SaveChanges();
                    }
                }
            }


            Posts posttoget = mydatabase.PostsUserManager.GetById(id);

            string postuserid = posttoget.OwnerId;
            string fname      = UserManager.Users.Where(i => i.Id == postuserid).FirstOrDefault().Fname;
            string lname      = UserManager.Users.Where(i => i.Id == postuserid).FirstOrDefault().Lname;
            string username   = string.Format("{0} {1}", fname, lname);
            PostDetailViewModel myviewmodel = new PostDetailViewModel
            {
                username = username,
                post     = mydatabase.PostsUserManager.GetById(id),

                comments = mydatabase.CommentsUserManager.GetAll().Where(i => i.PostId == id).ToList(),

                posttext = mydatabase.PostsTextsUserManager.GetAll().Where(i => i.PostId == id).FirstOrDefault()
                ,
                Commentators = new Dictionary <int, string>()
            };

            foreach (Comments comment in myviewmodel.comments)
            {
                string commentuserid       = comment.OwnerId;
                string commentatorfname    = UserManager.Users.Where(i => i.Id == commentuserid).FirstOrDefault().Fname;
                string commentatorlname    = UserManager.Users.Where(i => i.Id == commentuserid).FirstOrDefault().Lname;
                string commentatorusername = string.Format("{0} {1}", commentatorfname, commentatorlname);
                myviewmodel.Commentators.Add(comment.Id, commentatorusername);
            }

            return(PartialView("_PartialShowonepost", myviewmodel));
        }
Beispiel #10
0
    /// <summary>
    /// The proccess itself, gets likes and comments from Facebook
    /// </summary>
    public static void processMissions()
    {
        MySqlDataReader             dr;
        MySqlCommand                CMD        = new MySqlCommand();
        int                         proccessID = 0;
        List <ThreadingMissionPost> List_Posts = new List <ThreadingMissionPost>();

        using (MySqlConnection con = new MySqlConnection(siteDefaults.ConnStr))
        {
            con.Open();
            CMD.Connection = con;

            //INSERTS NEW PROCCESS TIMESTAMP
            CMD.CommandText = string.Format("INSERT into ThreadsRecord (ThreadStartedAt) VALUES ('{0}');", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            CMD.ExecuteNonQuery();
            CMD.CommandText = "SELECT @@identity AS myID";
            dr = CMD.ExecuteReader();
            if (dr.Read())
            {
                proccessID = int.Parse(dr["myID"].ToString());
            }
            dr.Close();

            CMD.CommandText = "SELECT tblposts2missions.*, tblusers.LoginTypeToken as UserTokenAccess FROM israelikedb.tblposts2missions left join tblusers on tblusers.EmailAddress= tblposts2missions.UserMail where Platform = 'FB' AND FBResponsePostID is not null and (UserMail is not null AND usermail != '');";
            dr = CMD.ExecuteReader();
            while (dr.Read())
            {
                ThreadingMissionPost TmpPost = new ThreadingMissionPost();
                TmpPost.MissionPostID   = dr["MissionPostID"].ToString();
                TmpPost.UserMail        = dr["UserMail"].ToString();
                TmpPost.MissionID       = int.Parse(dr["MissionID"].ToString());
                TmpPost.MissionGUID     = dr["MissionName"].ToString();
                TmpPost.FBUserID        = dr["FBResponseID"].ToString();
                TmpPost.FB_ShareID      = dr["FBResponsePostID"].ToString();
                TmpPost.ShareLikes      = int.Parse(dr["TotalpostLikes"].ToString());
                TmpPost.ShareComments   = int.Parse(dr["TotlaPostComments"].ToString());
                TmpPost.UserTokenAccess = dr["UserTokenAccess"].ToString();
                List_Posts.Add(TmpPost);
            }
            dr.Close();
            con.Close();
        }
        try
        {
            foreach (var item in List_Posts)
            {
                //GET NUMBER OF LIKES!
                HttpWebRequest webRequest = (HttpWebRequest)System.Net.WebRequest.Create("https://graph.facebook.com/" + item.FB_ShareID + "/likes?access_token=" + siteDefaults.MyAppToken + "&summary=true"); //setting an httpWebRequest with the URL of the API
                webRequest.Method      = "GET";                                                                                                                                                                 //the type of method the API returns
                webRequest.Timeout     = 70000;                                                                                                                                                                 //sets the timeout for thew request
                webRequest.ContentType = "application/x-www-form-urlencoded";                                                                                                                                   //the content type. most of the times it will be application/x-www-form-urlencoded
                StreamReader MyStream     = new StreamReader(webRequest.GetResponse().GetResponseStream());                                                                                                     //creating a stream reader to read the results from the API
                string       responseData = MyStream.ReadToEnd();                                                                                                                                               //reading the result from the API into a string
                System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();                                                                   //creating a JSON deserializer JSON.
                PostLikes TmpPostInfo = serializer.Deserialize <PostLikes>(responseData);                                                                                                                       //De-serealization of the string into an array of pre-defined objects
                if (TmpPostInfo != null && TmpPostInfo.summary != null)
                {
                    item.ShareLikes = TmpPostInfo.summary.total_count;
                }

                //GET NUMBER OF COMMENTS!
                webRequest   = (HttpWebRequest)System.Net.WebRequest.Create("https://graph.facebook.com/" + item.FB_ShareID + "/comments?access_token=" + siteDefaults.MyAppToken + "&summary=true"); //setting an httpWebRequest with the URL of the API
                MyStream     = new StreamReader(webRequest.GetResponse().GetResponseStream());                                                                                                        //creating a stream reader to read the results from the API
                responseData = MyStream.ReadToEnd();                                                                                                                                                  //reading the result from the API into a string
                serializer   = new System.Web.Script.Serialization.JavaScriptSerializer();                                                                                                            //creating a JSON deserializer JSON.
                TmpPostInfo  = serializer.Deserialize <PostLikes>(responseData);                                                                                                                      //De-serealization of the string into an array of pre-defined objects
                if (TmpPostInfo != null && TmpPostInfo.summary != null)
                {
                    item.ShareComments = TmpPostInfo.summary.total_count;
                }
            }
        }
        catch (Exception ex)
        {
            using (MySqlConnection con = new MySqlConnection(siteDefaults.ConnStr))
            {
                CMD.Connection = con;
                con.Open();
                CMD.CommandText = string.Format("update ThreadsRecord SET ExceptionDetails='{0}' where idthreadsrecord='{1}'", ex.Message, proccessID);
                CMD.ExecuteNonQuery();
                con.Close();
            }
        }
        using (MySqlConnection con = new MySqlConnection(siteDefaults.ConnStr))
        {
            CMD.Connection = con;
            con.Open();

            //UPDATE DATABASE WITH RESULTS!
            List_Posts.ForEach(p =>
            {
                CMD.CommandText = string.Format("UPDATE tblposts2missions set TotalpostLikes={0},TotlaPostComments={1},LastprocessUpdate=now() where MissionPostID = {2}", p.ShareLikes, p.ShareComments, p.MissionPostID);
                CMD.ExecuteNonQuery();
            });

            // UPDATES PROCCESS ENDING TIMESTAMP
            CMD.CommandText = string.Format("update ThreadsRecord SET ThreadEndedAt='{0}' where idthreadsrecord={1};", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), proccessID);
            CMD.ExecuteNonQuery();

            con.Close();
        }
    }
Beispiel #11
0
        private LikePost SaveLike(int?postid, string userid)
        {
            var post = _db.Posts.Find(postid);

            var user    = _db.Users.Find(userid);
            var isLiked = _db.PostLikes.Where(e => e.UserId == user.Id).FirstOrDefault(e => e.PostID == postid);

            if (isLiked != null)
            {
                using (var context = new ScoutUpDB())
                {
                    _db.Dispose();

                    context.PostLikes.Attach(isLiked);
                    context.Entry(isLiked).State = EntityState.Deleted;
                    context.SaveChanges();
                    return(new LikePost
                    {
                        LikeCount = post.PostLikes.Count,
                        Liked = false,
                        PostId = (int)postid
                    });
                }
            }

            var postLike = new PostLikes
            {
                UserId  = user.Id,
                PostID  = (int)postid,
                IsLiked = true
            };

            try
            {
                using (var context = new ScoutUpDB())
                {
                    context.PostLikes.Add(postLike);
                    context.UsersLastMoves.Add(new UsersLastMoves {
                        MoveDate = DateTime.Now, UserId = user.Id, UsersLastMoveText = " bir gönderiyi beğendi.", UsersMoveLink = "/users/index/" + post.UserId + "#post" + post.PostID
                    });
                    context.SaveChanges();
                    return(new LikePost
                    {
                        LikeCount = post.PostLikes.Count,
                        Liked = true
                        , PostId = (int)postid
                    });
                }
            }
            catch (Exception ex)
            {
                return(new LikePost
                {
                    LikeCount = post.PostLikes.Count,
                    Liked = false
                });
            }
            //    var postId = int.Parse(id);
            //    var baseContext = Context.Request.GetHttpContext();
            //    var postRepository = _db;
            //    var item = _db.Posts.Find(postId);
            //    var liked = new PostLike
            //    {
            //        IPAddress = baseContext.Request.UserHostAddress,
            //        PostId = item.Id,
            //        UserAgent = baseContext.Request.UserAgent,
            //        UserLike = true
            //    };
            //    var dupe = item.PostLikes.FirstOrDefault(e => e.IPAddress == liked.IPAddress);
            //    if (dupe == null)
            //    {
            //        item.PostLikes.Add(liked);
            //    }
            //    else
            //    {
            //        dupe.UserLike = !dupe.UserLike;
            //    }
            //    postRepository.SaveChanges();
            //    var post = postRepository.GetById(postId);

            //    return new LikePost
            //    {
            //        LikeCount = post.PostLikes.Count(e => e.UserLike)
            //    };
            //}
        }