コード例 #1
0
 /// <summary>
 /// Spawns a new thread for TCP communication.
 /// </summary>
 private void StartServer()
 {
     try
     {
         th = new Thread(new ThreadStart(StartListen));
         th.Start();
     }
     catch (Exception ex)
     {
         MyMessageBox.ShowMessage("Failed to start the server: " + ex.ToString());
     }
 }
コード例 #2
0
 //The public key must be send to the client so they can
 //encrypt their symmetric key and send it back without the key being compromised
 private void SendPublicKey()
 {
     byte[] bt;
     bt = Encoding.UTF8.GetBytes(GetPublicKeyString());
     try
     {
         connectedClient.Client.Send(bt);
     }
     catch (Exception ex)
     {
         MyMessageBox.ShowMessage("Failed to send RSA public key: " + ex.ToString());
     }
 }
コード例 #3
0
 /// <summary>
 /// Retrieves the relevant records from TblStaff in the
 /// database and stores them in the staffMembers list.
 /// </summary>
 private void InitaliseList()
 {
     try
     {
         SqlConnector db = new SqlConnector();
         staffMembers = db.GetStaff_All();
     }
     catch
     {
         MyMessageBox.ShowMessage("Access to the database failed.");
         return;
     }
     UpdateStaffMemberList();
 }
コード例 #4
0
 private void ButtonSearch_Click(object sender, EventArgs e)
 {
     try
     {
         SqlConnector db = new SqlConnector();
         students = db.GetStudentList_BySearch(TextBoxSearchBar.Text);
     }
     catch
     {
         MyMessageBox.ShowMessage("Access to database failed.");
         return;
     }
     UpdateStudentList();
 }
コード例 #5
0
 private void ButtonAddNotes_Click(object sender, EventArgs e)
 {
     //If no student is selected, then display a message.
     //Otherwise, open a new AddNoteForm.
     if (ListBoxStudentList.SelectedItem == null)
     {
         MyMessageBox.ShowMessage("No student selected.");
     }
     else
     {
         AddNoteForm addNoteForm = new AddNoteForm(selectedStudent);
         addNoteForm.ShowDialog();
     }
 }
コード例 #6
0
        //Staff name must be sent before the client and server begin chatting,
        //so the users know who they're communicating with
        private void SendStaffName()
        {
            string encryptedMessage = ClassLibrary.SymmetricEncryptDecrypt(staffMember.StaffFirstName, symmetricKey);

            byte[] bt = Encoding.UTF8.GetBytes(encryptedMessage);

            try
            {
                connectedClient.Client.Send(bt);
            }
            catch (Exception ex)
            {
                MyMessageBox.ShowMessage("Failed to send staff first name: " + ex.ToString());
            }
        }
コード例 #7
0
        /// <summary>
        /// When a new item is selected in ListBoxNoteList,
        /// that note is to be displayed in TextBoxNoteViewer.
        /// </summary>
        private void UpdateNoteViewer()
        {
            try
            {
                SqlConnector db = new SqlConnector();
                notes = db.GetNote_ByNoteID(snl[ListBoxNoteList.SelectedIndex].NoteID);
            }
            catch
            {
                MyMessageBox.ShowMessage("Failed to load notes from the database.");
                return;
            }

            TextBoxNoteViewer.Text = notes[0].NoteContents;
        }
コード例 #8
0
 private void ButtonSearch_Click(object sender, EventArgs e)
 {
     try
     {
         //Updates the list of students according to what was input in the search box
         SqlConnector db = new SqlConnector();
         students = db.GetStudentList_BySearch(TextBoxSearchBar.Text);
     }
     catch
     {
         MyMessageBox.ShowMessage("Failed to load student list from the database.");
         return;
     }
     UpdateStudentList();
 }
コード例 #9
0
 /// <summary>
 /// Retrieves the relevant records from TblMeeting in the database and
 /// stores them in the meetings list.
 /// The ListBoxUpcomingMeetings is then populated using the meetings list.
 /// </summary>
 public void InitaliseList()
 {
     try
     {
         SqlConnector db = new SqlConnector();
         meetings = db.GetMeeting_ByStaffIDAndDate(staffMember.StaffID, DateTime.Now.Date);
     }
     catch
     {
         MyMessageBox.ShowMessage("Failed to load meetings from the database.");
         return;
     }
     ListBoxUpcomingMeetings.DataSource    = meetings;
     ListBoxUpcomingMeetings.DisplayMember = "StaffPOVUpcomingAppointment";
 }
コード例 #10
0
        /// <summary>
        /// Retrieves the relevant records from TblStudent in the
        /// database and stores them in the students list.
        /// </summary>
        private void InitaliseList()
        {
            try
            {
                SqlConnector db = new SqlConnector();
                students = db.GetStudent_All();
            }
            catch
            {
                MyMessageBox.ShowMessage("Access to database failed.");
                return;
            }

            UpdateStudentList();
        }
コード例 #11
0
 /// <summary>
 /// Retrieves the relevant records from TblMeeting in the database and
 /// stores them in the meetings list.
 /// The ListBoxUpcomingMeetings is then populated using the meetings list.
 /// </summary>
 private void InitaliseList()
 {
     //If access to the database fails, display a message to the user.
     try
     {
         SqlConnector db = new SqlConnector();
         meetings = db.GetMeeting_ByStudentIDAndDate(student.StudentID, DateTime.Now.Date);
     }
     catch
     {
         MyMessageBox.ShowMessage("Failed to load meetings from the database.");
         return;
     }
     ListBoxUpcomingMeetings.DataSource    = meetings;
     ListBoxUpcomingMeetings.DisplayMember = "StudentPOVUpcomingAppointment";
 }
コード例 #12
0
        /// <summary>
        /// Function to stop the server.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ButtonStopServer_Click(object sender, EventArgs e)
        {
            try
            {
                StopServer();
            }
            catch (Exception ex)
            {
                MyMessageBox.ShowMessage("Failed to stop the server: " + ex.ToString());
                return;
            }

            //Set the controls to show the server is offline
            TextBoxServerStatus.BackColor = Color.Red;
            ButtonStartServer.Enabled     = true;
            ButtonStopServer.Enabled      = false;
        }
コード例 #13
0
        /// <summary>
        /// When a new item is selected in ListBoxMessageList,
        /// that message is to be displayed in TextBoxMessageViewer
        /// </summary>
        private void UpdateMessageViewer()
        {
            try
            {
                SqlConnector db = new SqlConnector();
                messages = db.GetMessage_ByMessageID(sml[ListBoxMessageList.SelectedIndex].MessageID);
            }
            catch
            {
                MyMessageBox.ShowMessage("Failed to load message from the database.");
                return;
            }

            TextBoxMessageViewer.Text = messages[0].MessageContents;
            TextBoxDate.Text          = messages[0].MessageDate.ToString().Substring(0, 10);
            TextBoxTime.Text          = messages[0].MessageTime.ToString().Substring(0, 5);
        }
コード例 #14
0
        public void UpdateList()
        {
            try
            {
                SqlConnector db = new SqlConnector();
                oldMeetings = db.GetOldMeeting_ByStaffIDAndDate(staffMember.StaffID, DateTime.Now.Date);
            }
            catch
            {
                MyMessageBox.ShowMessage("Failed to load meetings from the database.");
                return;
            }

            ListBoxOldMeetings.DataSource    = oldMeetings;
            ListBoxOldMeetings.DisplayMember = "StaffPOVOldAppointment";
            TextBoxCounter.Text = oldMeetings.Count.ToString();
        }
コード例 #15
0
        private void ButtonStartServer_Click(object sender, EventArgs e)
        {
            try
            {
                StartServer();
            }
            catch (Exception ex)
            {
                MyMessageBox.ShowMessage(ex.ToString());
                return;
            }

            //Set the controls to show the server is operational
            TextBoxServerStatus.BackColor = Color.Green;
            ButtonStartServer.Enabled     = false;
            ButtonStopServer.Enabled      = true;
            TreeViewClientList.Enabled    = true;
        }
コード例 #16
0
        private void ButtonUpdatePassword_Click(object sender, EventArgs e)
        {
            //If the input data is valid
            if (ValidateForm())
            {   //If the current password is correct
                if (student.StudentPassword == TextBoxOldPassword.Text)
                {
                    //If the 2 new passwords match each other
                    if (TextBoxNewPassword.Text == TextBoxReTypePassword.Text)
                    {
                        try
                        {
                            SqlConnector db = new SqlConnector();
                            db.UpdateStudentPassword(student.StudentID, TextBoxReTypePassword.Text);
                        }
                        catch
                        {
                            MyMessageBox.ShowMessage("Action aborted. Access to database failed.");
                            ClearAllFields();
                            return;
                        }

                        student.StudentPassword = TextBoxReTypePassword.Text;
                        MyMessageBox.ShowMessage("Password successfully changed.");
                        ClearAllFields();
                    }
                    else
                    {
                        MyMessageBox.ShowMessage("New passwords do not match. Check your spelling and try again.");
                        ClearAllFields();
                    }
                }
                else
                {
                    MyMessageBox.ShowMessage("Incorrect password input.");
                    ClearAllFields();
                }
            }
            else
            {
                MyMessageBox.ShowMessage("Not all components validated successfully.");
                ClearAllFields();
            }
        }
コード例 #17
0
        private void ButtonDeleteMeeting_Click(object sender, EventArgs e)
        {
            if (meetings.Count() == 0 || ListBoxUpcomingMeetings.SelectedItem == null)
            {
                MyMessageBox.ShowMessage("No meetings to delete.");
            }
            else
            {
                MeetingModel        meeting   = meetings[ListBoxUpcomingMeetings.SelectedIndex];
                string              studentID = meeting.StudentID;
                int                 staffID   = meeting.StaffID;
                List <StudentModel> studentToEmail;

                try
                {
                    SqlConnector db = new SqlConnector();
                    db.DeleteMeeting_ByMeetingID(meeting.MeetingID);
                }
                catch
                {
                    MyMessageBox.ShowMessage("Action aborted. Access to database failed.");
                    return;
                }

                InitaliseList();

                //Find participating student
                try
                {
                    SqlConnector db = new SqlConnector();
                    studentToEmail = db.GetStudent_ByStudentID(studentID);
                }
                catch
                {
                    MyMessageBox.ShowMessage("Action aborted. Access to database failed.");
                    return;
                }

                //Email the participants
                SendEmail_CancelMeeting(studentToEmail[0].StudentEmail, staffMember.StaffFirstName, staffMember.StaffLastName, meeting);
                SendEmail_CancelMeeting(staffMember.StaffEmail, studentToEmail[0].StudentFirstName, studentToEmail[0].StudentLastName, meeting);
            }
        }
コード例 #18
0
        private void ButtonUpdatePassword_Click(object sender, EventArgs e)
        {
            //If the user input data validates correctly
            if (ValidateForm())
            {
                if (staffMember.StaffPassword == TextBoxOldPassword.Text)
                {
                    if (TextBoxNewPassword.Text == TextBoxReTypePassword.Text)
                    {
                        try
                        {
                            SqlConnector db = new SqlConnector();
                            db.UpdateStaffPassword(staffMember.StaffID, TextBoxReTypePassword.Text);
                        }
                        catch
                        {
                            MyMessageBox.ShowMessage("Action aborted. Access to database failed.");
                            return;
                        }

                        staffMember.StaffPassword = TextBoxReTypePassword.Text;
                        ClearAllFields();
                        MyMessageBox.ShowMessage("Password successfully changed.");
                    }
                    else
                    {
                        MyMessageBox.ShowMessage("New passwords do not match. Check your spelling and try again.");
                        ClearAllFields();
                    }
                }
                else
                {
                    MyMessageBox.ShowMessage("The password you entered was incorrect.");
                    ClearAllFields();
                }
            }
            else
            {
                MyMessageBox.ShowMessage("Not all components validated successfully.");
                ClearAllFields();
            }
        }
コード例 #19
0
 private void ButtonAddNote_Click(object sender, EventArgs e)
 {
     //If the TextBoxAddNote contains valid data
     if (ValidateForm_AddNote())
     {
         NoteModel n = new NoteModel(TextBoxNote.Text);
         try
         {
             //Add the note to the database
             GlobalConfig.Connection.CreateNote(n, student.StudentID);
         }
         catch
         {
             MyMessageBox.ShowMessage("Failed to add note.");
             return;
         }
         MyMessageBox.ShowMessage($"Note successfully added to {student.StudentFirstName} {student.StudentLastName}.");
         TextBoxNote.Text = "";
     }
 }
コード例 #20
0
 private void ButtonPinMessage_Click(object sender, EventArgs e)
 {
     if (ListBoxChat.SelectedItem != null)
     {
         MessageModel m = new MessageModel(ListBoxChat.SelectedItem.ToString(), DateTime.Now, DateTime.Now);
         try
         {
             GlobalConfig.Connection.CreateMessage(m, connectedStudent.StudentID);
             MyMessageBox.ShowMessage($"Message successfully pinned to {connectedStudent.StudentFirstName} {connectedStudent.StudentLastName}.");
         }
         catch
         {
             MyMessageBox.ShowMessage("Failed to pin message.");
         }
     }
     else
     {
         MyMessageBox.ShowMessage("Error: no message selected. Please select a message and try again.");
     }
 }
コード例 #21
0
 // If there are no pinned messages left to delete,
 //display a message saying so
 private void ButtonDeleteMessage_Click(object sender, EventArgs e)
 {
     if (sml.Count() == 0 || ListBoxMessageList.SelectedItem == null)
     {
         MyMessageBox.ShowMessage("No messages to delete.");
     }
     else
     {
         try
         {
             SqlConnector db = new SqlConnector();
             db.DeleteMessage_ByMessageID(sml[ListBoxMessageList.SelectedIndex].MessageID);
         }
         catch
         {
             MessageBox.Show("Action aborted. Access to database failed.");
             return;
         }
         InitaliseList();
     }
 }
コード例 #22
0
 private void ButtonDeleteStudent_Click(object sender, EventArgs e)
 {
     if (ListBoxStudentList.SelectedItem == null)
     {
         MyMessageBox.ShowMessage("No students to delete.");
     }
     else
     {
         try
         {
             SqlConnector db = new SqlConnector();
             db.DeleteStudent_ByStudentID(students[ListBoxStudentList.SelectedIndex].StudentID);
         }
         catch
         {
             MyMessageBox.ShowMessage("Action aborted: attempted to delete a student present in multiple tables.");
             return;
         }
         InitaliseList();
     }
 }
コード例 #23
0
 private void ButtonClearOldMeetings_Click(object sender, EventArgs e)
 {
     if (oldMeetings.Count > 0)
     {
         try
         {
             SqlConnector db = new SqlConnector();
             db.DeleteExpiredMeetings();
         }
         catch
         {
             MyMessageBox.ShowMessage("Action aborted. Access to database failed.");
             return;
         }
         UpdateList();
         MyMessageBox.ShowMessage("Expired meetings successfully cleared.");
     }
     else
     {
         MyMessageBox.ShowMessage("No meetings to delete.");
     }
 }
コード例 #24
0
 private void ButtonDeleteNote_Click(object sender, EventArgs e)
 {
     //If there are no notes to delete, display a message saying so
     if (snl.Count() == 0 || ListBoxNoteList.SelectedItem == null)
     {
         MyMessageBox.ShowMessage("No notes to delete.");
     }
     else
     {
         try
         {
             SqlConnector db = new SqlConnector();
             db.DeleteNote_ByNoteID(snl[ListBoxNoteList.SelectedIndex].NoteID);
         }
         catch
         {
             MessageBox.Show("Action aborted. Access to database failed.");
             return;
         }
         InitaliseList();
     }
 }
コード例 #25
0
        private void ButtonAddStudent_Click(object sender, EventArgs e)
        {
            const string REPEATSTUDENTIDERROR = "Student ID is already present in the database";

            if (ValidateForm())
            {
                StudentModel model = new StudentModel(
                    TextBoxStudentIDValue.Text,
                    TextBoxFirstNameValue.Text,
                    TextBoxLastNameValue.Text,
                    TextBoxStudentIDValue.Text);

                try
                {
                    GlobalConfig.Connection.CreateStudent(model);
                }
                catch (SqlException)
                {
                    MyMessageBox.ShowMessage("Failed to add student to the database: the specified student ID is already present in the database.");
                    ErrorProvider.SetError(TextBoxStudentIDValue, REPEATSTUDENTIDERROR);
                    return;
                }
                catch
                {
                    MyMessageBox.ShowMessage("Failed to access the database. ");
                    return;
                }

                MyMessageBox.ShowMessage("Successfully added new student to the database.");
                TextBoxStudentIDValue.Clear();
                TextBoxFirstNameValue.Clear();
                TextBoxLastNameValue.Clear();
                SendEmail_AddStudent(model);
            }
            else
            {
                MyMessageBox.ShowMessage("Not all components validated successfully. Please check the flagged entries and try again.");
            }
        }
コード例 #26
0
        /// <summary>
        /// Callback function called when data is received on the socket
        /// </summary>
        /// <param name="ar"></param>
        public void OnReceive(IAsyncResult ar)
        {
            string content = string.Empty;
            int    bytesRead;

            // Retrieve the state object and the handler socket
            //from the asynchronous state object.
            StateObject state        = (StateObject)ar.AsyncState;
            Socket      clientSocket = state.workSocket;

            if (clientSocket.Connected)
            {
                // Read data from the client socket.
                try
                {
                    bytesRead = clientSocket.EndReceive(ar);
                    if (bytesRead > 0)
                    {
                        if (!symmetricKeyReceived)
                        {
                            byte[] temp = state.buffer;
                            int    i    = temp.Length - 1;
                            while (temp[i] == 0)
                            {
                                --i;
                            }
                            // now data[i] is the last non-zero byte
                            byte[] receivedData = new byte[i + 1];
                            Array.Copy(temp, receivedData, i + 1);

                            //Get the symmetric key after decrypting it using RSA
                            byte[] decryptedKey       = rsa.Decrypt(receivedData, false);
                            string decryptedKeyString = Convert.ToBase64String(decryptedKey);

                            symmetricKey         = decryptedKeyString;
                            symmetricKeyReceived = true;

                            SendStaffName();

                            clientSocket.BeginReceive(state.buffer, 0, StateObject.BufferSize,
                                                      0, new AsyncCallback(OnReceive), state);

                            return;
                        }

                        // There might be more data, so store the data received so far.
                        state.sb.Remove(0, state.sb.Length);
                        state.sb.Append(Encoding.UTF8.GetString(state.buffer, 0, bytesRead));

                        if (!studentNameReceived)
                        {
                            string encryptedStudentID = state.sb.ToString();
                            string sID = ClassLibrary.SymmetricEncryptDecrypt(encryptedStudentID, symmetricKey);

                            try
                            {
                                SqlConnector        db           = new SqlConnector();
                                List <StudentModel> listStudents = db.GetStudent_ByStudentID(sID);
                                connectedStudent = listStudents[0];
                            }
                            catch
                            {
                                MyMessageBox.ShowMessage("Access to the database failed.");
                                return;
                            }

                            SetTextBoxStudentName();
                            studentNameReceived = true;

                            clientSocket.BeginReceive(state.buffer, 0, StateObject.BufferSize,
                                                      0, new AsyncCallback(OnReceive), state);

                            return;
                        }

                        // Display text in rich text box
                        string received = state.sb.ToString();
                        content = ClassLibrary.SymmetricEncryptDecrypt(received, symmetricKey);
                        SetText(content);
                        clientSocket.BeginReceive(state.buffer, 0, StateObject.BufferSize,
                                                  0, new AsyncCallback(OnReceive), state);
                    }
                    else
                    {
                        //Disconnect request has 0 bytes.
                        //So if 0 byte message detected: disable further communication.
                        SetSendButton(false);
                        SetTextBoxConnectionStatus(Color.Red);

                        clientStream.Dispose();
                        clientStream.Close();
                        connectedClient.Client.Dispose();
                        connectedClient.Client.Close();
                    }
                }
                catch (SocketException socketException)
                {
                    //WSAECONNRESET, the other side closed impolitely
                    if (socketException.ErrorCode == 10054 || ((socketException.ErrorCode != 10004) && (socketException.ErrorCode != 10053)))
                    {
                        // Complete the disconnect request.
                        string remoteIP =
                            ((IPEndPoint)clientSocket.RemoteEndPoint).Address.ToString();
                        string remotePort =
                            ((IPEndPoint)clientSocket.RemoteEndPoint).Port.ToString();
                        this.ownerForm.DisconnectClient(remoteIP, remotePort);
                        clientSocket.Close();
                        clientSocket = null;
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message.ToString());
                }
            }
        }
コード例 #27
0
        private void ButtonSendEmail_Click(object sender, EventArgs e)
        {
            ClassLibrary.CheckEmailIsValid(TextBoxEmail, ErrorProvider);

            //If the ErrorProvider has an error set, then display a message
            if (ErrorProvider.GetError(TextBoxEmail) != "")
            {
                MyMessageBox.ShowMessage("Not all components validated successfully. Please check the flagged entries and try again.");
                return;
            }
            else if (RadioButtonStudent.Checked == true)
            {
                List <StudentModel> students = new List <StudentModel>();

                try
                {
                    SqlConnector db = new SqlConnector();
                    students = db.GetStudent_All();
                }
                catch
                {
                    MyMessageBox.ShowMessage("Access to database failed.");
                    return;
                }

                //Search each StudentModel in the student list.
                //If the email the user input matches an email in the
                //database, send the email.
                for (int i = 0; i < students.Count; i++)
                {
                    if (students[i].StudentEmail == TextBoxEmail.Text)
                    {
                        ErrorProvider.SetError(TextBoxEmail, null);
                        //Send email
                        SendEmail(students[i].StudentEmail, students[i].StudentFirstName, students[i].StudentID, students[i].StudentPassword);
                        MyMessageBox.ShowMessage("Email successfully sent.");
                        return;
                    }
                }
            }
            else if (RadioButtonStaff.Checked)
            {
                List <StaffModel> staffMembers = new List <StaffModel>();

                try
                {
                    SqlConnector db = new SqlConnector();
                    staffMembers = db.GetStaff_All();
                }
                catch
                {
                    MyMessageBox.ShowMessage("Access to database failed.");
                    return;
                }

                for (int i = 0; i < staffMembers.Count; i++)
                {
                    if (staffMembers[i].StaffEmail == TextBoxEmail.Text)
                    {
                        ErrorProvider.SetError(TextBoxEmail, null);
                        //Send email
                        SendEmail(staffMembers[i].StaffEmail, staffMembers[i].StaffFirstName, staffMembers[i].StaffEmail, staffMembers[i].StaffPassword);
                        MyMessageBox.ShowMessage("Email successfully sent.");
                        return;
                    }
                }
            }

            MyMessageBox.ShowMessage("This email doesn't exist in the database.");
        }
コード例 #28
0
        private void ButtonCreateMeeting_Click(object sender, EventArgs e)
        {
            //If all the controls validated correctly
            if (ValidateForm_CreateMeeting())
            {
                int meetingLength;

                if (CheckBoxCustomLength.Checked)
                {
                    meetingLength = int.Parse(TextBoxCustomLength.Text);
                }
                else
                {
                    meetingLength = timeOptions[ListBoxMeetingLengths.SelectedIndex];
                }

                //Get the staff member selected in the listbox
                StaffModel selectedStaffMember = staffMembers[ListBoxStaffList.SelectedIndex];

                //Create a new meeting
                MeetingModel meeting = new MeetingModel(
                    selectedStudent.StudentID,
                    DateTimePickerDate.Value,
                    DateTimePickerTime.Value,
                    meetingLength,
                    selectedStaffMember.StaffID);

                try
                {
                    GlobalConfig.Connection.CreateMeeting(meeting);
                }
                catch
                {
                    MyMessageBox.ShowMessage("Failed to add meeting to the database.");
                    return;
                }
                MyMessageBox.ShowMessage("Successfully scheduled the meeting");

                try
                {
                    //Update the selected student's record in the database to show they have had a meeting before
                    SqlConnector db = new SqlConnector();
                    db.UpdateIsNewStudent(selectedStudent.StudentID);
                }
                catch
                {
                    MyMessageBox.ShowMessage("Failed to update student's status.");
                    return;
                }

                TextBoxCustomLength.Clear();

                //Email the participants
                SendEmail_ScheduleMeeting(meeting, selectedStudent.StudentEmail, selectedStaffMember.StaffFirstName, selectedStaffMember.StaffLastName);
                SendEmail_ScheduleMeeting(meeting, selectedStaffMember.StaffEmail, selectedStudent.StudentFirstName, selectedStudent.StudentLastName);
            }
            else
            {
                MyMessageBox.ShowMessage("Not all components validated successfully. Please check the flagged entries and try again.");
            }
        }
コード例 #29
0
        private void ButtonLogIn_Click(object sender, EventArgs e)
        {
            //True if all the components validate successfully
            if (ValidateForm())
            {
                //Checks whether it is a student or staff member attempting to login
                if (RadioButtonStudent.Checked == true)
                {
                    List <StudentModel> studentLogInDetails = new List <StudentModel>();
                    try
                    {
                        //Attempt to retrieve the record from TblStudent in the database that exactly matches the data
                        //input to TextBoxUsername and TextBoxPassword.
                        SqlConnector db = new SqlConnector();
                        studentLogInDetails = db.GetStudent_ByLogInDetails(TextBoxUsername.Text, TextBoxPassword.Text);
                    }
                    catch
                    {
                        MyMessageBox.ShowMessage("Access to the database failed.");
                        return;
                    }

                    if (studentLogInDetails.Count() == 1)
                    {
                        this.Hide();
                        StudentMainForm studentMainForm = new StudentMainForm(studentLogInDetails[0]);
                        studentMainForm.ShowDialog();
                        this.Close();
                    }
                    else
                    {
                        MyMessageBox.ShowMessage("Check your username and password.");
                    }
                }
                else if (RadioButtonStaff.Checked == true)
                {
                    List <StaffModel> staffLogInDetails = new List <StaffModel>();
                    try
                    {
                        SqlConnector db = new SqlConnector();
                        staffLogInDetails = db.GetStaff_ByLogInDetails(TextBoxUsername.Text, TextBoxPassword.Text);
                    }
                    catch
                    {
                        MyMessageBox.ShowMessage("Access to the database failed.");
                        return;
                    }

                    if (staffLogInDetails.Count() == 1)
                    {
                        this.Hide();
                        StaffMainForm staffMainForm = new StaffMainForm(staffLogInDetails[0]);
                        staffMainForm.ShowDialog();
                        this.Close();
                    }
                    else
                    {
                        MyMessageBox.ShowMessage("Check your username and password.");
                    }
                }
            }
            else
            {
                MyMessageBox.ShowMessage("Not all components validated successfully. Please check the flagged entries and try again.");
            }
        }
コード例 #30
0
        /// <summary>
        /// A callback function triggered when data is received on the socket.
        /// </summary>
        /// <param name="ar"></param>
        public void OnReceive(IAsyncResult ar)
        {
            string content = string.Empty;

            //Retrieve the state object and the handler socket from the asynchronous state object
            state = (StateObject)ar.AsyncState;
            Socket handler = state.workSocket;

            int bytesRead;

            if (handler.Connected)
            {
                //Read data from the client socket
                try
                {
                    bytesRead = handler.EndReceive(ar);

                    if (bytesRead > 0)
                    {
                        //There might be more data, so store the data received so far
                        state.sb.Remove(0, state.sb.Length);
                        //Translate the bytes into a readable format
                        state.sb.Append(Encoding.UTF8.GetString(state.buffer, 0, bytesRead));
                        string s = state.sb.ToString();
                        //Before the server and client can begin chatting, the server must send its
                        //public key over, the client then sends a generated symmetric key back, encrypted
                        //using the public key. Then the server must send the staff member's name while
                        //the client must send the student ID.
                        if (!publicKeyReceived)
                        {
                            rsa = new RSACryptoServiceProvider(2048);
                            //Save the public key received to rsa
                            rsa.FromXmlString(state.sb.ToString());

                            SendSymmetricKey();

                            publicKeyReceived = true;

                            //Continue to asynchronously receive data from the server
                            handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                                                 new AsyncCallback(OnReceive), state);

                            return;
                        }

                        if (!nameReceived)
                        {
                            SendStudentID();

                            string encryptedStaffName = state.sb.ToString();
                            staffName    = ClassLibrary.SymmetricEncryptDecrypt(encryptedStaffName, symmetricKey);
                            nameReceived = true;

                            handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                                                 new AsyncCallback(OnReceive), state);

                            return;
                        }

                        //Display text in TextBox
                        string received = state.sb.ToString();
                        content = ClassLibrary.SymmetricEncryptDecrypt(received, symmetricKey);
                        //Function used to display text in the rich text box. A delegate function
                        //must be used as we're not on the main thread.
                        SetText(content);
                        handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                                             new AsyncCallback(OnReceive), state);
                    }
                    else
                    {
                        //If no data is received, then an error has occured as null messages cannot be sent.
                        MyMessageBox.ShowMessage("Error occured: no data was supplied.");
                    }
                }
                catch (SocketException socketEx)
                {
                    //WSAECONNRESET: if the other side closes impolitely
                    //(they shut down the server or crash for some reason)
                    //Cut the connection and reset everything
                    if (socketEx.ErrorCode == 10054 || ((socketEx.ErrorCode != 10004) && (socketEx.ErrorCode != 10053)))
                    {
                        handler.Close();
                        SetTextBoxConnectionStatusBackgroundColour(Color.Red);
                        SetSendButton(false);
                        SetConnectButton(true);
                        SetDisconnectButton(false);
                        serverStream.Close();
                        server.Close();
                        nameReceived      = false;
                        publicKeyReceived = false;
                    }
                }
                catch (Exception ex)
                {
                    //Anyother unexpected error is displayed here
                    MyMessageBox.ShowMessage(ex.Message);
                }
            }
            else
            {
                handler.Close();
            }
        }