//离线
 public int CompareToOffLine(UserFriend a1, UserFriend a2)
 {
     /* 2.按照可领取体力分
     * 3.按照登陆时间分
     * 4.按照卡牌星级分*/
     if (a1.canGetPower != a2.canGetPower)
     {
         return(a2.canGetPower.CompareTo(a1.canGetPower));
     }
     else if (a1.lastLogoutHours != a2.lastLogoutHours)
     {
         return(-1 * a2.lastLogoutHours.CompareTo(a1.lastLogoutHours));
     }
     else
     {
         if (a2.cardTempletID > 0 && a1.cardTempletID > 0)
         {
             return(TableManager.GetCardByID(a2.cardTempletID).Star.CompareTo(TableManager.GetCardByID(a1.cardTempletID).Star));
         }
         else
         {
             return(0);
         }
         //return  .CompareTo(cardA.templateID);
     }
 }
Exemplo n.º 2
0
        public override async Task <string> HandleAsync(Message message, TymDbContext db)
        {
            var reply      = new StringBuilder();
            var userId     = message.From.Id;
            var fromUserId = message.ReplyToMessage?.From.Id;

            if (fromUserId == null)
            {
                reply.AppendLine("Reply to a message using /friend command.");
            }
            else
            {
                var userFriend = await db.UserFriends
                                 .Where(f => f.UserId == userId && f.FriendId == fromUserId)
                                 .FirstOrDefaultAsync();

                if (userFriend == null)
                {
                    userFriend = new UserFriend()
                    {
                        FriendId = fromUserId.Value,
                        UserId   = userId,
                    };
                    db.UserFriends.Add(userFriend);
                    await db.SaveChangesAsync();

                    reply.AppendLine($"{message.ReplyToMessage.From.FirstName} can now see your time.");
                }
            }

            return(reply.ToString());
        }
Exemplo n.º 3
0
        public async Task <IActionResult> FriendToggle(string friendId, string refferer)
        {
            var curUserId = _userManager.GetUserId(HttpContext.User);
            var curUser   = _dbContext.Users.Include(x => x.Friends).FirstOrDefault(x => x.Id == curUserId);

            if (curUser == null)
            {
                return(NotFound());
            }
            var actualFriend = await _dbContext.Users.FirstOrDefaultAsync(x => x.Id == friendId);

            if (actualFriend == null)
            {
                return(NotFound());
            }
            var friend = new UserFriend {
                Friend = actualFriend, FriendId = actualFriend.Id, User = curUser, UserId = curUserId
            };
            var hest = new UserFriend {
                User = actualFriend, UserId = actualFriend.Id, Friend = curUser, FriendId = curUserId
            };

            if (!curUser.Friends.Contains(friend))
            {
                curUser.Friends.Add(friend);
                actualFriend.Friends.Add(hest);
                await _dbContext.SaveChangesAsync();
            }
            return(RedirectToAction(refferer));
        }
Exemplo n.º 4
0
        public void CallUserFriendRepository_AddOnce()
        {
            // Arrange
            var mockedUserFriendRepository = new Mock <IEFRepository <UserFriend> >();
            var mockedUserRepository       = new Mock <IEFRepository <CustomUser> >();
            var mockedUserFriendFactory    = new Mock <IUserFriendFactory>();
            var friendShip = new UserFriend();

            mockedUserFriendFactory
            .Setup(
                x => x.CreateUserFriend(
                    It.IsAny <int>(),
                    It.IsAny <string>(),
                    It.IsAny <int>()))
            .Returns(friendShip);
            var mockedUnitOfWork = new Mock <IUnitOfWork>();

            var friendService = new FriendService(
                mockedUserFriendRepository.Object,
                mockedUserRepository.Object,
                mockedUserFriendFactory.Object,
                mockedUnitOfWork.Object);
            int    userId           = 10;
            string friendIdentityId = "friend-xx-id";
            int    friendId         = 50;

            // Act
            friendService.AddFriendship(userId, friendIdentityId, friendId);

            // Assert
            mockedUserFriendRepository.Verify(x => x.Add(It.Is <UserFriend>(u => u == friendShip)), Times.Once);
        }
        public async Task <UserFriend> GetExistingRequest(UserFriend userFriend, Guid?userId = null,
                                                          bool noTracking = true)
        {
            var uf = await Repository.GetExistingRequest(userFriend, userId, noTracking);

            return(Mapper.Map(uf));
        }
Exemplo n.º 6
0
        public void AddFriend(string friend) //Sayfasına girdiğim kişinin username ni alıp gerekli işlemlerin yapıldığı alan
        {
            Users user = userService.GetBy(x => x.Username == sessionname);

            int userId = user.Id; //Login Olan Kişinin Idsi



            Users user2    = userService.GetBy(x => x.Username == friend); //Sayfasına girilen kişinin ıdsi yani furkan
            int   friendId = user2.Id;


            UserFriend userFriend = new UserFriend()
            {
                UserId    = userId,
                FriendId  = friendId,
                Active    = false,
                Engelle   = false,
                IsDeleted = false
            };



            userFriendService.Add(userFriend);
        }
Exemplo n.º 7
0
        public void FindChangedCache()
        {
            var        watch  = Stopwatch.StartNew();
            int        userId = 1001;
            var        cache  = new PersonalCacheStruct <UserFriend>();
            UserFriend Jim    = cache.FindKey(userId.ToString());

            if (Jim == null)
            {
                Jim = new UserFriend()
                {
                    UserId = userId, Friends2 = new CacheList <FriendsData>()
                };
                Jim.Friends2.Add(new FriendsData()
                {
                    UserId = 1000
                });
                Assert.IsTrue(cache.AddOrUpdate(Jim));
            }
            else
            {
                Assert.IsFalse(Jim.HasChanged);
                Assert.IsTrue(Jim.IsInCache);
            }

            foreach (var f in Jim.Friends2)
            {
                f.Num++;
            }

            Assert.IsTrue(Jim.HasChanged);
            Assert.IsTrue(Jim.IsInCache);
            WaitEnd(watch);
        }
Exemplo n.º 8
0
        public async Task AcceptInvite(User user, User accept)
        {
            if (accept == null)
            {
                throw new NotFoundException("Usuário não existe.");
            }

            var accepted = await _context.UserPendings
                           .Include(x => x.User)
                           .Include(x => x.Pending)
                           .FirstOrDefaultAsync(x => CompareIds(user.Id, x.User.Id) && CompareIds(accept.Id, x.Pending.Id));

            if (accepted == null)
            {
                throw new NotFoundException("Não há convites relacionado ao usuário informado.");
            }

            _context.UserPendings.Remove(accepted);

            var userFriendship = new UserFriend {
                User = user, Friend = accept
            };
            var acceptFriendship = new UserFriend {
                User = accept, Friend = user
            };

            await _context.UserFriends.AddAsync(userFriendship);

            await _context.UserFriends.AddAsync(acceptFriendship);

            await _context.SaveChangesAsync();
        }
        public List <UserFriend> GetWaitingUserFriends(int id)
        {
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                SqlCommand command = new SqlCommand(UserQueries.GetWatingFriends(id), connection);
                connection.Open();
                try
                {
                    List <UserFriend> friends = new List <UserFriend>();

                    using (SqlDataReader reader = command.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            UserFriend uf = new UserFriend();
                            uf.User    = GetUser((int)reader["friend"]);
                            uf.Pending = (bool)reader["pending"];
                            friends.Add(uf);
                        }
                    }
                    return(friends);
                }
                catch (SqlException e)
                {
                    throw e;
                }
            }
        }
Exemplo n.º 10
0
        public UserProfile SetAdditionalSettingsForProfile(UserProfile profile, int loginUserId)
        {
            UserFriend friend = _context.UserFriends.FirstOrDefault(x =>
                                                                    (x.IdUser == profile.UserId && x.IdUserToFriendList == loginUserId) ||
                                                                    (x.IdUser == loginUserId && x.IdUserToFriendList == profile.UserId));
            UserBlacklist blackList = _context.UserBlacklists.FirstOrDefault(x =>
                                                                             (x.IdUser == profile.UserId && x.IdUserToBlackList == loginUserId) ||
                                                                             (x.IdUser == loginUserId && x.IdUserToBlackList == profile.UserId));

            if (friend != null)
            {
                if (friend.RequestAccepted)
                {
                    profile.AreFriends = true;
                }
                else
                {
                    profile.FriendRequestSend = true;
                }
            }

            if (blackList != null)
            {
                profile.IsBlocked = false;
            }

            if (_context.UsersFollowings.Any(x => x.IdUser == loginUserId && x.IdUserToFollow == profile.UserId))
            {
                profile.IsFollowing = true;
            }

            return(profile);
        }
Exemplo n.º 11
0
        /// <summary>
        /// 建立好友关系
        /// </summary>
        /// <param name="model">建立好友模型</param>
        private void CreateFriendRelationShip(NewFriendRelationShipModel model)
        {
            IRepository <UserFriend> friendRep = Factory.Factory <IRepository <UserFriend> > .GetConcrete <UserFriend>();

            IRepository <ShortMessage> smRep = Factory.Factory <IRepository <ShortMessage> > .GetConcrete <ShortMessage>();

            IRepository <UserProperty> propertyRep = Factory.Factory <IRepository <UserProperty> > .GetConcrete <UserProperty>();

            //新建好友关系
            UserFriend uf1 = new UserFriend(model.RequestUser.UserID, model.ReciveUser.UserID, model.ReciveUser.UserName, model.ReciveUser.UserTiny);
            UserFriend uf2 = new UserFriend(model.ReciveUser.UserID, model.RequestUser.UserID, model.RequestUser.UserName, model.RequestUser.UserTiny);

            //加入仓库
            friendRep.Add(uf1);
            friendRep.Add(uf2);

            //需要添加各自的好友数
            UserProperty requestUser = propertyRep.Find(new Specification <UserProperty>(up => up.UserID == model.RequestUser.UserID));
            UserProperty receiveUser = propertyRep.Find(new Specification <UserProperty>(up => up.UserID == model.ReciveUser.UserID));

            //添加好友数
            requestUser.AddFriendsCount();
            receiveUser.AddFriendsCount();
            //更新数据
            propertyRep.Update(requestUser);
            propertyRep.Update(receiveUser);

            //好友关系持久化
            friendRep.PersistAll();

            //好友数量持久化
            propertyRep.PersistAll();
        }
        public async Task <UserFriend> SendFriendRequest(UserFriend userFriend, Guid?userId = null,
                                                         bool noTracking = true)
        {
            var uf = await GetExistingRequest(userFriend);

            if (uf == null)
            {
                if (userFriend.AppUserId == userFriend.RecipientId)
                {
                    return(userFriend);
                }
                Add(userFriend);
                await UOW.SaveChangesAsync();

                return(userFriend);
            }
            if (uf.Accepted)
            {
                return(uf);
            }

            if (uf.Pending)
            {
                return(uf);
            }

            uf.Pending = true;
            await UpdateAsync(uf);

            await UOW.SaveChangesAsync();

            return(uf);
        }
Exemplo n.º 13
0
        /// <summary>
        /// 获取好友列表.
        /// </summary>
        /// <returns></returns>
        public UserFriend GetUserFriends()
        {
            // 填写提交表单的数据.
            StringBuilder sb = new StringBuilder();

            sb.Append("r=%7B%22h%22%3A%22hello%22%2C%22hash%22%3A%22");
            //string code = Tool.Hash((ulong)_LoginResult.Result.Uin, _PTWebQQ);
            string code = Tool.Hash2(ulong.Parse(_MyQQNumber), _PTWebQQ);

            sb.Append(code);
            sb.Append("%22%2C%22vfwebqq%22%3A%22");
            sb.Append(_VFWebQQ);
            //sb.Append(_LoginResult .Result .VFWebQQ);
            sb.Append("%22%7D");

            //请求数据.
            _HttpWeb.Referer = HttpText.GetUserFriendReferer;
            string text = _HttpWeb.PostWebRequest("http://s.web2.qq.com/api/get_user_friends2", sb.ToString(), Encoding.UTF8);

            try
            {
                UserFriend fm = JSON.Parse <UserFriend>(text);
                return(fm);
            }
            catch (Exception)
            {
                return(null);
            }
        }
Exemplo n.º 14
0
    public void Send_Request()
    {
        UserFriend userFriend = new UserFriend(AWSManager.instance.userInfo.nickname, friendInfo.nickname, 0);
        UserFriend friend     = new UserFriend(friendInfo.nickname, AWSManager.instance.userInfo.nickname, 1);

        jsonAdapter.CreateUserFriend(userFriend, friend, RequestCallback);
    }
Exemplo n.º 15
0
        public List <UserFriend> GetUserFriends(string username)
        {
            string query =
                "SELECT f.User_ID_1 AS Sender_ID, CASE WHEN f.User_ID_1 = u.ID THEN f.User_ID_2 ELSE f.User_ID_1 END AS Friend_ID, " +
                "CASE WHEN f.User_ID_1 = u.ID THEN (SELECT u1.Username FROM [User] u1 WHERE u1.ID = f.User_ID_2) ELSE (SELECT u1.Username FROM [User] u1 WHERE u1.ID = f.User_ID_1) END AS Friend_Username, " +
                "f.Status FROM [User] u JOIN Friendship f ON f.User_ID_1 = u.ID OR f.User_ID_2 = u.ID WHERE u.Username = @Username";
            List <UserFriend> friends = new List <UserFriend>();

            using (SqlCommand command = con.Connection.CreateCommand())
            {
                command.CommandText = query;
                command.CommandType = CommandType.Text;
                command.Parameters.AddWithValue("@Username", username);
                using (SqlDataReader dataReader = command.ExecuteReader())
                {
                    while (dataReader.Read())
                    {
                        UserFriend uf = new UserFriend
                        {
                            ID       = dataReader.GetInt32(dataReader.GetOrdinal("Friend_ID")),
                            Username = dataReader.GetString(dataReader.GetOrdinal("Friend_Username")),
                            Status   = dataReader.GetBoolean(dataReader.GetOrdinal("Status")),
                            Sender   = false
                        };
                        if (uf.ID != dataReader.GetInt32(dataReader.GetOrdinal("Sender_ID")))
                        {
                            uf.Sender = true;
                        }
                        friends.Add(uf);
                    }
                }
            }
            return(friends);
        }
Exemplo n.º 16
0
        //[TestMethod]
        public void CheckTimeoutCache()
        {
            Trace.WriteLine("Wait long time start.");

            var waitTimes = new[] { 10 * 1000, 60 * 1000, 300 * 1000, 600 * 1000 };

            for (int i = 0; i < waitTimes.Length; i++)
            {
                var        watch   = Stopwatch.StartNew();
                int        fuserId = 1000;
                long       userId  = 1002;
                UserFriend Jim     = PersonalCacheStruct.GetOrAdd <UserFriend>(userId.ToString(), new Lazy <UserFriend>(() =>
                {
                    var f = new UserFriend()
                    {
                        UserId = userId, Name = "Jim"
                    };
                    f.Friends.Add(new FriendsData()
                    {
                        UserId = fuserId, Num = 1
                    });
                    f.FriendDict.Add(fuserId, new FriendsData()
                    {
                        UserId = fuserId, Num = 1
                    });
                    return(f);
                }));

                Trace.WriteLine("Running time:" + watch.ElapsedMilliseconds + "ms.");
                Thread.Sleep(waitTimes[i]);
            }
        }
Exemplo n.º 17
0
        protected void BtnMoveFriend_Click(object sender, EventArgs e)
        {
            int groupId = DataConverter.CLng(this.DropFriendGroup.SelectedValue, -1);

            if (groupId < 0)
            {
                DynamicPage.WriteErrMsg("<li>请选择移动到的组别</li>");
            }
            else
            {
                string str = this.EgvFriend.SelectList.ToString();
                if (string.IsNullOrEmpty(str))
                {
                    DynamicPage.WriteErrMsg("<li>请选择要移动的用户</li>");
                }
                else if (UserFriend.MoveByGroupId(str, groupId))
                {
                    DynamicPage.WriteSuccessMsg("批量移动操作成功!", "FriendManage.aspx");
                }
                else
                {
                    DynamicPage.WriteErrMsg("<li>批量移动操作失败!</li>");
                }
            }
        }
Exemplo n.º 18
0
        /// <summary>
        /// 添加用户x => x.UserID == nowUser.Value &&
        /// </summary>
        /// <returns></returns>
        public async Task <IActionResult> AddUser(Guid id)
        {
            var user = await _userManager.FindByIdAsync(id.ToString());

            var nowUser = User.Claims.FirstOrDefault();

            if (nowUser == null)
            {
                return(Json(new { isOK = false, message = "您未登录,请登录后再执行该操作" }));
            }
            if (nowUser.Value == id.ToString())
            {
                return(Json(new { isOK = false, message = "不可添加自己为好友" }));
            }
            if (user == null)
            {
                return(Json(new { isOK = false, message = "好友添加失败,不存在这个用户" }));
            }
            var entity = await _userFriendExtension.GetAll().Include(x => x.Friend).Where(x => x.Friend.Id == id.ToString() && x.UserID.ToString() == nowUser.Value).FirstOrDefaultAsync();

            if (entity != null)
            {
                return(Json(new { isOK = false, message = "你的好友列表里已存在该用户,不可重复添加" }));
            }
            var userFriend = new UserFriend()
            {
                UserID = nowUser.Value,
                Friend = user
            };

            _userFriendExtension.AddAndSave(userFriend);
            return(Json(new { isOK = true, message = "添加成功" }));
        }
Exemplo n.º 19
0
        public async Task <JsonResult> DelFriend(UserFriend model)
        {
            Models.Data.UserFriendController.JsonData jsonData = new Models.Data.UserFriendController.JsonData();
            var user = await _userManager.GetUserAsync(HttpContext.User);

            if (user != null)
            {
                var userTo = await _userManager.FindByNameAsync(model.UserNameTo);

                //找不对对象用户
                if (userTo == null)
                {
                    jsonData.info.state   = 0;
                    jsonData.info.message = "找不到用户" + model.UserNameTo;
                }
                else
                {
                    var uf = dbContext.UserFriend.SingleOrDefault(
                        item => item.UserId == user.Id && item.UserNameTo == model.UserNameTo && item.Type == model.Type);
                    if (uf != null)
                    {
                        dbContext.UserFriend.Remove(uf);
                        jsonData.info.state = 200;
                        await dbContext.SaveChangesAsync();
                    }
                }
            }
            return(new JsonResult(jsonData));
        }
Exemplo n.º 20
0
        public void UnFollow(int id)
        {
            UserFriend model = context.UserFriends.Where(k => k.Id == id).FirstOrDefault();

            context.UserFriends.Remove(model);
            context.SaveChanges();
        }
Exemplo n.º 21
0
        public void UpdateData(UserFriend profile)
        {
            _profile = profile;
            if (!string.IsNullOrEmpty(profile.Avatar))
            {
                Picasso.With(ItemView.Context)
                .Load(profile.Avatar.GetImageProxy(_recipientAvatar.LayoutParameters.Width, _recipientAvatar.LayoutParameters.Height))
                .Placeholder(Resource.Drawable.ic_holder)
                .NoFade()
                .Priority(Picasso.Priority.Normal)
                .Into(_recipientAvatar, null, () =>
                {
                    Picasso.With(ItemView.Context)
                    .Load(profile.Avatar.GetImageProxy(_recipientAvatar.LayoutParameters.Width, _recipientAvatar.LayoutParameters.Height))
                    .Placeholder(Resource.Drawable.ic_holder)
                    .NoFade()
                    .Priority(Picasso.Priority.Normal)
                    .Into(_recipientAvatar);
                });
            }
            else
            {
                Picasso.With(ItemView.Context).Load(Resource.Drawable.ic_holder).Into(_recipientAvatar);
            }

            _recipientLogin.Text = profile.Author;
            _recipientName.Text  = profile.Name;
        }
Exemplo n.º 22
0
 protected void EgvFriendGroup_RowDataBound(object sender, GridViewRowEventArgs e)
 {
     if (e.Row.RowType == DataControlRowType.DataRow)
     {
         DataRowView dataItem = e.Row.DataItem as DataRowView;
         e.Row.Cells[2].Text = UserFriend.GetFriendCount(DataConverter.CLng(dataItem["FriendGroupID"]), this.m_UserName).ToString();
     }
 }
Exemplo n.º 23
0
 public static UserFriendDto AsDto(this UserFriend userFriend)
 {
     return(new UserFriendDto
     {
         userFollowedId = (int)userFriend.UserFollowedId,
         userFollowerId = (int)userFriend.UserFollowerId
     });
 }
        public void Delete(int userId, int friendId)
        {
            var friend = new UserFriend {
                UserId = userId, FriendId = friendId
            };

            _userfriends.Remove(friend);
        }
        private void SeedFriendships()
        {
            using (var db = new SocialNetworkDbContext())
            {
                Console.Write("Adding friends.");

                var users = db.Users.ToList();

                int friendshipsCounter = 0;
                for (int i = 0; i < numberOfUsers; i++)
                {
                    int numberOfFriends = random.Next(15, numberOfUsers);
                    var user            = users[i];
                    for (int j = 0; j < numberOfFriends; j++)
                    {
                        var friend    = users[random.Next(0, numberOfFriends)];
                        var friendIds = users.Select(u => u.Id).ToList();
                        friendIds.Remove(user.Id);
                        if (user.FriendshipsMade.All(fm => fm.FriendId != friend.Id) &&
                            user.FriendshipsAccepted.All(fa => fa.FriendId != user.Id))
                        {
                            var friendshipsMade = new UserFriend
                            {
                                UserId   = user.Id,
                                FriendId = friend.Id
                            };

                            var friendshipsAccepted = new UserFriend
                            {
                                UserId   = friend.Id,
                                FriendId = user.Id
                            };

                            try
                            {
                                user.FriendshipsAccepted.Add(friendshipsAccepted);
                                user.FriendshipsMade.Add(friendshipsMade);

                                friendshipsCounter++;
                                db.SaveChanges();
                            }
                            catch (Exception)
                            {
                            }
                        }
                    }

                    if (i % 15 == 0)
                    {
                        Console.Write(".");
                    }
                }

                Console.WriteLine();
                Console.WriteLine($"Total of {friendshipsCounter} friendships has been made.");
            }
        }
Exemplo n.º 26
0
 public void Add(UserFriend item)
 {
     if (item.UserFriendId.Equals(Guid.Empty))
     {
         item.UserFriendId = Guid.NewGuid();
         _context.UserFriends.Add(item);
         _context.SaveChanges();
     }
 }
Exemplo n.º 27
0
        private async void Follow(UserFriend user)
        {
            if (user != null)
            {
                var errors = await _presenter.TryFollow(user);

                ShowAlert(errors);
            }
        }
Exemplo n.º 28
0
        public async Task <UserFriend> AddFriendsToEachothers(string idA, string idB)
        {
            var userA = await db.Users.Include("userFriends").FirstOrDefaultAsync(x => x.Id == idA);

            var userB = await db.Users.Include("userFriends").FirstOrDefaultAsync(x => x.Id == idB);

            if (userA == null)
            {
                throw new AppException("User not found");
            }
            if (userB == null)
            {
                throw new AppException("User not found");
            }

            var codeA = userA.secretId;
            var codeB = userB.secretId;

            // if friend
            if (userA.userFriends.Any(f => f.friendUserId == idB))
            {
                throw new AppException("already added");
            }

            if (userB.userFriends.Any(f => f.friendUserId == idA))
            {
                throw new AppException("already added");
            }


            var UserAFriendObject = new UserFriend()
            {
                friendUsername      = userA.UserName,
                friendEncryptedCode = codeA,
                friendUserId        = userA.Id,
                AreFriends          = true
            };


            var UserBFriendObject = new UserFriend()
            {
                friendUsername      = userB.UserName,
                friendEncryptedCode = codeB,
                friendUserId        = userB.Id,
                AreFriends          = true
            };

            userA.userFriends.Add(UserBFriendObject);
            var entityA = db.Users.Update(userA);

            userB.userFriends.Add(UserAFriendObject);
            var entityB = db.Users.Update(userB);

            await db.SaveChangesAsync();

            return(UserBFriendObject);
        }
Exemplo n.º 29
0
        private void UserAction(UserFriend userFriend)
        {
            if (userFriend == null)
            {
                return;
            }

            ((BaseActivity)Activity).OpenNewContentFragment(new ProfileFragment(userFriend.Author));
        }
Exemplo n.º 30
0
        private async void Follow(UserFriend user)
        {
            if (user != null)
            {
                var exception = await _presenter.TryFollow(user);

                ShowAlert(exception);
            }
        }
Exemplo n.º 31
0
        public ActionResult ExternalLoginCallback(string returnUrl)
        {
            AuthenticationResult result = OAuthWebSecurity.VerifyAuthentication(Url.Action("ExternalLoginCallback", new { ReturnUrl = returnUrl }));
            if (!result.IsSuccessful)
            {
                return RedirectToAction("ExternalLoginFailure");
            }

            // store the user id in the session
            Session["UserFacebookId"] = result.ProviderUserId;
            webpages_OAuthMembership userrecord = db.webpages_OAuthMembership.FirstOrDefault(m => m.Provider == "facebook" && m.ProviderUserId == result.ProviderUserId);
            if (userrecord != null)
            {
                Session["UserID"] = userrecord.UserId;
            }

            // remember the user's facebook friends

            var fb = new FacebookClient(result.ExtraData["accesstoken"]);
            dynamic myInfo = fb.Get("/me/friends");
            foreach (dynamic friend in myInfo.data)
            {

                // post a test message the friend's wall
                //try
                //{
                //    fb.Post(string.Format("{0}/feed",friend.id), new { message = "My first wall post" });
                //}
                //catch (Exception e)
                //{
                //    string text = e.StackTrace;
                //}

                // does the friend already exist?
                String strUserId = result.ProviderUserId;
                Int64 intUserId = Int64.Parse(strUserId);
                Int64 intfriendId = Int64.Parse(friend.id);
                UserFriend userFriend = db.UserFriends.FirstOrDefault(u => u.UserFriend_UserFacebookId == intUserId && u.UserFriend_FriendFacebookId == intfriendId);
                if (userFriend == null)
                {

                    UserFriend newUserFriend = new UserFriend();
                    newUserFriend.UserFriend_UserFacebookId = intUserId;
                    newUserFriend.UserFriend_FriendFacebookId = intfriendId;
                    newUserFriend.UserFriend_Name = friend.name;

                    // Save the record
                    db.UserFriends.Add(newUserFriend);
                    db.SaveChanges();
                }
            }

            // post a test message on my wall
            //try
            //{
            //    fb.Post("me/feed", new { message = "My second wall post" });
            //}
            //catch (Exception e)
            //{
            //    string text = e.StackTrace;
            //}

            // post a test
            var parameters = new Dictionary<string, object>
                {
                    {"event", "http://amovada.azurewebsites.net/Event/Details/1963"},
                    {"tags" , "585173979"}
                };
            var response = fb.Post("me/amovada:added_you_to", parameters);

            if (OAuthWebSecurity.Login(result.Provider, result.ProviderUserId, createPersistentCookie: false))
            {
                return RedirectToLocal(returnUrl);
            }

            if (User.Identity.IsAuthenticated)
            {
                // If the current user is logged in add the new account
                OAuthWebSecurity.CreateOrUpdateAccount(result.Provider, result.ProviderUserId, User.Identity.Name);
                return RedirectToLocal(returnUrl);
            }
            else
            {
                // User is new, ask for their desired membership name
                string loginData = OAuthWebSecurity.SerializeProviderUserId(result.Provider, result.ProviderUserId);
                ViewBag.ProviderDisplayName = OAuthWebSecurity.GetOAuthClientData(result.Provider).DisplayName;
                ViewBag.ReturnUrl = returnUrl;
                return View("ExternalLoginConfirmation", new RegisterExternalLoginModel { UserName = result.UserName, ExternalLoginData = loginData });
            }
        }
Exemplo n.º 32
0
        public void RemoveFriend(int friendID)
        {
            Query query = new Query(UserFriend.Schema).WHERE(UserFriend.Columns.UserID, this.UserID).AND(UserFriend.Columns.FriendID, friendID);
            UserFriend friend = new UserFriend();
            friend.LoadAndCloseReader(UserFriend.FetchByQuery(query));
            UserFriend.Destroy(friend.UserFriendID);

            UserCache.RemoveUser(this.UserID);
            UserCache.RemoveUser(friendID);
        }