Example #1
0
        public void Receive_SendMessage_ReturnsPage(string text, UserStates userStates, string expectedPage)
        {
            var messageHandler     = GetMessageHandler();
            var fakeMediator       = new FakeBotMediator();
            var stubMessageBuilder = new StubMessageBuilder();
            var fakeRegister       = new FakeMessageRegister();
            var fakeHistory        = new FakeMessageHistory();

            messageHandler.SetMessageBuilder(stubMessageBuilder);
            messageHandler.SetMediator(fakeMediator);
            fakeRegister.UserState = userStates;
            messageHandler.SetMessageRegister(fakeRegister);
            var user = new User {
                ChatId = "12345", MessengerClass = nameof(FakeMessengerApi)
            };
            var message = new Message(user)
            {
                BasicText = text
            };
            var pastMessage = new Message(user)
            {
                BasicText = "HistoryPage"
            };

            fakeHistory.ReturnMessage = pastMessage;
            messageHandler.SetMessageHistory(fakeHistory);

            messageHandler.Receive(message).Wait();

            StringAssert.Contains(expectedPage, fakeMediator.AddedMessage.BasicText);
        }
Example #2
0
 public User(string nickName, UserStates state, DateTimeOffset lastVizit, int avatarID)
 {
     NickName  = nickName;
     State     = state;
     LastVizit = lastVizit;
     AvatarID  = avatarID;
 }
Example #3
0
        public async Task <JsonResult> UpdateState(string id, UserStates state)
        {
            try
            {
                if (string.IsNullOrEmpty(id))
                {
                    throw new ArgumentNullException("缺少参数!");
                }

                var user = UserManager.FindById(id);
                user.UserState = state;
                user.Operator  = User.Identity.Name;

                var result = await UserManager.UpdateAsync(user);

                if (result.Succeeded)
                {
                    return(Success(result.Succeeded));
                }
                else
                {
                    throw new Exception(string.Join(",", result.Errors));
                }
            }
            catch (Exception e)
            {
                return(Fail(ErrorCode.DataError, e.Message));
            }
        }
Example #4
0
 public UpdateUserStatus(long Id, UserStates userState)
 {
     userStatus = new UserStatus {
         userId = Id, state = userState
     };
     IsExseption = false;
 }
Example #5
0
        public async Task UserCantLeaveWhenNotAlreadyJoined()
        {
            await Assert.ThrowsAsync <NotJoinedRoomException>(() => Hub.LeaveRoom());

            // ensure no state was left behind.
            await Assert.ThrowsAsync <KeyNotFoundException>(() => UserStates.GetForUse(USER_ID));
        }
        public void AddNewUser(string id, string platform, UserStates stateEnum = UserStates.NotRegister)
        {
            var statesDict = new Dictionary <UserStates, int>
            {
                [UserStates.NotRegister]       = 0,
                [UserStates.RegisterInProcess] = 1,
                [UserStates.Register]          = 2,
                [UserStates.AddingLink]        = 3
            };
            var state  = statesDict[stateEnum];
            var dbName = dbNameProvider.GetDBName("PeopleAndGroups", "csv");

            using (TextFieldParser parser = new TextFieldParser(dbName))
            {
                parser.SetDelimiters(",");
                while (!parser.EndOfData)
                {
                    var fields = parser.ReadFields();
                    if (fields[0] == id)
                    {
                        return;
                    }
                }
            }
            using (var writer = File.AppendText(dbName))
                using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
                {
                    csv.WriteField(id);
                    csv.WriteField(" ");
                    csv.WriteField(state);
                    csv.WriteField(platform);
                    csv.NextRecord();
                }
        }
Example #7
0
    public void OnRealTimeMessageReceived(bool reliable, string senderId, byte[] data)
    {
        string rawData = data.ConvertToString();

        string[] dataClumps = rawData.Split(' ');

        string dataHeader = dataClumps[0];

        LogDebugMessage("New MSG: " + dataHeader + " from " + senderId);

        switch (dataHeader)
        {
        case _introductionConst: {
            MPPlayer theNewPlayer = new MPPlayer(PlayGamesPlatform.Instance.RealTime.GetConnectedParticipants().Find(x => x.ParticipantId == senderId));

            OtherPlayerJoinedRoom(theNewPlayer);
        }

        break;

        case _gameStartingConst: {
            if (CurState != RoomStates.GameInProgress)
            {
                GameStarted();

                LogDebugMessage("Game Starting!");
            }
        }

        break;

        case _playerChangedState: {
            MPPlayer senderPlayer = _playersInRoom.Find(x => x.GetID() == senderId);

            if (senderPlayer != null)
            {
                UserStates oldState = senderPlayer.GetState();

                senderPlayer.ChangeStateTo((UserStates)int.Parse(dataClumps[1]));

                //check for player leaving
                if (senderPlayer.GetState() == UserStates.Disconnected)
                {
                    OtherPlayerLeftRoom(senderPlayer);
                }

                //check to see if they are setting themselves to ready
                else if (
                    (oldState == UserStates.Ready && senderPlayer.GetState() != UserStates.Ready) ||                    //changing from ready to not ready
                    (oldState != UserStates.Ready && senderPlayer.GetState() == UserStates.Ready)                       //changing from not ready to ready
                    )
                {
                    PlayerChangedReady(senderPlayer);
                }
            }
        }
        break;
        }
    }
Example #8
0
        public async Task UserCantJoinWhenRestricted()
        {
            Database.Setup(db => db.IsUserRestrictedAsync(It.IsAny <int>())).ReturnsAsync(true);

            await Assert.ThrowsAsync <InvalidStateException>(() => Hub.JoinRoom(ROOM_ID));

            // ensure no state was left behind.
            await Assert.ThrowsAsync <KeyNotFoundException>(() => UserStates.GetForUse(USER_ID));
        }
Example #9
0
        public async Task UserJoinPreRetrievalFailureCleansUpRoom()
        {
            SetUserContext(ContextUser2); // not the correct user to join the game first; triggers host mismatch failure.
            await Assert.ThrowsAnyAsync <Exception>(() => Hub.JoinRoom(ROOM_ID));

            await Assert.ThrowsAsync <KeyNotFoundException>(() => Rooms.GetForUse(ROOM_ID));

            await Assert.ThrowsAsync <KeyNotFoundException>(() => UserStates.GetForUse(USER_ID));
        }
Example #10
0
 public void SetUserState(ICollection <long> states, Zeze.Net.Binary statex)
 {
     lock (this) // 简单使用一下这个锁。
     {
         UserStates.Clear();
         UserStates.AddRange(states);
         UserStatex = statex;
     }
 }
        public void ChangeState(string id, UserStates newStateEnum)
        {
            var newState = statesDict[newStateEnum].ToString();
            var group    = GetGroupFromId(id);
            var platform = GetPlatformFromId(id);
            var dbName   = dbNameProvider.GetDBName("PeopleAndGroups", "csv");

            RewriteFields(id, group, newState, platform, dbName);
        }
Example #12
0
    public MPPlayer(Participant participantData)
    {
        if (participantData == null)
        {
            Debug.Log("Creating participant is null");
        }

        _ourData   = participantData;
        _userState = UserStates.Connected;
    }
Example #13
0
 public void Copy(ClientModel model)
 {
     this.Id                   = model.Id;
     this.Name                 = model.Name;
     this.Email                = model.Email;
     this.IsFriend             = model.IsFriend;
     this.IsApproved           = model.IsApproved;
     this.IsInitiatorToApprove = model.IsInitiatorToApprove;
     this.ClientState          = model.ClientState;
 }
Example #14
0
 public static Phrase[] GetPhrases(UserStates userState)
 {
     if (cache.ContainsKey(userState))
     {
         return cache[userState];
     }
     else
     {
         return new Phrase[] { };
     }
 }
Example #15
0
    public void ChangeStateTo(UserStates newState)
    {
        UserStates oldState = _userState;

        _userState = newState;

        if (_userState != oldState && PlayerStateChangedEvent != null)
        {
            PlayerStateChangedEvent(this);
        }
    }
Example #16
0
        public async Task UserJoinPostJoinFailureCleansUpRoomAndUser()
        {
            Database.Setup(db => db.AddRoomParticipantAsync(It.IsAny <MultiplayerRoom>(), It.IsAny <MultiplayerRoomUser>()))
            .ThrowsAsync(new Exception("error"));

            await Assert.ThrowsAnyAsync <Exception>(() => Hub.JoinRoom(ROOM_ID));

            await Assert.ThrowsAsync <KeyNotFoundException>(() => Rooms.GetForUse(ROOM_ID));

            await Assert.ThrowsAsync <KeyNotFoundException>(() => UserStates.GetForUse(USER_ID));
        }
Example #17
0
        public async Task UserJoinPreJoinFailureCleansUpRoom()
        {
            Database.Setup(db => db.MarkRoomActiveAsync(It.IsAny <MultiplayerRoom>()))
            .ThrowsAsync(new Exception("error"));

            await Assert.ThrowsAnyAsync <Exception>(() => Hub.JoinRoom(ROOM_ID));

            await Assert.ThrowsAsync <KeyNotFoundException>(() => Rooms.GetForUse(ROOM_ID));

            await Assert.ThrowsAsync <KeyNotFoundException>(() => UserStates.GetForUse(USER_ID));
        }
        public async Task SetState(int userId, UserStates state)
        {
            using (var connection = new SqlConnection(_connectionString))
            {
                await connection.OpenAsync();

                await connection.ExecuteAsync(
                    "UPDATE Users.Users SET UserStateId = @stateId WHERE UserId = @userId",
                    new { userId, stateId = (byte)state });
            }
        }
Example #19
0
        private int DefineStateFromEnum(UserStates enumState)
        {
            var statesDict = new Dictionary <UserStates, int>
            {
                [UserStates.NotRegister]       = 0,
                [UserStates.RegisterInProcess] = 1,
                [UserStates.Register]          = 2,
                [UserStates.AddingLink]        = 3
            };

            return(statesDict[enumState]);
        }
Example #20
0
        void HandleJoinRoomCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            var newRoom = (RoomInfo)e.UserState;

            lock (_locker)
            {
                _roomInfo = newRoom;
                RoomName  = newRoom.Name.ToUpper();
                UserStates.Clear();
                Start();
            }
        }
Example #21
0
        private static void ChangeState(List <CheckedUser> checkedUsers, UserStates state)
        {
            UserManager manager = new UserManager();

            foreach (CheckedUser cUser in checkedUsers)
            {
                if (cUser.Checked == true)
                {
                    manager.ModifyUserState(cUser.Id, state);
                }
            }
        }
Example #22
0
        public async Task UserCantJoinAlreadyEnded()
        {
            Database.Setup(db => db.GetRoomAsync(It.IsAny <long>()))
            .ReturnsAsync(new multiplayer_room
            {
                ends_at = DateTimeOffset.Now.AddMinutes(-5),
                user_id = USER_ID
            });

            await Assert.ThrowsAsync <InvalidStateException>(() => Hub.JoinRoom(ROOM_ID));

            // ensure no state was left behind.
            await Assert.ThrowsAsync <KeyNotFoundException>(() => UserStates.GetForUse(USER_ID));
        }
        private async void SwitchPersonState(Guid id, UserStates state)
        {
            Busy(true);
            var origin = await ClientService.Persons
                         .FirstAsync(it => it.PersonID == id);

            origin.PersonState = state;
            await ClientService.Persons.UpdateEntityAsync(id, origin);

            AdminsList.First(it => it.PersonID == id).PersonState = state;


            Busy(false);
            StateHasChanged();
        }
Example #24
0
    /// <summary>
    /// 更改状态
    /// </summary>
    /// <param name="State"></param>
    private void ChangeState(UserStates state)
    {
        UserManager manager = new UserManager();
        ArrayList   al      = new ArrayList();

        for (int i = 0; i < this.gvMain.Rows.Count; i++)
        {
            CheckBox cb = (gvMain.Rows[i].FindControl("chkSelect")) as CheckBox;
            int      id = Convert.ToInt32((gvMain.Rows[i].FindControl("lblId") as Label).Text);
            if (cb.Checked == true)
            {
                manager.ModifyUserState(id, state);
            }
        }
        this.gvMain.DataSource = manager.GetUsers();
        this.gvMain.DataBind();
    }
Example #25
0
        public static UserStates GetUserStatesById(int Id)
        {
            #region 通过用户状态Id返回用户的状态信息
            UserStates userstates = new UserStates();
            string     sql        = "SELECT * FROM UserStates WHERE Id=" + Id;
            using (SqlDataReader dr = DbHelp.GetReader(sql))
            {
                if (dr.Read())
                {
                    userstates.Id   = Convert.ToInt32(dr["Id"]);
                    userstates.Name = dr["Name"].ToString();
                }
            }
            return(userstates);

            #endregion
        }
Example #26
0
        public void SetState(Message message, UserStates states)
        {
            if (message?.User.ChatId == null || message.User.MessengerClass == null)
            {
                throw new ArgumentNullException(nameof(message.User));
            }

            var id = message.User;

            lock (userStates)
            {
                if (userStates.ContainsKey(id))
                {
                    userStates[id] = states;
                }
                else
                {
                    userStates.Add(id, states);
                }
            }
        }
Example #27
0
        public void AddUser(User usr)
        {
            if (!VerifyUsersExists(usr.Id))
            {
                Random r = new Random();

                UserStates.Add(new UserState()
                {
                    UserId          = usr.Id,
                    UserName        = usr.Name,
                    TableFlipPoints = 0,
                    Favorability    = 0,
                    RPGMaxHP        = (int)25 + r.Next(1, 25),
                    RPGGold         = r.Next(1, 25),
                    RPGLevel        = 1,
                    RPGLosses       = 0,
                    RPGWins         = 0,
                    RPGXP           = 0
                });
                Save();
            }
        }
Example #28
0
        public static UserStates GetUserStateById(int id)
        {
            UserStates userStates = new UserStates();
            string     sql        = "select * from UserStates where Id=@id";

            try
            {
                SqlDataReader reader = DBHelper.GetReader(sql, new SqlParameter("@id", id));
                if (reader.Read())
                {
                    userStates.Id   = (int)reader["Id"];
                    userStates.Name = (string)reader["Name"];
                }
                reader.Close();
                return(userStates);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                return(null);
            }
        }
Example #29
0
 private bool SetStatus(UserStates newSt)
 {
     try
     {
         TelegramBot.sendMessage(this.userId, "Please FirstName");
         Logging.logMessage("UserNameInsert wait for firstnam");
         SQLiteCommand cmd = new SQLiteCommand();
         cmd.CommandText = "UPDATE USERS SET LASTSTATE=@ST WHERE ID=@Id";
         cmd.Parameters.AddWithValue("@St", (int)newSt);
         cmd.Parameters.AddWithValue("Id", userId);
         if (!(DataAccessSqlite.executeCommand(cmd) == 1))
             throw new Exception("Set " + newSt.ToString() + "+Error for user" + userId.ToString());
         this.lastState = newSt;
         return true;
     }
     catch (Exception ex)
     {
         Logging.logMessage(ex.Message);
         throw ex;
         return false;
     }
 }
Example #30
0
        public void AddNewUser(string id, string platform, UserStates stateEnum = UserStates.NotRegister)
        {
            var statesDict = new Dictionary <UserStates, int>
            {
                [UserStates.NotRegister]       = 0,
                [UserStates.RegisterInProcess] = 1,
                [UserStates.Register]          = 2,
                [UserStates.AddingLink]        = 3
            };
            var state  = statesDict[stateEnum];
            var dbName = dbNameProvider.GetDBName("PeopleAndGroups");

            using (var connection = new SQLiteConnection(string.Format("Data Source={0};", dbName)))
            {
                connection.Open();
                using (var command =
                           new SQLiteCommand(string.Format(
                                                 "INSERT INTO PeopleAndGroups ('ChatID', 'GROUP_', 'State', 'platform') VALUES ('{0}', '{1}', '{2}', '{3}')",
                                                 id, " ", state, platform), connection))
                {
                    try
                    {
                        command.ExecuteNonQuery();
                        Console.WriteLine("Hello from AddNewUser");
                    }
                    catch (Exception e)
                    {
                        if (e.Message == "constraint failed\r\nUNIQUE constraint failed: PeopleAndGroups.ChatID")
                        {
                            return;
                        }
                        Console.WriteLine(e);
                    }
                }
            }
        }
Example #31
0
        /// <summary>
        /// Переводом состояний
        /// </summary>
        public string GetUserStateTranslate(UserStates state)
        {
            string result = "";

            switch (state)
            {
            case (UserStates.Blocked):
                result = "Заблокирован";
                break;

            case (UserStates.Deleted):
                result = "Удален";
                break;

            case (UserStates.Registered):
                result = "Зарегестрирован";
                break;

            case (UserStates.Ungeristered):
                result = "Не зарегестрирован";
                break;
            }
            return(result);
        }
 public void AddCommandPack(UserStates userStates, ICommandPack commandPack)
 {
     this.commandPack.Add(userStates, commandPack);
 }
Example #33
0
        protected void SetUserState(UserStates state)
        {
            if (state.HasFlag(UserStates.SetIFace))
            {          // Userface
                //                if (Game.Platform == Platform.NES)
                //                    _userState = (_userState & ~USERSTATE_IFACE_ALL) | (state & USERSTATE_IFACE_ALL);
                //                else
                _userState = state & UserStates.IFaceAll;
            }

            if (state.HasFlag(UserStates.SetFreeze))
            {     // Freeze
                if (state.HasFlag(UserStates.FreezeOn))
                    FreezeScripts(0);
                else
                    UnfreezeScripts();
            }

            if (state.HasFlag(UserStates.SetCursor))
            {         // Cursor Show/Hide
                //                if (_game.Platform == Common::kPlatformNES)
                //                    _userState = (_userState & ~USERSTATE_CURSOR_ON) | (state & USERSTATE_CURSOR_ON);
                if (state.HasFlag(UserStates.CursorOn))
                {
                    _userPut = 1;
                    _cursor.State = 1;
                }
                else
                {
                    _userPut = 0;
                    _cursor.State = 0;
                }
            }

            // Hide all verbs and inventory
            Rect rect;
            rect.Top = VerbVirtScreen.TopLine;
            rect.Bottom = VerbVirtScreen.TopLine + 8 * 88;
            rect.Right = VerbVirtScreen.Width - 1;
            //            if (_game.platform == Common::kPlatformNES)
            //            {
            //                rect.left = 16;
            //            }
            //            else
            {
                rect.Left = 0;
            }
            RestoreBackground(rect);

            // Draw all verbs and inventory
            RedrawVerbs();
            RunInventoryScript(1);
        }
Example #34
0
 public User()
 {
     lastState = 0;
 }