/// <summary>
        /// Reads the socket.
        /// </summary>
        /// <param name="obj">The object.</param>
        private void readSocket(object obj)
        {
            //cast the obj which is a clientConnection
            ClientConnections connection = obj as ClientConnections;
            try
            {
                //size/data of read
                List<byte[]> listObject = new List<byte[]>();
                byte[] bytes = new byte[8192];
                byte[] fullObjectBytes;
                NetworkStream stream = connection.cSocket.GetStream();

                //check if connection is still open
                if (connection.cSocket.Connected)
                {
                    stream.Read(bytes, 0, bytes.Length);
                }
                else
                {
                    //stop timer if connection closed
                    connection.rTimer.stop();
                }
                listObject.Add(bytes);

                //Convert data recived to an object
                var bformatter = new BinaryFormatter();
                fullObjectBytes = bytes;
                Stream fullObjectStream = new MemoryStream(fullObjectBytes);
                object objFromClient = bformatter.Deserialize(fullObjectStream);
                Type objType = objFromClient.GetType();

                byte[] objectOut = new byte[0];//temp- the file data the will be sent to client

                if (objType == typeof(String))//client sent name
                {
                    connection.name = ((string)objFromClient);
                    objectOut = ObjectToByteArray("Connected");
                }
                else if (objType == typeof(Answer))//client gives you an answer (give them next question or their results)
                {
                    //Send client a question
                    Answer userAnswer = (Answer)objFromClient;

                    //check if first question
                    if (connection.question != -1)
                    {
                        List<string> queryRow = db.Select("Select questionNum,question,ans1,ans2,ans3,ans4,correctAnswer from questions where questionNum = " + connection.question).FirstOrDefault();

                        QACombo QARow = new QACombo(String.Join("|", queryRow));

                        if (userAnswer.answer == QARow.correctAnswer)
                        {
                            connection.score += userAnswer.timeLeft;
                        }
                        else
                        {
                            userAnswer.timeLeft = 0;
                        }
                        //Add users answer/result to results list
                        connection.results.Add(new Result(QARow.questionNum + "|" + QARow.question + "|" + queryRow[1 + QARow.correctAnswer] + "|" + queryRow[1 + userAnswer.answer]));
                        db.Insert("INSERT INTO questionattempts (questionId,timeLeft)VALUES(" + QARow.questionNum + "," + userAnswer.timeLeft + ")");
                    }
                    //get next question data
                    List<string> nextQuestion = db.Select("Select questionNum,question,ans1,ans2,ans3,ans4,correctAnswer from questions where questionNum > " + connection.question + " Order By questionNum ASC").FirstOrDefault();
                    if (nextQuestion != null)
                    {
                        //Create object to send to client
                        QACombo nextQ = new QACombo(String.Join("|", nextQuestion));
                        objectOut = ObjectToByteArray(nextQ);

                        connection.question = nextQ.questionNum;
                    }
                    else
                    {
                        //Add user to leaderboard
                        db.Insert("INSERT INTO leaderboard (name,score)VALUES('" + connection.name + "'," + connection.score + ")");
                        objectOut = ObjectToByteArray(connection.results);
                    }
                }
                else if (objType == typeof(CurrentStatus))//
                {
                    //List of current connections
                    List<CurrentStatus> statusList = new List<CurrentStatus>();
                    foreach (var con in connections)
                    {
                        if (con.question != -1)
                        {
                            CurrentStatus newStatus;
                            newStatus.name = con.name;
                            newStatus.score = con.score;
                            newStatus.questionNum = con.question;
                            statusList.Add(newStatus);
                        }
                    }
                    //Send list of current connection to admin
                    objectOut = ObjectToByteArray(statusList);
                }
                else if (objType == typeof(Leaderboard))
                {
                    //create leaderboard
                    List<List<string>> leader = db.Select("Select name, score from leaderboard order by score Desc");
                    List<Leaderboard> leaderBoard = new List<Leaderboard>();
                    foreach (var player in leader)
                    {
                        Leaderboard newLeaderboard;
                        newLeaderboard.name = player[0];
                        newLeaderboard.score = Convert.ToInt16(player[1]);
                        leaderBoard.Add(newLeaderboard);
                    }
                    leaderBoard.OrderBy(o => o.score).ToList();
                    //Send leaderboard to user
                    objectOut = ObjectToByteArray(leaderBoard);
                }
                else if (objType == typeof(ExcelData))
                {
                    //Create excel list for admin
                    List<ExcelData> excelDataList = new List<ExcelData>();
                    List<List<string>> excelRecords = db.Select("Select questionId, timeLeft from questionattempts");
                    List<List<string>> questionData = db.Select("Select questionNum, question from questions");
                    //Combine questionatttempts and question information to generate fields for excel
                    foreach (List<string> questionRecord in questionData)
                    {
                        int questionNumber = Convert.ToInt16(questionRecord[0]);
                        string questionText = questionRecord[1];

                        double avgTime = 0;
                        int count = 0;
                        double percentCorrect = 0;

                        foreach (var excelRecord in excelRecords)
                        {
                            if (excelRecord[0] == questionRecord[0])
                            {
                                avgTime += Convert.ToDouble(excelRecord[1]);

                                if (excelRecord[1] != "0")
                                {
                                    percentCorrect++;
                                }
                                count++;
                            }
                        }
                        avgTime = count != 0 ? avgTime /= count : 0;

                        percentCorrect = count != 0 ? percentCorrect /= count : 0;
                        percentCorrect *= 100;

                        excelDataList.Add(new ExcelData(questionNumber, questionText, avgTime, percentCorrect));
                    }
                    //Send excel data to admin
                    objectOut = ObjectToByteArray(excelDataList);
                }

                else if (objType == typeof(List<QACombo>))
                {
                    //Admin updates the question list
                    List<QACombo> QAList = (List<QACombo>)objFromClient;
                    if (QAList.Any())//Admin is changing questions
                    {
                        db.Delete("DELETE FROM questions");//Remove all questions
                        db.Delete("DELETE FROM questionattempts");//remove all questionattempts
                        //insert all new questions
                        foreach (var record in QAList)
                        {
                            db.Insert("INSERT INTO questions (questionNum,question,ans1,ans2,ans3,ans4,correctAnswer)VALUES(" + record.questionNum + ",'" + record.question + "','" + record.ans1 + "','" + record.ans2 + "','" + record.ans3 + "','" + record.ans4 + "'," + record.correctAnswer + ")");
                        }
                    }
                    else//Read all questions
                    {

                        List<QACombo> send = new List<QACombo>();

                        List<List<string>> thisQuestion = db.Select("Select questionNum,question,ans1,ans2,ans3,ans4,correctAnswer from questions");
                        foreach (List<string> record in thisQuestion)
                        {
                            send.Add(new QACombo(String.Join("|", record)));
                        }
                        //Send all questions to admin
                        objectOut = ObjectToByteArray(send);
                    }

                }
                //Send the data to the client
                stream.Write(objectOut, 0, objectOut.Length);
            }
            catch (IOException e)
            {
                connection.cSocket.Close();
                connection.rTimer.stop();
            }
            catch (SerializationException e)
            {
                connection.cSocket.Close();
                connection.rTimer.stop();
            }
            finally
            {
                for (int i = 0; i < connections.Count; i++)
                {
                    //Check if any clients have disconnected from the server
                    if (connections[i].cSocket.Connected == false)
                    {
                        //Remove the client from running clients list
                        connections.RemoveAt(i);
                    }
                }
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Handles the Click event of the btnSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        private void btnSave_Click(object sender, EventArgs e)
        {
            if (txtQuestion.Text != "" & txtAns1.Text != "" & txtAns2.Text != "" & txtAns3.Text != "" & txtAns4.Text != "" & (cbAns_1.Checked | cbAns_2.Checked | cbAns_3.Checked | cbAns_4.Checked))
            { //if none of the fields are blank
                if (!txtQuestion.Text.Contains('|') & !txtAns1.Text.Contains('|') & !txtAns2.Text.Contains('|') & !txtAns3.Text.Contains('|') & !txtAns4.Text.Contains('|'))
                { //if none of the fields contain a pipe symbol
                    int qid = (lbQuestions.SelectedIndex == -1) ? 0 : lbQuestions.SelectedIndex; //if the question id is -1, sets to 0

                    if (qid == 0)
                    { //make a new question
                        currentQA = new QACombo(Convert.ToString(GetLowestQNumber()) + "|" + txtQuestion.Text + "|" + txtAns1.Text + "|" + txtAns2.Text + "|" + txtAns3.Text + "|" + txtAns4.Text + "|" + (cbAns_1.Checked == true ? 1 : cbAns_2.Checked == true ? 2 : cbAns_3.Checked == true ? 3 : 4));
                        questionsList.Add(currentQA);
                        lbQuestions.Items.Add(currentQA.question);

                    }
                    else
                    { //edit an older question

                        currentQA = questionsList.ElementAt(qid - 1);
                        currentQA.question = txtQuestion.Text;
                        currentQA.ans1 = txtAns1.Text;
                        currentQA.ans2 = txtAns2.Text;
                        currentQA.ans3 = txtAns3.Text;
                        currentQA.ans4 = txtAns4.Text;
                        currentQA.correctAnswer = (cbAns_1.Checked == true ? 1 : cbAns_2.Checked == true ? 2 : cbAns_3.Checked == true ? 3 : 4);

                        lbQuestions.Items.RemoveAt(qid); //remove the older question
                        lbQuestions.Items.Add(currentQA.question); //add the new question

                        clearFields();
                    }
                    MessageBox.Show("Saved the question!");

                }
                else
                {
                    MessageBox.Show("Question not saved, invalid characters found in a text box. (No '|' allowed.)");
                }
            }
            else
            {
                MessageBox.Show("Question not saved. Must complete all fields.");
            }
        }
Ejemplo n.º 3
0
 /// <summary>
 /// Handles the SelectedIndexChanged event of the lbQuestions control.
 /// </summary>
 /// <param name="sender">The source of the event.</param>
 /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
 private void lbQuestions_SelectedIndexChanged(object sender, EventArgs e)
 {
     if(lbQuestions.SelectedItem != null) {
         string questionText = lbQuestions.SelectedItem.ToString(); //gets the text of the question
         if (questionText == "Add a new question...")
         {
             clearFields(); //clears all fields so a new question can be made
         }
         else
         {
             currentQA = questionsList.ElementAt((lbQuestions.SelectedIndex) - 1); //get the question from the question list
             txtQuestion.Text = currentQA.question; //set all the text
             txtAns1.Text = currentQA.ans1;
             txtAns2.Text = currentQA.ans2;
             txtAns3.Text = currentQA.ans3;
             txtAns4.Text = currentQA.ans4;
             switch ((checkBoxes)currentQA.correctAnswer)
             { //set the checkbox
                 case checkBoxes.ANS_ONE:
                     cbAns_1.Checked = true;
                     break;
                 case checkBoxes.ANS_TWO:
                     cbAns_2.Checked = true;
                     break;
                 case checkBoxes.ANS_THREE:
                     cbAns_3.Checked = true;
                     break;
                 case checkBoxes.ANS_FOUR:
                     cbAns_4.Checked = true;
                     break;
             }
             uncheckOthers((checkBoxes)currentQA.correctAnswer);
         }
     }
 }
Ejemplo n.º 4
0
        /// <summary>
        /// Gets the next question.
        /// </summary>
        public void GetNextQuestion()
        {
            lblQuestionText.Text = "Getting new question...";

            try //to get a new question
            {

                tmrTimeLeft.Enabled = false;
                //Int32 port = Convert.ToInt32(portStr);
                //client = new TcpClient(server, port);
                Answer ans = new Answer();
                ans.answer = cbAnswer_1.Checked == true ? 1 : cbAnswer_2.Checked == true ? 2 : cbAnswer_3.Checked == true ? 3 : 4;
                ans.question = questionNumber;
                ans.timeLeft = Convert.ToInt32(lblTimeLeft.Text);

                Byte[] data = ObjectToByteArray(ans);

                stream = host.GetStream();

                stream.Write(data, 0, data.Length); //send our answer

                List<byte[]> listObject = new List<byte[]>();
                byte[] bytes = new byte[8192];
                byte[] fullObjectBytes;

                stream.Read(bytes, 0, bytes.Length); //get a new question or the end of game
                listObject.Add(bytes);

                var bformatter = new BinaryFormatter();
                fullObjectBytes = bytes;
                Stream fullObjectStream = new MemoryStream(fullObjectBytes);
                object objFromServer = bformatter.Deserialize(fullObjectStream);
                Type objType = objFromServer.GetType();

                if (objType == typeof(QACombo)) //if new question
                {

                    currentQA = (QACombo)objFromServer;
                    setQAText();
                    tmrTimeLeft.Enabled = true;
                }
                else if (objType == typeof(List<Result>)) //if results(end of game)
                {

                    pAnswers.Visible = false;
                    pQuestions.Visible = false;
                    pEndQuestions.Visible = true;
                    pTimeLeft.Visible = false;
                    pStartScreen.Visible = false;
                    btnSubmit.Visible = false;

                    List<Result> results = (List<Result>)objFromServer;

                    foreach (var result in results)
                    { //print results
                        txtResults.Text += "\r\n#" + result.questionNumber + "\r\nQuestion: " + result.question + "\r\n Your answer: " + result.theirAnswer + "\r\n Correct answer: " + result.actualAnswer;
                    }
                    data = ObjectToByteArray(new Leaderboard());
                    stream.Write(data, 0, data.Length); //send blank leaderboard

                    stream.Read(bytes, 0, bytes.Length);  //receive leaderboard with data
                    listObject.Add(bytes);

                    fullObjectBytes = bytes;

                    fullObjectStream = new MemoryStream(fullObjectBytes);
                    objFromServer = bformatter.Deserialize(fullObjectStream);
                    objType = objFromServer.GetType();

                    txtResults.Clear();
                    List<Leaderboard> leaderboards = (List<Leaderboard>)objFromServer;
                    int count = 1;
                    foreach (var leaderboard in leaderboards)
                    { //print leaderboard
                        txtResults.Text += "#" + count++ + " " + leaderboard.name + " " + leaderboard.score + "\r\n";
                    }
                }
            }
            catch (ArgumentNullException ex)
            {

                MessageBox.Show("InvalidOperationException: {0}", ex.Message);
                Console.WriteLine("ArgumentNullException: {0}", ex);
                stream.Close();
                this.Close();
            }
            catch (SocketException ex)
            {
                MessageBox.Show("InvalidOperationException: {0}", ex.Message);
                Console.WriteLine("SocketException: {0}", ex);
                stream.Close();
                this.Close();
            }
            catch (IOException ex)
            {
                MessageBox.Show("InvalidOperationException: {0}", ex.Message);
                Console.WriteLine("IOException: {0}", ex);
                stream.Close();
                this.Close();
            }
            catch (SerializationException ex)
            {
                MessageBox.Show("InvalidOperationException: {0}", ex.Message);
                Console.WriteLine("SerializationException: {0}", ex);
                stream.Close();
                this.Close();
            }
            catch (InvalidOperationException ex)
            {
                MessageBox.Show("InvalidOperationException: {0}", ex.Message);
                Console.WriteLine("InvalidOperationException: {0}", ex);
                stream.Close();
                this.Close();
            }

            lblTimeLeft.Text = "20";
            tmrTimeLeft.Enabled = true;
        }