示例#1
0
        /// <summary>
        /// 处理肌力测试上传请求
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public MuscleStrengthResponse HandleMuscleStrengthRequest(MuscleStrengthRequest request)
        {
            MuscleStrengthResponse response = new MuscleStrengthResponse
            {
                Uid     = request.Uid,
                Success = false,
            };

            try
            {
                string   muscleCreatTime = request.MuscleCreatTime;
                DateTime dt = DateTime.ParseExact(muscleCreatTime, "yyyy-MM-dd HH:mm:ss", System.Globalization.CultureInfo.CurrentCulture);
                var      userRelationEntity = new UserRelation
                {
                    Fk_user_id      = int.Parse(request.Uid),
                    Muscle_test_val = request.MuscleTestValue,
                    Mtv_create_time = dt
                };

                userRelationDao.updateMuscle(userRelationEntity);
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                //throw;
            }

            response.Success = true;
            return(response);
        }
示例#2
0
        public void Add_Friend()
        {
            UserInfo user = IPublic.VerifyUser();

            if (user == null)
            {
                return;
            }
            UserRelation user_relation = new UserRelation()
            {
                UserId   = HttpContext.Current.Request["UserId"],
                FriendId = HttpContext.Current.Request["FriendId"]
            };

            if (!userRelationBLL.AddUserRelation(user_relation))
            {
                responseResult.ResponseDetails = "添加好友失败!";
                responseResult.ResponseStatus  = 0;
            }
            else
            {
                responseResult.ResponseData    = user_relation;
                responseResult.ResponseDetails = "添加好友成功!";
                responseResult.ResponseStatus  = 1;
            }
            responseResult.ResponseWrite();
        }
示例#3
0
        /// <summary>
        /// 新增用户关系
        /// </summary>
        /// <param name="user">关系信息</param>
        /// <returns></returns>
        public int AddUserRelation(UserRelation user_relation)
        {
            StringBuilder sbSql = new StringBuilder();

            sbSql.Append("insert into UserRelation values");
            sbSql.Append("(@Id,@UserId,@FriendId);");
            sbSql.Append("insert into UserRelation values");
            sbSql.Append("(@Id,@FriendId,@UserId);");
            SQLiteParameter[] parameters =
            {
                new SQLiteParameter("@Id", DbType.Int32)
                {
                    Value = DBNull.Value
                },
                new SQLiteParameter("@UserId", DbType.String)
                {
                    Value = user_relation.UserId
                },
                new SQLiteParameter("@FriendId", DbType.String)
                {
                    Value = user_relation.FriendId
                }
            };
            return(SqliteHelper.ExecuteNonQuery(sbSql.ToString(), parameters));
        }
示例#4
0
        public async Task <Dictionary <string, UserRelation> > GetRelations(string suid, IEnumerable <string> tuids)
        {
            var redis   = _redisHelper.GetDatabase();
            var batch   = redis.CreateBatch();
            var results = new Dictionary <string, UserRelation>();
            var tasks   = new List <Task>();

            foreach (var tuid in tuids)
            {
                var result = new UserRelation();
                results.Add(tuid, result);

                tasks.Add(batch.SetContainsAsync(string.Format(KEY_USER_ALL_LOVED_USERS_FMT, suid), tuid).ContinueWith(tr =>
                {
                    result.SLoveT = tr.Result;
                }));

                tasks.Add(batch.SetContainsAsync(string.Format(KEY_USER_ALL_LOVED_USERS_FMT, tuid), suid).ContinueWith(tr =>
                {
                    result.TLoveS = tr.Result;
                }));

                tasks.Add(batch.SetContainsAsync(string.Format(KEY_USER_ALL_BAN_USERS_FMT, suid), tuid).ContinueWith(tr =>
                {
                    result.SBanT = tr.Result;
                }));
            }

            batch.Execute();

            await Task.WhenAll(tasks);

            return(results);
        }
示例#5
0
        public void CreateUserFollowRequestRelation(Guid requesterUserId, Guid targetUserId)
        {
            var requesterUser = Repository.UserRepository.GetUserById(requesterUserId);
            var targetUser    = Repository.UserRepository.GetUserById(targetUserId);

            if (requesterUser != null && targetUser != null)
            {
                var requesterUserRelation = new UserRelation()
                {
                    Id           = Guid.NewGuid(),
                    RelationType = UserRelationType.FollowRequestOutgoing,
                    TargetUser   = targetUser,
                    User         = requesterUser
                };
                var targetUserRelation = new UserRelation()
                {
                    Id           = Guid.NewGuid(),
                    RelationType = UserRelationType.FollowRequestIncoming,
                    TargetUser   = requesterUser,
                    User         = targetUser
                };

                Repository.UserRelationRepository.AddUserRelation(requesterUserRelation);
                Repository.UserRelationRepository.AddUserRelation(targetUserRelation);
            }
        }
        public async Task <bool> DeleteUserSubscription(UserRelation ur)
        {
            _context.Remove(ur);
            await _context.SaveChangesAsync();

            return(true);
        }
示例#7
0
        GetUserRelationForUserResponse IUserRelationHandlerLogic.GetUserRelationForUser(Guid requesterUserId, Guid targetUserId)
        {
            UserRelation userRelation = Repository.UserRelationRepository.GetUserRelationForUserByUser(requesterUserId, targetUserId);

            string relation = "none";

            if (userRelation != null)
            {
                if (userRelation.RelationType == UserRelationType.Follow)
                {
                    relation = "following";
                }
                else if (userRelation.RelationType == UserRelationType.FollowRequestIncoming)
                {
                    relation = "incomingpending";
                }
                else if (userRelation.RelationType == UserRelationType.FollowRequestOutgoing)
                {
                    relation = "outgoingpending";
                }
            }

            return(new GetUserRelationForUserResponse()
            {
                Relation = relation,
                Success = true,
                UserId = requesterUserId
            });
        }
示例#8
0
        //public async Task<Tuple<long?, long?>> GetUserRank(string uid, int theday, int yesterday)
        //{
        //    var redis = _redisHelper.GetDatabase();
        //    var batch = redis.CreateBatch();
        //    var rankTask = batch.SortedSetRankAsync(string.Format(KEY_USER_RANK_FMT, theday), uid, Order.Descending);
        //    var lastRankTask = batch.SortedSetRankAsync(string.Format(KEY_USER_RANK_FMT, yesterday), uid, Order.Descending);

        //    batch.Execute();

        //    var rank = await rankTask;
        //    var lastRank = await lastRankTask;

        //    return Tuple.Create(rank, lastRank);
        //}

        //public List<UserScore> GetUserRange(int theday, int yesterday, int start, int stop)
        //{
        //    var redis = _redisHelper.GetDatabase();
        //    var key = string.Format(KEY_USER_RANK_FMT, theday);
        //    List<UserScore> result = null;

        //    if (redis.KeyExists(key))
        //    {
        //        var entries = redis.SortedSetRangeByRankWithScores(key,
        //            start, stop, Order.Descending);

        //        result = entries.Select(entry => new UserScore
        //        {
        //            UID = entry.Element,
        //            Score = (long)entry.Score
        //        }).ToList();
        //    }
        //    else
        //    {
        //        key = string.Format(KEY_USER_RANK_FMT, yesterday);
        //        var entries = redis.SortedSetRangeByRankWithScores(key,
        //           start, stop, Order.Descending);

        //        result = entries.Select(entry => new UserScore
        //        {
        //            UID = entry.Element,
        //            Score = (long)entry.Score
        //        }).ToList();
        //    }

        //    return result;
        //}

        //public async Task TryFillUserInfo(List<UserScore> users)
        //{
        //    var redis = _redisHelper.GetDatabase();

        //    var tasks = new List<Task>();
        //    var batch = redis.CreateBatch();

        //    foreach (var item in users)
        //    {
        //        var key = string.Format(KEY_USER_INFO_FMT, item.UID);

        //        var task = batch.HashGetAsync(key, F_DISPLAY_NAME).ContinueWith(tresult =>
        //        {
        //            item.Name = tresult.Result;
        //        });

        //        var task2 = batch.HashGetAsync(key, F_THUMB).ContinueWith(tresult =>
        //        {
        //            item.Thumb = tresult.Result;
        //        });

        //        tasks.Add(task);
        //        tasks.Add(task2);
        //    }

        //    batch.Execute();

        //    await Task.WhenAll(tasks);
        //}

        public async Task <UserRelation> GetRelation(string userId, string targetUId)
        {
            var redis  = _redisHelper.GetDatabase();
            var batch  = redis.CreateBatch();
            var result = new UserRelation();
            var tasks  = new List <Task>();

            tasks.Add(batch.SetContainsAsync(string.Format(KEY_USER_ALL_LOVED_USERS_FMT, userId), targetUId).ContinueWith(tr =>
            {
                result.SLoveT = tr.Result;
            }));

            tasks.Add(batch.SetContainsAsync(string.Format(KEY_USER_ALL_LOVED_USERS_FMT, targetUId), userId).ContinueWith(tr =>
            {
                result.TLoveS = tr.Result;
            }));

            tasks.Add(batch.SetContainsAsync(string.Format(KEY_USER_ALL_BAN_USERS_FMT, userId), targetUId).ContinueWith(tr =>
            {
                result.SBanT = tr.Result;
            }));

            batch.Execute();

            await Task.WhenAll(tasks);

            return(result);
        }
 private void btnremove_Click(object sender, EventArgs e)
 {
     if (DialogResult.Yes == MessageBox.Show("是否删除该数据?", "是否删除该数据", MessageBoxButtons.YesNo, MessageBoxIcon.Question))
     {
         if ((TabType)tabs.SelectedIndex == TabType.apply && dataGridApply.SelectedRows.Count > 0)
         {
             string applyid = dataGridApply.SelectedRows[0].Cells["申请ID"].Value.ToString();
             ApplyInfo.deleteApplyInfo(applyid);
             bindApplyInfo();
         }
         if ((TabType)tabs.SelectedIndex == TabType.approval && dataGridApproval.SelectedRows.Count > 0)
         {
             string applyid = dataGridApproval.SelectedRows[0].Cells["申请ID"].Value.ToString();
             ApprovalRecord.deleteApprovalInfo(applyid);
             bindApprovalInfo();
         }
         if ((TabType)tabs.SelectedIndex == TabType.user && dataGridUser.SelectedRows.Count > 0)
         {
             string userid = dataGridUser.SelectedRows[0].Cells["ID"].Value.ToString();
             UserInfo.deleteUserInfo(userid);
             UserRelation.deleteUserFrelationInfo(userid);
             bindUserInfo();
         }
     }
 }
示例#10
0
        public IActionResult AddFriend([FromQuery] int?initiatorId, [FromQuery] int?deciderId)
        {
            if (initiatorId == null || deciderId == null)
            {
                return(Json(new { statusCode = ResponseStatus.ValidationError }));
            }
            try
            {
                if (!facebookDataContext.Users.Any(u => u.Id == initiatorId) ||
                    !facebookDataContext.Users.Any(u => u.Id == deciderId))
                {
                    return(Json(new { statusCode = ResponseStatus.NoDataFound }));
                }

                UserRelation newUserRelation = new UserRelation()
                {
                    InitiatorId    = (int)initiatorId,
                    DesiderId      = (int)deciderId,
                    SocialStatusId = (int)SocialStatuses.Request,
                    CreatedAt      = DateTime.Now,
                    IsDeleted      = false,
                };
                facebookDataContext.UserRelations.Add(newUserRelation);
                facebookDataContext.SaveChanges();
                return(Json(new { statusCode = ResponseStatus.Success }));
            }
            catch (Exception)
            {
                return(Json(new { statusCode = ResponseStatus.Error }));
            }
        }
示例#11
0
        public IActionResult VerifyFriendsRequest(string name)
        {
            string username = UserManager.GetUserName(User);

            var query = from reqst in Database.Requests
                        where reqst.Target == username && reqst.UserName == name
                        select reqst;

            // If there are no request, return bad request
            if (!query.Any())
            {
                return(BadRequest("No such request exists"));
            }

            // Remove the request
            Database.Requests.Remove(query.Single());

            // Create new relation as request was varified
            var userRelation = new UserRelation()
            {
                ToUserId   = username,
                FromUserId = name,
                Date       = DateTime.UtcNow,
            };

            Database.UserRelations.Add(userRelation);

            Database.SaveChanges();

            return(Ok());
        }
        public ActionResult Edit(UserRelation request)
        {
            string User1Id = request.User1Id;
            string User2Id = request.User2Id;

            try
            {
                if (ModelState.IsValid)
                {
                    UserRelation userrelation  = db.UserRelations.Find(User1Id, User2Id);
                    UserRelation userrelation2 = db.UserRelations.Find(User2Id, User1Id);

                    if (TryUpdateModel(userrelation) /*&& TryUpdateModel(userrelation2)*/)
                    {
                        userrelation.Status = request.Status;

                        switch (userrelation.Status)
                        {
                        case "Friend":
                            userrelation2.Status = "Friend";
                            break;

                        case "Follows":
                            if (userrelation2.Status == "Follows")
                            {
                                userrelation.Status = userrelation2.Status = "Friend";
                                break;
                            }
                            userrelation2.Status = "IsFollowed";
                            break;

                        case "Blocked":
                            userrelation2.Status = "IsBlocked";
                            break;
                        }

                        userrelation.Date  = DateTime.Now;
                        userrelation2.Date = DateTime.Now;
                        db.SaveChanges();
                        TempData["message"] = "The status has been successfully changed!";
                        return(RedirectToAction("Show", "Users", new { id = User2Id }));
                    }
                    else
                    {
                        return(RedirectToAction("Index", "Users"));
                    }
                }
                else
                {
                    TempData["ErrorMsg"] = "Error boss!";
                    return(RedirectToAction("Index", "Users"));
                }
            }
            catch (Exception e)
            {
                TempData["ErrorMsg"] = e.Message;
                return(RedirectToAction("Index", "Users"));
            }
        }
示例#13
0
        public int insertUserRelation(UserRelation userRelation)
        {
            using (var conn = DbUtil.getConn())
            {
                const string insert = "INSERT INTO bdl_user_relation (`fk_user_id`, `bind_id`) VALUES (@Fk_user_id, @Bind_id)";

                return(conn.Execute(insert, userRelation));
            }
        }
        public ActionResult Delete(string User1Id, string User2Id)
        {
            UserRelation ToDelete1 = db.UserRelations.Find(User1Id, User2Id);
            UserRelation ToDelete2 = db.UserRelations.Find(User2Id, User1Id);

            db.UserRelations.Remove(ToDelete1);
            db.UserRelations.Remove(ToDelete2);
            db.SaveChanges();
            // return RedirectToAction("Show", "Users", new { id = User2Id });
            return(RedirectToAction((string)TempData["action"], (string)TempData["controller"], new { id = (string)TempData["id"] }));
        }
        public async Task <bool> Handle(FollowCommand request, CancellationToken cancellationToken)
        {
            var ur = await _userRelationRepository.GetUserRelationAsync(request.FollowerId, request.FollowedUserId);

            if (ur == null)
            {
                ur = new UserRelation(request.FollowerId, request.FollowedUserId);
                _userRelationRepository.Add(ur);
                return(await _userRelationRepository.UnitOfWork.SaveEntitiesAsync(cancellationToken));
            }

            return(true);
        }
示例#16
0
        protected async override Task <HandleResult> HandleCoreAsync(AddFollowRequest reqObj)
        {
            UserRelation relation = await _cacheManager.GetCache <IUserInfoCache>().GetRelation(reqObj.UserId, reqObj.TargetUId);

            if (relation.SLoveT)
            {
                return(new AddFollowResult
                {
                    State = HandleStates.Success,
                    Msg = string.Empty
                });
            }

            var follow = new Follow
            {
                FollowTime = DateTime.Now,
                IsMutual   = relation.TLoveS,
                SUID       = reqObj.UserId,
                SUname     = TryGetUserName(reqObj.UserId),
                TUID       = reqObj.TargetUId
            };

            var rowAffected = await _followRepo.AddFollowAsync(follow, relation.SBanT);

            if (rowAffected > 0)
            {
                _eventPublisher.Publish(new LoveUserEvent {
                    SUID = reqObj.UserId,
                    TUID = reqObj.TargetUId
                });

                if (relation.SBanT)
                {
                    _eventPublisher.Publish(new UnBanUserEvent {
                        SUID = reqObj.UserId,
                        TUID = reqObj.TargetUId
                    });
                }

                return(new AddFollowResult {
                    State = HandleStates.Success,
                    Msg = string.Empty
                });
            }

            return(new AddFollowResult {
                State = HandleStates.NoDataFound,
                Msg = "未找到数据"
            });
        }
示例#17
0
        public IActionResult RequestFriendAction(int InitiatorId, int DesiderId)
        {
            UserRelation newUserRel = new UserRelation()
            {
                CreatedAt      = DateTime.Now,
                DesiderId      = DesiderId,
                InitiatorId    = InitiatorId,
                IsDeleted      = false,
                SocialStatusId = (int)SocialStatuses.Request
            };

            facebookDataContext.UserRelations.Add(newUserRel);
            facebookDataContext.SaveChanges();
            return(Json(new { success = true }));
        }
示例#18
0
        public void updateBind_idByFk_user_id(UserRelation userRelation)
        {
            string sql = @"update bdl_user_relation set bind_id=@Bind_id ,gmt_modified=@Gmt_modified where fk_user_id = @Fk_user_id";

            using (var conn = DbUtil.getConn())
            {
                try
                {
                    conn.Execute(sql, userRelation);
                }
                catch (Exception ex)
                {
                    logger.Error("数据库updateUserRelation操作异常:" + ex.ToString());
                }
            }
        }
示例#19
0
        public void Update(UserDescription description)
        {
            Name        = description.Name;
            DisplayName = description.DisplayName;
            Status      = description.Status;
            Relation    = UserRelation.None;
            if (description.Friend ?? false)
            {
                Relation = UserRelation.Friend;
            }
            else if (client.Me == null)
            {
                Relation = UserRelation.Me;
            }

            Changed.SafeInvoke(this, new EventArgs());
        }
        public async Task <bool> Handle(ToggleUserFollowCommand request, CancellationToken cancellationToken)
        {
            var isFollow = false;
            var ur       = await _userRelationRepository.GetAsync(request.FollowerId, request.UserIdToFollow);

            if (ur == null)
            {
                ur = new UserRelation(request.FollowerId, request.UserIdToFollow);
                ur.Follow();
                _userRelationRepository.Add(ur);
                isFollow = true;
            }
            else
            {
                if (ur.Followed)
                {
                    ur.UnFollow();
                }
                else
                {
                    isFollow = true;
                    ur.Follow();
                }
            }

            var result = await _userRelationRepository.UnitOfWork.SaveEntitiesAsync(cancellationToken);

            if (result)
            {
                if (isFollow)
                {
                    await SendUserFollowedEventAsync(request.FollowerId, request.UserIdToFollow);
                }
                else
                {
                    await SendUserUnFollowedEventAsync(request.FollowerId, request.UserIdToFollow);
                }

                // 返回被关注者是否关注了我
                ur = await _userRelationRepository.GetAsync(request.UserIdToFollow, request.FollowerId);

                return(ur?.Followed ?? false);
            }

            throw new ApplicationException("操作失败");
        }
        public ActionResult New(UserRelation userrelation)
        {
            userrelation.Date = DateTime.Now;
            var userrelation2 = new UserRelation();

            userrelation2.Date   = userrelation.Date;
            userrelation2.Status = userrelation.Status;

            switch (userrelation.Status)
            {
            case "Friend":
                userrelation2.Status = "Friend";
                break;

            case "Follows":
                userrelation2.Status = "IsFollowed";
                break;

            case "Blocked":
                userrelation2.Status = "IsBlocked";
                break;
            }

            userrelation2.User1Id = userrelation.User2Id;
            userrelation2.User2Id = userrelation.User1Id;
            try
            {
                if (ModelState.IsValid)
                {
                    db.UserRelations.Add(userrelation);
                    db.UserRelations.Add(userrelation2);
                    db.SaveChanges();
                    return(RedirectToAction("Show", "Users", new { id = userrelation.User2Id }));
                }
                else
                {
                    return(RedirectToAction("Index", "Users"));
                }
            }
            catch (Exception e)
            {
                TempData["ErrorMsg"] = e.Message;
                return(RedirectToAction("Index", "Users"));
            }
        }
示例#22
0
        public void updateMuscle(UserRelation entity)
        {
            string sql = @"update bdl_user_relation set muscle_test_val=@Muscle_test_val,mtv_create_time=@Mtv_create_time
                where fk_user_id = @Fk_user_id
            ";

            using (var conn = DbUtil.getConn())
            {
                try
                {
                    conn.Execute(sql, entity);
                }
                catch (Exception ex)
                {
                    logger.Error("数据库updateMuscle操作异常:" + ex.ToString());
                }
            }
        }
示例#23
0
        public void AssignDepartmentManagerToEmployee(string employeeId, string[] departmentManagerIds)
        {
            if ((departmentManagerIds != null) && (departmentManagerIds.Count() > 0))
            {
                foreach (var dmId in departmentManagerIds)
                {
                    UserRelation ur = new UserRelation()
                    {
                        DepartmentManagerId = dmId,
                        EmployeeId          = employeeId
                    };

                    _userRelationRepository.Add(ur);
                }

                _userRelationRepository.Commit();
            }
        }
示例#24
0
 private void btnsave_Click(object sender, EventArgs e)
 {
     if (!checkControlsData())
     {
         return;
     }
     if (!UserInfo.IsUserExistById(txt_phone.Text.Trim()))
     {
         UserInfo user = new UserInfo();
         user.UserId         = user.UserAccount = user.UserPhone = txt_phone.Text.Trim();
         user.UserName       = txt_username.Text.Trim();
         user.UserPassword   = Login.GetMD5(txt_pwd.Text.Trim());
         user.UserType       = cb_usertype.SelectedIndex.ToString();
         user.UserRegion     = txt_region.Text.Trim();
         user.UserDepartment = txt_department.Text.Trim();
         user.SystemId       = txt_systemid.Text.Trim();
         try
         {
             if (isedit)
             {
                 UserInfo.deleteUserInfo(DataManagement.currentuser.UserId);
                 UserRelation.deleteUserFrelationInfo(DataManagement.currentuser.UserId);
             }
             UserInfo.addUserInfo(user);
             UserRelation ur = new UserRelation();
             for (int i = 0; i < this.clb_leader.CheckedItems.Count; i++)
             {
                 ur.applyUserId     = txt_phone.Text.Trim();
                 ur.fapprovalUserId = ((DataRowView)this.clb_leader.CheckedItems[i])[0].ToString();
                 UserRelation.addUserRelation(ur);
             }
             MessageBox.Show("成功");
         }
         catch (Exception ex)
         {
             MessageBox.Show("失败,请稍后再试" + ex.ToString());
         }
     }
     else
     {
         MessageBox.Show("失败,已经存在该手机号码");
     }
 }
        public List <UserDomain> GetFriends(long myId, UserRelation userRelation)
        {
            var friendship = Context.Friendships.AsQueryable();

            switch (userRelation)
            {
            case UserRelation.Friend:
                friendship = friendship
                             .Where(x => (x.UserOneId == myId || x.UserTwoId == myId) &&
                                    x.Status == FriendStatus.Friend);
                break;

            case UserRelation.InFollower:
                friendship = friendship
                             .Where(x => (x.UserOneId == myId || x.UserTwoId == myId) &&
                                    x.Status == FriendStatus.FollowerPendingInFriend &&
                                    x.ActionUserId != myId);
                break;

            case UserRelation.OutFollower:
                friendship = friendship
                             .Where(x => (x.UserOneId == myId || x.UserTwoId == myId) &&
                                    x.Status == FriendStatus.FollowerPendingInFriend &&
                                    x.ActionUserId == myId);
                break;
            }

            var friendsId = friendship.Select(x => x.UserOneId == myId ? x.UserTwoId : x.UserOneId);
            var friends   = Context.Users.Where(x => friendsId.Contains(x.Id))
                            .Select(x => new
            {
                user         = x,
                avatarActive = x.Avatars.FirstOrDefault(y => y.Active == true)
            })
                            .AsEnumerable()
                            .Select(x => x.user)
                            .ToList();

            var tt = Mapper.Map <List <UserDomain> >(friends);

            return(tt);
        }
示例#26
0
        /// <summary>
        /// 两个用户建立关联(系)
        /// </summary>
        /// <param name="firstUser"></param>
        /// <param name="secondUser"></param>
        /// <returns></returns>
        public async Task <int> CreateRelation(long firstUser, long secondUser)
        {
            using (var db = new DbContext())
            {
                var item = new UserRelation
                {
                    CreateTime      = DateTime.Now,
                    FirstDelete     = false,
                    FirstGroupName  = string.Empty,
                    FirstUser       = firstUser,
                    SecondDelete    = false,
                    SecondGroupName = string.Empty,
                    SecondUser      = secondUser
                };

                db.UserRelation.Add(item);

                return(await db.SaveChangesAsync());
            }
        }
        public async Task <bool> Handle(FollowEachOtherCommand request, CancellationToken cancellationToken)
        {
            var anotherUserId = await _userRepository.GetUserIdByCodeAsync(request.InvitingUserCode);

            if (anotherUserId != null)
            {
                var userId    = Guid.Parse(request.UserId);
                var relation1 = new UserRelation(userId, anotherUserId.Value);
                var relation2 = new UserRelation(anotherUserId.Value, userId);

                relation1.Follow();
                relation2.Follow();

                _userRelationRepository.Add(relation1);
                _userRelationRepository.Add(relation2);

                return(await _userRelationRepository.UnitOfWork.SaveEntitiesAsync());
            }

            return(false);
        }
        public async Task <IActionResult> Unfollow(string username)
        {
            string       followerId  = _usersService.GetCurrentUserId();
            string       followingId = (await _usersService.GetByUserNameAsync(username)).Id;
            UserRelation ur          = await _userSubscriptions.GetUserSubscription(followingId, followerId);

            if (ur != null)
            {
                if (await _userSubscriptions.DeleteUserSubscription(ur))
                {
                    return(StatusCodeAndDtoWrapper.BuildSuccess($"Subscription deleted successfully"));
                }
                else
                {
                    return(StatusCodeAndDtoWrapper.BuildErrorResponse($"Something went wrong"));
                }
            }
            else
            {
                return(StatusCodeAndDtoWrapper.BuildErrorResponse($"You are not subscribed to {username}"));
            }
        }
示例#29
0
        public static HomeUserTempDto MapDecider(UserRelation from, IWebHostEnvironment hostingEnvironment, int currentUserId)
        {
            if (from == null)
            {
                return(null);
            }

            var to = new HomeUserTempDto
            {
                FullName    = $"{from.Initiator.FirstName} {from.Initiator.LastName}",
                HomePostDto = Map(from.Initiator.UsersPosts, hostingEnvironment, currentUserId).ToList(),
                Bio         = from.Initiator.Bio,
                UserId      = from.Initiator.Id
            };

            string path = hostingEnvironment.WebRootPath + "/ProfilePics/" + (from.Initiator.ProfilePhotos.Where(x => x.IsCurrent).Select(x => x.Url).FirstOrDefault() ?? (from.Initiator.GenderId == 1 ? "default.jpg" : "default_female.png"));

            byte[] b = System.IO.File.ReadAllBytes(path);
            to.ProfilePicUrl = "data:image/png;base64," + Convert.ToBase64String(b);

            return(to);
        }
示例#30
0
        public async Task <bool> Handle(MuteUserCommand request, CancellationToken cancellationToken)
        {
            var claim = _httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier);
            var myId  = claim == null ? Guid.Empty : Guid.Parse(claim.Value);

            var userRelation = await _userRelationRepository.GetAsync(myId, request.UserId);

            if (request.Muted)
            {
                if (userRelation == null)
                {
                    userRelation = new UserRelation(myId, request.UserId);
                    _userRelationRepository.Add(userRelation);
                }

                userRelation.Mute();
            }
            else if (userRelation != null)
            {
                userRelation.UnMute();
            }

            return(await _userRelationRepository.UnitOfWork.SaveEntitiesAsync(cancellationToken));
        }
示例#31
0
	private void attach_UserRelations(UserRelation entity)
	{
		this.SendPropertyChanging();
		entity.User = this;
	}
示例#32
0
 partial void InsertUserRelation(UserRelation instance);
示例#33
0
 partial void UpdateUserRelation(UserRelation instance);
示例#34
0
 partial void DeleteUserRelation(UserRelation instance);
示例#35
0
	private void detach_UserRelations1(UserRelation entity)
	{
		this.SendPropertyChanging();
		entity.User1 = null;
	}