Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Microsoft CSharp Programming For The Absolute Beginner (2002) [eng]-1.pdf
Скачиваний:
46
Добавлен:
16.08.2013
Размер:
15.71 Mб
Скачать

Figure 10.17: The native XML code is complete but very difficult for humans to read.

Fortunately, the XmlDocument class has a property named PreserveWhiteSpace. When this property is set to true, the document is formatted for human reading. When the property is set to false, all whitespace (carriage returns and space characters) are removed. To get the effects of the PreserveWhiteSpace property, you need to reload the document.

The btnDisplay click event takes advantage of the PreserveWhiteSpace property to display the code in a human−readable format and then convert it back to the compressed form preferred by .NET:

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

//save the current document doc.Save(fileName);

//display with whitespace doc.PreserveWhitespace = true; doc.Load(fileName); txtOutput.Text = doc.OuterXml;

//reload without whitespace doc.PreserveWhitespace = false; doc.Load(fileName);

} // end btnDisplay

I started by saving the XML file as it currently exists to whatever file is determined by the fileName variable (set at the beginning of the program). I then set PreserveWhitespace to true, reloaded the document, and displayed the formatted version in the text box. The formatted version seemed to cause problems for some of the XML code, so I turned off PreserveWhitespace and reloaded the document again so that the version of doc in memory has no whitespace. There are other ways to automate the formatting of an XML document, but this appears to be the simplest.

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

302

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();

303

} // 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).

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.

304

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

305

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;

306

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];

307

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.

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.

308

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.

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.

309

Соседние файлы в предмете Программирование на C++