/// <summary>
        /// Function called when the user attempts to create a meeting.
        /// The ErrorProvider only set an error if the event TextBox_Validating is fired. If the user presses
        /// the schedule meeting button before this event can be triggered, it would appear as though the data is valid as
        /// there would be no ErrorProvider message. Therefore, when that button is pressed, each control
        /// must be validated.
        /// </summary>
        /// <returns>A boolean indicating whether the input data is valid or not.</returns>
        private bool ValidateForm_CreateMeeting()
        {
            bool isValid = true;
            //Lamda expression to compare the ErrorProviders error message with the constant ERRORMESSAGE.
            //If they are equal, compareString returns true.
            Func <string, bool> compareString = s => s == NULLDATAERRORMESSAGE;

            //Alternative to writing IF statements that improve readability since the use far less lines
            ClassLibrary.CheckTextBoxNotNull(TextBoxSelectedStudent, ErrorProvider);
            isValid = compareString(ErrorProvider.GetError(TextBoxSelectedStudent)) ? false : isValid;
            CheckDateTimePickerNotNull(DateTimePickerDate);
            isValid = compareString(ErrorProvider.GetError(DateTimePickerDate)) ? false : isValid;
            CheckDateTimePickerNotNull(DateTimePickerTime);
            isValid = compareString(ErrorProvider.GetError(DateTimePickerTime)) ? false : isValid;
            CheckListBoxNotNull(ListBoxStaffList);
            isValid = compareString(ErrorProvider.GetError(ListBoxStaffList)) ? false : isValid;

            //Whether the checkbox is checked or not determines which control to validate
            if (CheckBoxCustomLength.Checked)
            {
                ClassLibrary.CheckTextBoxNotNull(TextBoxCustomLength, ErrorProvider);
                isValid = compareString(ErrorProvider.GetError(TextBoxCustomLength)) ? false : isValid;
            }
            else
            {
                CheckListBoxNotNull(ListBoxMeetingLengths);
                isValid = compareString(ErrorProvider.GetError(ListBoxMeetingLengths)) ? false : isValid;
            }

            return(isValid);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Function to send data to the client.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ButtonSendMessage_Click(object sender, EventArgs e)
        {
            const string NULLDATAERRORMESSAGE = "Field cannot be left empty";

            //If there is no message to send, display an error message in the ErrorProvider
            ClassLibrary.CheckTextBoxNotNull(TextBoxTypeMessage, ErrorProvider);
            if (ErrorProvider.GetError(TextBoxTypeMessage) == NULLDATAERRORMESSAGE)
            {
                return;
            }

            //Encrypt the message and transmit it
            string encryptedMessage = ClassLibrary.SymmetricEncryptDecrypt(TextBoxTypeMessage.Text, symmetricKey);

            byte[] bt = Encoding.UTF8.GetBytes(encryptedMessage);
            try
            {
                connectedClient.Client.Send(bt);
            }
            catch (Exception ex)
            {
                MyMessageBox.ShowMessage(ex.ToString());
                return;
            }

            //Display the text in the list box
            ListBoxChat.Items.Add(staffMember.StaffFirstName + ": " + TextBoxTypeMessage.Text + Environment.NewLine);
            TextBoxTypeMessage.Clear();
        }
        private void ButtonSendMessage_Click(object sender, EventArgs e)
        {
            const string NULLDATAERRORMESSAGE = "Field cannot be left empty";

            ClassLibrary.CheckTextBoxNotNull(TextBoxTypeMessage, ErrorProvider);
            //As long as the user has some sort of input in the textbox, the message will send
            if (ErrorProvider.GetError(TextBoxTypeMessage) == NULLDATAERRORMESSAGE)
            {
                return;
            }

            //Encrypt the message
            string encryptedMessage = ClassLibrary.SymmetricEncryptDecrypt(TextBoxTypeMessage.Text, symmetricKey);

            //Encode the message and send it
            serverStream.Write(Encoding.UTF8.GetBytes(encryptedMessage), 0, Encoding.UTF8.GetByteCount(encryptedMessage));
            serverStream.Flush();

            //Display the message to the rich text box
            sbSend.Clear();
            sbSend.Append(student.StudentFirstName);
            sbSend.Append(": ");
            sbSend.Append(TextBoxTypeMessage.Text);
            sbSend.Append(Environment.NewLine);

            RichTextBoxChatWindow.SelectionColor = Color.Blue;
            RichTextBoxChatWindow.AppendText(sbSend.ToString());
            TextBoxTypeMessage.Clear();
        }
        private void SendStudentID()
        {
            string sID = ClassLibrary.SymmetricEncryptDecrypt(student.StudentID, symmetricKey);

            serverStream.Write(Encoding.UTF8.GetBytes(sID), 0, Encoding.UTF8.GetByteCount(sID));
            serverStream.Flush();
        }
        /// <summary>
        /// Checks that the user input data is valid.
        /// </summary>
        /// <returns>A boolean indicating whether the input data is
        /// valid or not.</returns>
        private bool ValidateForm()
        {
            const string        NULLDATAERRORMESSAGE = "Field cannot be left empty";
            bool                isValid       = true;
            Func <string, bool> compareString = s => s == NULLDATAERRORMESSAGE;

            ClassLibrary.CheckTextBoxNotNull(TextBoxOldPassword, ErrorProvider);
            isValid = compareString(ErrorProvider.GetError(TextBoxOldPassword)) ? false : isValid;
            ClassLibrary.CheckTextBoxNotNull(TextBoxNewPassword, ErrorProvider);
            isValid = compareString(ErrorProvider.GetError(TextBoxNewPassword)) ? false : isValid;
            ClassLibrary.CheckTextBoxNotNull(TextBoxReTypePassword, ErrorProvider);
            isValid = compareString(ErrorProvider.GetError(TextBoxReTypePassword)) ? false : isValid;

            return(isValid);
        }
Ejemplo n.º 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());
            }
        }
        /// <summary>
        /// Checks that the user input data is valid.
        /// </summary>
        /// <returns>A boolean indicating whether the
        /// input data is valid or not.</returns>
        private bool ValidateForm_AddNote()
        {
            bool isValid = true;
            //Lamda expression to compare the ErrorProviders
            //error message with the constant NULLDATAERRORMESSAGE.
            //If they are equal, compareString returns true.
            Func <string, bool> compareString = s => s == NULLDATAERRORMESSAGE;

            ClassLibrary.CheckTextBoxNotNull(TextBoxNote, ErrorProvider);
            //Alternative to writing IF statements that improves
            //readability since they use far less lines.
            isValid = compareString(ErrorProvider.GetError(TextBoxNote)) ? false : isValid;

            return(isValid);
        }
        /// <summary>
        /// Verifies that all the user input data is valid.
        /// </summary>
        /// <returns>A boolean indicating whether the
        /// input data is valid or not.</returns>
        private bool ValidateForm()
        {
            bool isValid = true;
            //Lamda expression comparing the input to "" (null data).
            //Returns true if they are equal.
            Func <string, bool> compareString = s => s == "";

            CheckIDIsValid();
            //If the error message is null (i.e. there is no error message),
            //isValid remains the same.
            isValid = compareString(ErrorProvider.GetError(TextBoxStudentIDValue)) ? isValid : false;
            ClassLibrary.CheckNameIsValid(TextBoxFirstNameValue, ErrorProvider);
            isValid = compareString(ErrorProvider.GetError(TextBoxFirstNameValue)) ? isValid : false;
            ClassLibrary.CheckNameIsValid(TextBoxLastNameValue, ErrorProvider);
            isValid = compareString(ErrorProvider.GetError(TextBoxLastNameValue)) ? isValid : false;

            return(isValid);
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Checks that the user input data is valid.
        /// </summary>
        /// <returns>A boolean indicating whether the input data is valid or not.</returns>
        private bool ValidateForm()
        {
            const string NULLDATAERRORMESSAGE = "Field cannot be left empty";
            bool         isValid = true;
            //Lamda expression to compare the ErrorProviders error message with the
            //constant NULLDATAERRORMESSAGE. If they are equal, compareString returns true.
            Func <string, bool> compareString = s => s == NULLDATAERRORMESSAGE;

            //Each control that has user input data must be checked.
            ClassLibrary.CheckTextBoxNotNull(TextBoxUsername, ErrorProvider);
            //Alternative to writing IF statements that improves readability since they use far less lines.
            //If compareString returns true, then isValid is set to false as this means the
            //ErrorProvider has set an error so the input is invalid.
            isValid = compareString(ErrorProvider.GetError(TextBoxUsername)) ? false : isValid;
            ClassLibrary.CheckTextBoxNotNull(TextBoxPassword, ErrorProvider);
            isValid = compareString(ErrorProvider.GetError(TextBoxPassword)) ? false : isValid;

            return(isValid);
        }
        /// <summary>
        /// Verifys that the user input data is valid.
        /// </summary>
        /// <returns>A boolean indicating whether the components
        /// have validated correctly or not.</returns>
        private bool ValidateForm()
        {
            bool isValid = true;
            //Lamda expression that compares an input to null data.
            //Returns true if the supplied input is null.
            Func <string, bool> compareString = s => s == "";

            ClassLibrary.CheckNameIsValid(TextBoxFirstNameValue, ErrorProvider);
            //Alternative to writing IF statements to improve readability.
            //isValid remains the same (in this case, TRUE) if the ErrorProvider
            //has no error set, otherwise it is set to false
            isValid = compareString(ErrorProvider.GetError(TextBoxFirstNameValue)) ? isValid : false;
            ClassLibrary.CheckNameIsValid(TextBoxLastNameValue, ErrorProvider);
            isValid = compareString(ErrorProvider.GetError(TextBoxLastNameValue)) ? isValid : false;
            ClassLibrary.CheckEmailIsValid(TextBoxStaffEmailValue, ErrorProvider);
            isValid = compareString(ErrorProvider.GetError(TextBoxStaffEmailValue)) ? isValid : false;

            //Returns true if all components validate successfully
            return(isValid);
        }
 private void TextBoxSelectedStudent_Validating(object sender, CancelEventArgs e)
 {
     ClassLibrary.CheckTextBoxNotNull(TextBoxSelectedStudent, ErrorProvider);
 }
Ejemplo n.º 12
0
 private void TextBoxPassword_Validating(object sender, CancelEventArgs e)
 {
     //Checks that the TextBoxPassword contains data
     ClassLibrary.CheckTextBoxNotNull(TextBoxPassword, ErrorProvider);
 }
        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.");
        }
 private void TextBoxEmail_Validating(object sender, CancelEventArgs e)
 {
     ClassLibrary.CheckEmailIsValid(TextBoxEmail, ErrorProvider);
 }
        /// <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();
            }
        }
Ejemplo n.º 16
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());
                }
            }
        }
 private void TextBoxLastNameValue_Validating(object sender, CancelEventArgs e)
 {
     ClassLibrary.CheckNameIsValid(TextBoxLastNameValue, ErrorProvider);
 }
 //Events
 private void TextBoxCustomLength_Validating(object sender, CancelEventArgs e)
 {
     ClassLibrary.CheckTextBoxNotNull(TextBoxCustomLength, ErrorProvider);
 }