예제 #1
0
        private void BtnClearName_Click(object sender, RoutedEventArgs e)
        {
            TxtBoxUserName.Text = String.Empty;
            TxtBoxUserName.Focus();

            e.Handled = true;
        }
예제 #2
0
 private void HandleCommand(string data) // обработчик команд с сервера
 {
     if (data.Contains("#updatechat"))
     {
         UpdateChat(data);
         return;
     }
     else if (data.Contains("#history&"))
     {
         GetHistory(data);
         return;
     }
     else if (data.Contains("#getonline&"))
     {
         GetOnline(data); // отображает список пользователей онлайн
         return;
     }
     else if (data.Contains("#auth&"))
     {
         if (menuStrip.InvokeRequired)
         {
             TxtBoxUserName.Invoke(new Action(() => регистрацияToolStripMenuItem.Enabled = false));
         }
         else
         {
             регистрацияToolStripMenuItem.Enabled = false;
         }
         _authoriz = true;
         return;
     }
     else if (data.Contains("#alreadyauth&"))
     {
         MessageBox.Show("Пользователь с этого аккаунта уже авторизирован!", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
         return;
     }
     else if (data.Contains("#badauth&"))
     {
         MessageBox.Show("Неверное имя пользователя или пароль!", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
         return;
     }
     else if (data.Contains("#badreg&"))
     {
         MessageBox.Show("Такое имя уже существует!", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
         return;
     }
     else if (data.Contains("#regandauth&"))
     {
         AuthSucsess();
         MessageBox.Show("Вы успешно зарегистрированны и авторизированы!", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information);
         return;
     }
     else if (data.Contains("#regoff&"))
     {
         MessageBox.Show("Регистрация на сервере выключена, обратитесь к администатору!", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
         return;
     }
 }
예제 #3
0
        private void ChatForm_Load(object sender, EventArgs e)
        {
            this.MinimumSize = new Size(796, 600);
            GetKeyIv();
            TxtBoxUserName.Select();
            //Создание объекта, для работы с файлом
            INIManager manager = new INIManager(Environment.CurrentDirectory.ToString() + "\\settings.ini");

            _serverIp   = manager.GetPrivateString("SERVER", "IP");
            _serverPort = int.Parse(manager.GetPrivateString("SERVER", "Port"));
        }
예제 #4
0
        private void ChatLogOff() // выйти из чата
        {
            if (BtnChatSend.InvokeRequired)
            {
                BtnChatSend.Invoke(new Action(() => BtnChatSend.Enabled = false));
            }
            else
            {
                BtnChatSend.Enabled = false;
            }

            if (TxtBoxChatMsg.InvokeRequired)
            {
                TxtBoxChatMsg.Invoke(new Action(() => TxtBoxChatMsg.Enabled = false));
            }
            else
            {
                TxtBoxChatMsg.Enabled = false;
            }

            if (BtnEnterChat.InvokeRequired)
            {
                BtnEnterChat.Invoke(new Action(() => BtnEnterChat.Enabled = true));
            }
            else
            {
                BtnEnterChat.Enabled = true;
            }

            if (BtnEnterChat.InvokeRequired)
            {
                BtnEnterChat.Invoke(new Action(() => BtnEnterChat.Text = "Войти"));
            }
            else
            {
                BtnEnterChat.Text = "Войти";
            }

            if (menuStrip.InvokeRequired)
            {
                TxtBoxUserName.Invoke(new Action(() => регистрацияToolStripMenuItem.Enabled = false));
            }
            else
            {
                регистрацияToolStripMenuItem.Enabled = false;
            }

            _authoriz   = false;
            _connection = false;
            ClearChat();        // очищаем чат
            ClearOnlineUsers(); // очищаем список онлайн пользователей
            EndSession();       // отключаемся от сервера
        }
예제 #5
0
        private void Listner() // слушаем сообщения с сервера
        {
            try
            {
                while (_serverSocket.Connected)                                                        // если сокет подключен к удаленному узлу, то считываем данные
                {
                    byte[] buffer   = new byte[65536];                                                 // создаем буфер для приема сообщений
                    int    bytesRec = _serverSocket.Receive(buffer);                                   // принимаем данные
                    Array.Resize(ref buffer, bytesRec);                                                // обрезаем массив байтов по длине полученного сообщения
                    buffer = DESCryptography.Decrypt(buffer, DESCryptography.Key, DESCryptography.Iv); // расшифровываем сообщение
                    string data = Encoding.UTF8.GetString(buffer);                                     // преобразуем массив байтов в текст
                    HandleCommand(data);                                                               // передаем сообщение в обработчик команд
                }
            }
            catch (Exception)
            {
                ClearChat();        // очищаем окно чата
                ClearOnlineUsers(); // очищаем список онлайн пользователей
                Print($"Вы были отключены от сервера!");

                // Возвращаем все элементы формы в начальное положеие
                if (menuStrip.InvokeRequired)
                {
                    TxtBoxUserName.Invoke(new Action(() => регистрацияToolStripMenuItem.Enabled = true));
                }
                else
                {
                    регистрацияToolStripMenuItem.Enabled = true;
                }

                if (TxtBoxUserName.InvokeRequired)
                {
                    TxtBoxUserName.Invoke(new Action(() => TxtBoxUserName.Enabled = true));
                }
                else
                {
                    TxtBoxUserName.Enabled = true;
                }

                if (TxtBoxUserPassword.InvokeRequired)
                {
                    TxtBoxUserPassword.Invoke(new Action(() => TxtBoxUserPassword.Enabled = true));
                }
                else
                {
                    TxtBoxUserPassword.Enabled = true;
                }

                if (BtnEnterChat.InvokeRequired)
                {
                    BtnEnterChat.Invoke(new Action(() => BtnEnterChat.Enabled = true));
                }
                else
                {
                    BtnEnterChat.Enabled = true;
                }

                if (BtnChatSend.InvokeRequired)
                {
                    BtnChatSend.Invoke(new Action(() => BtnChatSend.Enabled = false));
                }
                else
                {
                    BtnChatSend.Enabled = false;
                }

                if (TxtBoxChatMsg.InvokeRequired)
                {
                    TxtBoxChatMsg.Invoke(new Action(() => TxtBoxChatMsg.Enabled = false));
                }
                else
                {
                    TxtBoxChatMsg.Enabled = false;
                }

                if (BtnEnterChat.InvokeRequired)
                {
                    BtnEnterChat.Invoke(new Action(() => BtnEnterChat.Text = "Войти"));
                }
                else
                {
                    BtnEnterChat.Text = "Войти";
                }
            }
        }
예제 #6
0
        private void AuthSucsess()
        {
            // Активируем видимость элеменов чата и отключаем видимость элементов регистрации в чате

            if (TxtBoxChatMsg.InvokeRequired)
            {
                TxtBoxChatMsg.Invoke(new Action(() => TxtBoxChatMsg.Enabled = true));
            }
            else
            {
                TxtBoxChatMsg.Enabled = true;
            }

            if (BtnChatSend.InvokeRequired)
            {
                BtnChatSend.Invoke(new Action(() => BtnChatSend.Enabled = true));
            }
            else
            {
                BtnChatSend.Enabled = true;
            }

            if (TxtBoxUserPassword.InvokeRequired)
            {
                TxtBoxUserPassword.Invoke(new Action(() => TxtBoxUserPassword.Enabled = false));
            }
            else
            {
                TxtBoxUserPassword.Enabled = false;
            }

            if (TxtBoxUserName.InvokeRequired)
            {
                TxtBoxUserName.Invoke(new Action(() => TxtBoxUserName.Enabled = false));
            }
            else
            {
                TxtBoxUserName.Enabled = false;
            }

            if (TxtBoxChatMsg.InvokeRequired)
            {
                TxtBoxChatMsg.Invoke(new Action(() => TxtBoxChatMsg.Focus()));
            }
            else
            {
                TxtBoxChatMsg.Focus();
            }

            if (BtnEnterChat.InvokeRequired)
            {
                BtnEnterChat.Invoke(new Action(() => BtnEnterChat.Enabled = true));
            }
            else
            {
                BtnEnterChat.Enabled = true;
            }

            if (BtnEnterChat.InvokeRequired)
            {
                BtnEnterChat.Invoke(new Action(() => BtnEnterChat.Text = "Выйти"));
            }
            else
            {
                BtnEnterChat.Text = "Выйти";
            }
        }
예제 #7
0
        private void BtnOk_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;

            try
            {
                string name = TxtBoxUserName.Text.Trim();
                if (name.Contains("'"))
                {
                    MessageBox.Show(this, "含有非法字符 \"'\" !", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Stop);
                    TxtBoxUserName.Focus();
                    return;
                }
                if (WorkingState.Add == this.WorkingState)
                {
                    DataTable dataTable = TableUsersManage.QueryUserName(name);
                    if (dataTable.Rows.Count > 0)
                    {
                        MessageBox.Show(this, "已存在相同的用户名!", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Stop);
                        TxtBoxUserName.Focus();
                        return;
                    }
                }

                string password = TxtBoxPassword.Text.Trim();
                if (password.Contains("'"))
                {
                    MessageBox.Show(this, "含有非法字符 \"'\" !", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Stop);
                    TxtBoxPassword.Focus();
                    return;
                }
                if (string.IsNullOrWhiteSpace(password))
                {
                    MessageBox.Show(this, "密码不能为空!", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Stop);
                    TxtBoxPassword.Focus();
                    return;
                }

                string nickname = TxtBoxNickname.Text.Trim();
                if (nickname.Contains("'"))
                {
                    MessageBox.Show(this, "含有非法字符 \"'\" !", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Stop);
                    TxtBoxNickname.Focus();
                    return;
                }

                string privilege = ComboBoxPrivilege.Text;
                if (WorkingState.Add == this.WorkingState)
                {
                    int identity = TableUsersManage.AddUserAndReturnIdentity(name, password, privilege, nickname, DateTime.Now.ToLocalTime().ToString());
                    if (identity > 0)
                    {
                        this.DialogResult = DialogResult.OK;
                        this.Close();
                    }
                    else
                    {
                        MessageBox.Show(this, "添加用户失败!", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                else if (WorkingState.Modify == this.WorkingState)
                {
                    int suc = TableUsersManage.ModifyUserByUserName(name, password, privilege, nickname);
                    if (suc > 0)
                    {
                        this.DialogResult = DialogResult.OK;
                        this.Close();
                    }
                    else
                    {
                        MessageBox.Show(this, "修改用户失败!", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            Cursor.Current = Cursors.Default;
        }