Examining the Quizzer Program

As usual, the final program for the chapter does not introduce any new code or ideas. The Quizzer game simply puts together the concepts you have learned into an interesting package. I also borrowed heavily from the Adventure Kit game in Chapter 9 because the underlying structure is quite similar. The program has a main menu screen, which calls an editor and a quiz program.

Building the Main Form

The main form (XmlMainForm) is the simplest form of the project. It consists of three buttons, which call the other forms or exit the program altogether.

Creating Instance Variables

XmlMainForm has only two instance variables. Both are instances of the other two forms in the project:

private frmQuiz theQuiz;
private frmEdit theEditor;

These variables will be used to create the other forms when they are needed.

Creating the Visual Design of the Form

The visual design of XmlMainForm is quite simple. It has three buttons. The first two buttons call other forms, and the last one exits the program (see Figure 10.18).

Figure 10.18. As usual, the layout of the main form is extremely simple.


Responding to the Button Events

All the important work is encapsulated in the various other forms, so the main buttons call these forms to do their work:

private void btnTake_Click(object sender,
         System.EventArgs e) { 
  theQuiz = new frmQuiz();
  theQuiz.Show();
} // end btnTake

private void btnEdit_Click(object sender,
         System.EventArgs e) {
  theEditor = new frmEdit();
  theEditor.Show();
} // end btnEdit

private void btnQuit_Click(object sender,
         System.EventArgs e) {
  Application.Exit();
} // end btnQuit

The Quit button uses the Application.Exit() method to close the entire application.

Writing the Quiz Form

The quiz form is responsible for displaying the quiz. It examines an XML document and copies the appropriate information to the form elements. It also has the capability to navigate to other questions and grade the quiz.

Designing the Visual Layout

The quiz form is designed to show one problem at a time. The question goes in a label at the top of the screen, and the various answers are placed in radio buttons (also called option buttons).

NOTE

IN THE REAL WORLD

Of all the visual design elements, radio buttons seem to have the most inconsistent naming convention. Some languages call them radio buttons, some call them option buttons, and some call them grouped check boxes. C# uses the term radio buttons, but many programmers still call them option buttons because that’s what they were called in Visual Basic. It doesn’t matter how you refer to them in your own code, as long as you’re consistent. However, if you’re working on a professional project with a group of programmers, you will probably be required to follow a standard naming convention.

Two buttons enable navigation forward and backward through the quiz, and a label indicates which question is currently being displayed.

The form also features a small menu structure. The File menu has Open, Exit, and Grade options. Figure 10.19 shows the form in the designer.

Figure 10.19. The FrmQuiz form has a label for the question and radio buttons for the answers


Creating Instance Variables

The instance variables for the quiz form are used primarily to examine the underlying XML document:

private XmlDocument doc;
private XmlNode theTest;
private int qNum = 0;
private int numQuestions = 0;
private string[] response;

I created XmlDocument and XmlNode variables to hold the document and the various elements. The qNum variable holds the question number. numQuestions holds the number of questions, and response is a string array to hold the user’s responses to the questions.

Initializing in the Load Event

In the form’s load event, I created a new XmlDocument and loaded the sample test into it. The code runs more smoothly if there is always an XML document loaded, so I forced the sample document to be loaded as a default. Of course, the user will be able to load any other quiz he or she wants. The resetQuiz() method (described in the next section) will initialize the quiz and display the first question:

private void frmQuiz_Load(object sender,
         System.EventArgs e) {
   doc = new XmlDocument();
   doc.Load("sampleTest.qml");
   resetQuiz();
 } // end Load

Resetting the Quiz

The program needs to initialize a quiz a couple times (generally after a new quiz has been loaded). The resetQuiz() method prepares the quiz:

private void resetQuiz(){
  theTest = doc.ChildNodes[1];
  numQuestions = theTest.ChildNodes.Count;
  response = new String[numQuestions];
  for (int i = 0; i < numQuestions; i++){
    response[i] = "X";
  } // end for loop
  qNum = 0;
  showQuestion(0);
} // end resetQuiz

I began by assigning theTest the first child of the document. The program can then determine the number of questions by accessing theTest’s ChildNodes property. ChildNodes is a collection, so it has a Count property.

When the user begins a new quiz, it is also necessary to initialize the response array. This array will hold all the user responses so that the quiz can be graded. I set the initial value of each response to "X" to indicate that the question has not yet been answered. This way, if a user gets a question incorrect, it will be possible to tell whether he or she responded at all. (I didn’t take advantage of this feature in this version of the quiz program, but it doesn’t hurt to set up things this way.) I set qNum to 0 and showed question zero using the showQuestion() method.

Moving to the Preceding Question

The user will navigate through the quiz by clicking buttons. The Prev button moves backward one element in the document, stores the user’s response with the getResponse() method, checks to ensure that the user has not passed the beginning of the document, and displays the appropriate node using the showQuestion() method:

private void btnPrev_Click(object sender,
         System.EventArgs e) {
  getResponse();
  qNum--;
  if (qNum < 0){
    MessageBox.Show("First Question");
    qNum = 0;
  } else {
    showQuestion(qNum);
  } // end if
} // end btnPrev

Moving to the Next Question

The code for the Next button is very similar to the code for the Prev button, except that the logic is different when the user reaches the last item in the quiz:

private void btnNext_Click(object sender,
         System.EventArgs e) {
   getResponse();
   qNum++;
   if (qNum >= numQuestions){
     qNum = theTest.ChildNodes.Count -1;
     if (MessageBox.Show("Last Question. Grade Quiz?",
         "Last Question",
         MessageBoxButtons.YesNo,
         MessageBoxIcon.Question) == DialogResult.Yes){
       gradeTest();
     } // end if
   } else {
     showQuestion(qNum);
   } // end if
 } // end btnNext

If the user has moved beyond the last item, the program resets the question number to the last question and informs the user of the situation. The method uses a message box to ask whether the user wants to grade the program. (It is logical that the user might want a grade at the end of the quiz, but it’s also possible that he or she will want to back up and review his or her answers first.)

If the user responds yes to the message box, the gradeTest() method calculates the user’s score. If the user is not past the end of the quiz, the showQuestion() method displays the new question.

Checking the Radio Buttons for a Response

The user indicates his or her responses to the questions by choosing one of the radio buttons. The program needs to store this information so that the grading method will be able to compare each user response to the corresponding correct answer. The easiest way to store the responses is with an array. The response array stores one string for each question in the quiz. The btnNext() and btnPrev() methods call this method before the user moves away from a question, so the response array should always indicate all the user’s responses (or an "X" if the user has not yet responded to a particular question).

private void getResponse(){
  //queries the buttons for user input, copies to response array
  if (optA.Checked){
  response[qNum] = "A";
  } else if (optB.Checked){
  response[qNum] = "B";
  } else if (optC.Checked){
  response[qNum] = "C";
  } else if (optD.Checked){
  response[qNum] = "D";
  } else {
  response[qNum] = "X";
  } // end if
} // end get response

The getResponse() method simply looks at all the option buttons to see which one is checked and sets the response element that corresponds with the current question to a value indicating the user’s response. If the user has not clicked any option buttons, the current response element will get the value "X".

Displaying a Question

The showQuestion() method is the workhorse of the quiz form. It accepts a question number as a parameter, extracts the appropriate question from the XML document, and displays the question on the form:

private void showQuestion(int qNum){
  theTest = doc.ChildNodes[1];
  XmlNode theProblem = theTest.ChildNodes[qNum];
  lblQuestion.Text = theProblem["question"].InnerText;
  optA.Text = theProblem["answerA"].InnerText;
  optB.Text = theProblem["answerB"].InnerText;
  optC.Text = theProblem["answerC"].InnerText;
  optD.Text = theProblem["answerD"].InnerText;

  lblNum.Text = Convert.ToString(qNum);

  //clear up the checkBoxes
  optA.Checked = false;
  optB.Checked = false;
  optC.Checked = false;
  optD.Checked = false;

  //indicate response if there is one
  if (response[qNum] == "A"){
    optA.Checked = true;
  } else if (response[qNum] == "B"){
    optB.Checked = true;
  } else if (response[qNum] == "C"){
    optC.Checked = true;
  } else if (response[qNum] == "D"){
    optD.Checked = true;
  } else {
    //MessageBox.Show("There's a problem!");
  } // end if

} // end showQuestion

The first part of the method assigns doc.ChildNodes[1] to a variable named theTest and the current problem (theTest.ChildNodes[qNum]) to a node named theProblem.

NOTE

IN THE REAL WORLD

You might wonder how I knew that the test element would be doc.ChildNodes[1] and where the problem would be stored. In the quiz program, I’m using a custom form of XML I designed, so I know exactly where everything should be. My program will create the XML, so it should be in exactly the right format. Even when you know the document structure, figuring out exactly how it looks to the .NET parser can be challenging. When you create your own XML scheme, you might want to examine it in the XML Viewer program presented earlier in this chapter so that you can be sure that you know how the internal document structure is organized.

When I have a reference to the current problem in theProblem, it’s easy to copy the inner text of theProblem’s nodes to the appropriate labels and option buttons. I also put the current question number in lblNum. The question number is handy for the user, but I really put lblNum in as a debugging tool to ensure that the Next and Prev buttons were working correctly. Examining the question number is much easier than trying to remember which question is the first or last question.

Determining which radio button (if any) should be checked requires thought because, in the quiz form, this is determined by the user’s response, which is not stored in the XML document at all, but in the response array. I started by setting the Checked property of each check box to false. Then I examined the response element corresponding to the current question, turning on the Checked property of the corresponding radio button.

Grading the Test

The quiz isn’t very interesting without feedback. The gradeTest() method compares the response array to the correct element in each problem of the test XML:

private void gradeTest(){
  int score = 0;
  for (int i = 0; i < numQuestions; i++){
    XmlNode theProblem = theTest.ChildNodes[i];
    string correct = theProblem["correct"].InnerText;
    if (response[i] == correct){
      score ++;
    } // end if 
  } // end for loop
  MessageBox.Show("Score: " + score + " of " + numQuestions);
} // end gradeTest

The score variable holds the current score. For each question in the quiz, I extract the inner text of the correct node and compare this against the corresponding value of response. If the two values are equal, the user got the right answer, and the score should be incremented. At the end of the test, I display the score.

NOTE

IN THE REAL WORLD

The gradeTest() method would be an ideal place to extend the program’s capabilities. For example, you might want to create another XML document to track all the users who have taken the quiz and store their results. You might also want to do more detailed analysis of a user’s score, such as which questions the user missed and which questions the user simply didn’t answer. You might also want to screen for unanswered questions and allow the user to go back without grading the quiz if there are unanswered questions.

Opening a Quiz

The File menu includes a command for opening a new quiz. This is done just like opening any other XML document:

private void mnuOpen_Click(object sender,
        System.EventArgs e) {
  if (opener.ShowDialog() != DialogResult.Cancel){
    doc.Load(opener.FileName);
    resetQuiz();
  } // end if
} // end mnuOpen

I displayed a File Open dialog and used the resulting file name to open the document using the doc.Load() method.

After a document is loaded into memory, it is necessary to reset the quiz, which I did with the resetQuiz() method.

Responding to Other Menu Requests

The other two menu events require quite simple code:

private void mnuGradeQuiz_Click(object sender,
        System.EventArgs e) {
  gradeTest();
} // end gradeTest

private void mnuExit_Click(object sender,
    System.EventArgs e) {
  this.Close();
} // end mnuExit

The Grade Quiz menu calls the gradeTest() method, and the Exit menu closes the current form.

Writing the Editor Form

The editor form was designed to be parallel to the quiz form in its general structure. The editor’s main purpose is to allow the user to generate new quizzes, rather than to display existing quizzes. For this reason, the editor uses many features described in the XML Creator program to create new documents and nodes and populate these nodes with values from the form.

Designing the Visual Interface

Figure 10.20 shows the editor’s visual interface. I tried to keep the visual interface as similar to the quiz form as possible, but I used text boxes for user input. The editor has four radio buttons (named optAoptD), but I sized the radio buttons so that their text attributes would not be visible. I carefully placed the text boxes where the radio buttons’ text would normally go. This gives the effect of an editable radio button. The buttons and label at the bottom of the form are just like those in the quiz form. The program has two menus containing elements to load and store the quiz, create a new quiz, add a new question, and close the editor.

Figure 10.20. The editor form relies on text boxes to display and retrieve the problems.


Creating the Instance Variables

The instance variables for the editor are typical for the programs in this chapter:

private XmlDocument doc;
private XmlNode theTest;
private int qNum = 0;
private int numQuestions = 0;

The doc variable will hold the entire quiz document, and theTest will hold a reference to the test. qNum is the current question number, and numQuestions holds the total number of questions in the quiz.

Initializing in the Load Event

The form’s load event loads a sample test to ensure that an XML document is always in memory. As in the quiz program, this eliminates the need for certain kinds of error checking, and the user is free to modify the default quiz, load another quiz, or create a new one.

private void frmEdit_Load(object sender,
        System.EventArgs e) {
  //load up a sample test.
  doc = new XmlDocument();
  doc.Load("sampleTest.qml");
  resetQuiz();

} // end frmEdit_Load

The frmEdit_Load() method simply loads up a default document and calls the resetQuiz() method (described in the next section) to start the quiz editing process.

Because I’m using a specific style of XML markup, I decided to give it its own extension (qml for quiz markup language). You commonly do this when you’re working with a specific document structure. You use the more generic xml extension when the exact structure of the document isn’t as important (as in the XML Viewer program, which was designed to handle any XML document).

Resetting the Quiz

Resetting the quiz works exactly the same way in the editor as in the quiz program:

private void resetQuiz(){
  theTest = doc.ChildNodes[1];
  numQuestions = theTest.ChildNodes.Count;
  qNum = 0;
  showQuestion(0);
} // end resetQuiz

The test is retrieved from doc.ChildNodes[1], and numQuestions extracts the number of questions from the test object.

I reset qNum to 0 and showed the initial question using the showQuestion() method.

Showing a Question

Showing a question in the editor is much like showing it in the quiz program, except that the radio button values are extracted from the XML document in the editor, rather than in the response array in the quiz program:

private void showQuestion(int qNum){
  XmlNode theProblem = theTest.ChildNodes[qNum];
  txtQuestion.Text = theProblem["question"].InnerText;
  txtA.Text = theProblem["answerA"].InnerText;
  txtB.Text = theProblem["answerB"].InnerText;
  txtC.Text = theProblem["answerC"].InnerText;
  txtD.Text = theProblem["answerD"].InnerText;
  lblNum.Text = Convert.ToString(qNum);

  //uncheck all the option buttons
  optA.Checked = false;
  optB.Checked = false; 
 optC.Checked = false;
 optD.Checked = false;

 //Check the appropriate option button
 switch (theProblem["correct"].InnerText){
   case "A":
     optA.Checked = true;
     break;
   case "B":
     optB.Checked = true;
     break;
    case "C":
      optC.Checked = true;
      break;
    case "D":
      optD.Checked = true;
      break;
    default:
      // do nothing
      break;
  } // end switch
} // end showQuestion

The radio buttons are set by extracting the correct element from the current problem and setting the Checked property of the corresponding radio button.

Updating a Question

Whenever the user moves to a new question, the program stores the current question’s data to the internal XML structure by copying the values of the appropriate text boxes to the current problem node:

private void updateQuestion(int qNum){
   // updates the current question's XML
   XmlNode theProblem = theTest.ChildNodes[qNum];
   theProblem["question"].InnerText = txtQuestion.Text;
   theProblem["answerA"].InnerText = txtA.Text; 
   theProblem["answerB"].InnerText = txtB.Text; 
   theProblem["answerC"].InnerText = txtC.Text; 
   theProblem["answerD"].InnerText = txtD.Text; 
  //store the correct answer based on the option buttons
  if (optA.Checked){
    theProblem["correct"].InnerText = "A";
  } else if (optB.Checked){
    theProblem["correct"].InnerText = "B";
  } else if (optC.Checked){
    theProblem["correct"].InnerText = "C";
  } else if (optD.Checked){
    theProblem["correct"].InnerText = "D";
  } else {
    theProblem["correct"].InnerText = "X";
  } // end if
} // end updateQuestion

The correct value cannot be directly determined from a text box entry, so it is generated by evaluating which radio button has been checked.

It might seem that the correct and response elements are a pain to work with compared to the other elements. True, the radio buttons require more attention than the text elements. This effort is worth it in the long run, however. Most of the elements in a problem are simply text and don’t require any error checking. If you let the user type in an answer, it would be easier to copy the values to and from the resulting text box, but you would have to do all kinds of validation. You would have to ensure that the user typed a legal response, used the correct case, and didn’t try to type the entire answer instead of the letter corresponding to the answer. The overhead associated with using radio buttons for input is offset by the knowledge that the user input will always fall within a predictable range.

Moving to the Preceding Question

Moving to the preceding question works almost exactly the same in the editor and the quiz program. The only new wrinkle is that the editor does not allow the user to move on without clicking one of the option buttons. This ensures that every question will have a response. Otherwise, the quiz could have questions that would be impossible to answer. The noResponse() method (described in the next section) returns the boolean value true if there are no responses and false if at least one of the check boxes has been selected. If no responses are selected, the code reminds the user that something must be selected. If a radio button has been selected, the code proceeds to update the current question, decrement the question number, check to ensure that the question number isn’t less than 0, and display the new question.

private void btnPrev_Click(object sender,
        System.EventArgs e) {
  if (noResponse()){
    MessageBox.Show("You must select one of the answers");
  } else {
    updateQuestion(qNum);
    qNum--;
    if (qNum < 0){
      qNum = 0;
      MessageBox.Show("First question");
    } else {
      showQuestion(qNum);
    } // end 'first question' if
  } // end answerEmpty if
} // end btnPrev

Moving to the Next Question

The next question code is similar to the preceding question code. However, when the user reaches the last question in the editor, the code prompts to see whether the user wants to add a new question. In an editor, it’s possible that the user will want to add a new question at the end of the quiz.

private void btnNext_Click(object sender,
          System.EventArgs e) {

  if (answerEmpty()){
    MessageBox.Show("You must select one of the answers");
  } else {
    updateQuestion(qNum);
    qNum++;
    if (qNum >= numQuestions){
      qNum = numQuestions -1;
      if (MessageBox.Show("Last question. Add new question?",
          "last question",
          MessageBoxButtons.YesNo, 
          MessageBoxIcon.Question) == DialogResult.Yes){ 
        mnuAddQuestion_Click(sender, e);
      } // end 'add question' if
    } else {
      showQuestion(qNum);
    } // end 'last question' if
  } // end 'answer empty' if

}  // end btnNext

Checking for a No Response

The btnNext and btnPrev events need to know whether the option buttons are empty (that is, none of the responses have been checked). This is done by setting a boolean variable named responseEmpty to true. Then I checked each option button to see whether it was checked. If so, responseEmpty is set to false. I then returned the value of responseEmpty. If any radio button has been selected, the noResponse() method returns a value of false. If none of the radio buttons have been selected, noResponse() returns the value true.

private bool noResponse(){
  //checks to see if all the check boxes are empty
  bool responseEmpty = true;
  if (optA.Checked){
    responseEmpty = false;
  } // end if
  if (optB.Checked){
    responseEmpty = false;
  } // end if
  if (optC.Checked){
    responseEmpty = false;
  } // end if
  if (optD.Checked){
    responseEmpty = false;
  } // end if
  return responseEmpty;
}// end noResponse

Saving a File

Saving the file is a simple affair:

private void mnuSaveAs_Click(object sender,
        System.EventArgs e) {
  if (saver.ShowDialog() != DialogResult.Cancel){
    doc.Save(saver.FileName);
  } // end if
} // end mnuSave

I show a File Save dialog box and use it to get the user’s requested file name. I then call the doc object’s Save() method to save the current XmlDocument to the file system.

Opening a File

Opening a file also uses a familiar method of XmlDocument. I used another File dialog to let the user choose a file to open. Next, I used the Load() method of doc to load the file into memory. I then called the resetQuiz() method to prepare the quiz for editing.

private void menuOpen_Click(object sender,
        System.EventArgs e) {
  if (opener.ShowDialog() != DialogResult.Cancel){
    doc.Load(opener.FileName);
    theTest = doc.ChildNodes[1];
    resetQuiz();
  } // end if
} // end mnuOpen

Adding a Question

To add a question to the end of the quiz, I used the algorithm described in the XML Creator program described earlier in this chapter:

 
private void mnuAddQuestion_Click(object sender, 
        System.EventArgs e) { 
  numQuestions++; 
  qNum = numQuestions -1; 

  //create the new Node 
  XmlNode newProblem = theTest.ChildNodes[0].Clone(); 
  theTest.AppendChild(newProblem); 

  showQuestion(qNum); 
  //clear the screen
  txtQuestion.Text = "";
  txtA.Text = "";
  txtB.Text = "";
  txtC.Text = "";
  txtD.Text = "";
  optA.Checked = false;
  optB.Checked = false;
  optC.Checked = false;
  optD.Checked = false;

} // end mnuAdd

The mnuAddQuestion_Click() method begins by making a clone of the first problem and then appending the clone to the end of the test. I incremented numQuestions to indicate that the total number of questions has changed, and I set qNum to indicate the last question, which is the new node that has just been created.

I didn’t bother to change the values of the new node (they will still be exactly the same as the values of the first problem node) because it isn’t necessary to do so. I will clear the screen, and when the user moves off this question, the values on the screen will be copied over to the new node with the updateQuestion() method.

Creating a New Test

Creating a new test uses another algorithm developed in the XML Creator program from earlier in the chapter. I modified the code to reflect the structure of the quiz markup language I had devised:

private void mnuNewTest_Click(object sender,
        System.EventArgs e) {
   doc = new XmlDocument();
   theTest = doc.CreateNode(XmlNodeType.Element, "test", null);

   //create the first line:
   //<?xml version="1.0" encoding="utf-8"?>

   XmlNode header = doc.CreateXmlDeclaration("1.0", "utf-8", null);

  XmlNode theProblem = doc.CreateElement("problem");
  XmlNode theQuestion = doc.CreateElement("question"); 
  XmlNode theAnswerA = doc.CreateElement("answerA");
  XmlNode theAnswerB = doc.CreateElement("answerB");
  XmlNode theAnswerC = doc.CreateElement("answerC");
  XmlNode theAnswerD = doc.CreateElement("answerD");
  XmlNode theCorrect = doc.CreateElement("correct");

  //construct the new node structure
  doc.AppendChild(header);
  doc.AppendChild(theTest);
  theTest.AppendChild(theProblem);
  theProblem.AppendChild(theQuestion);
  theProblem.AppendChild(theAnswerA);
  theProblem.AppendChild(theAnswerB);
  theProblem.AppendChild(theAnswerC);
  theProblem.AppendChild(theAnswerD);
  theProblem.AppendChild(theCorrect);

  //populate values of nodes
  theQuestion.InnerText = "question";
  theAnswerA.InnerText = "a";
  theAnswerB.InnerText = "b";
  theAnswerC.InnerText = "c";
  theAnswerD.InnerText = "d";
  theCorrect.InnerText = "X";

  qNum = 0;
  showQuestion(0);

} // end mnuNewTest

First, I created a new XmlDocument and XmlNode to hold the document and the test, respectively. I then created the XML header with a call to the XmlDocument’s CreateXmlDeclaration() method.

I then created a series of XML elements to hold the problem and its components. Next, I used the AppendChild() method of the various nodes to build the test and the first problem. Finally, I added some default text to each of the nodes. I then reset qNum to 0 and showed the initial question.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.58.44.229