- •Microsoft C# Programming for the Absolute Beginner
- •Table of Contents
- •Microsoft C# Programming for the Absolute Beginner
- •Introduction
- •Overview
- •Chapter 1: Basic Input and Output: A Mini Adventure
- •Project: The Mini Adventure
- •Reviewing Basic C# Concepts
- •Namespaces
- •Classes
- •Methods
- •Statements
- •The Console Object
- •.NET Documentation
- •Getting into the Visual Studio .Net Environment
- •Examining the Default Code
- •Creating a Custom Namespace
- •Adding Summary Comments
- •Creating the Class
- •Moving from Code to a Program
- •Compiling Your Program
- •Looking for Bugs
- •Getting Input from the User
- •Creating a String Variable
- •Getting a Value with the Console.ReadLine() Method
- •Incorporating a Variable in Output
- •Combining String Values
- •Combining Strings with Concatenation
- •Adding a Tab Character
- •Using the Newline Sequence
- •Displaying a Backslash
- •Displaying Quotation Marks
- •Launching the Mini Adventure
- •Planning the Story
- •Creating the Variables
- •Getting Values from the User
- •Writing the Output
- •Finishing the Program
- •Summary
- •Chapter 2: Branching and Operators: The Math Game
- •The Math Game
- •Using Numeric Variables
- •The Simple Math Game
- •Numeric Variable Types
- •Integer Variables
- •Long Integers
- •Data Type Problems
- •Math Operators
- •Converting Variables
- •Explicit Casting
- •The Convert Object
- •Creating a Branch in Program Logic
- •The Hi Bill Game
- •Condition Testing
- •The If Statement
- •The Else Clause
- •Multiple Conditions
- •Working with The Switch Statement
- •The Switch Demo Program
- •Examining How Switch Statements Work
- •Creating a Random Number
- •Introducing the Die Roller
- •Exploring the Random Object
- •Creating a Random Double with the .NextDouble() Method
- •Getting the Values of Dice
- •Creating the Math Game
- •Designing the Game
- •Creating the Variables
- •Managing Addition
- •Managing Subtraction
- •Managing Multiplication and Division
- •Checking the Answers
- •Waiting for the Carriage Return
- •Summary
- •Chapter 3: Loops and Strings: The Pig Latin Program
- •Project: The Pig Latin Program
- •Investigating The String Object
- •The String Mangler Program
- •A Closer Look at Strings
- •Using the Object Browser
- •Experimenting with String Methods
- •Performing Common String Manipulations
- •Using a For Loop
- •Examining The Bean Counter Program
- •Creating a Sentry Variable
- •Checking for an Upper Limit
- •Incrementing the Variable
- •Examining the Behavior of the For Loop
- •The Fancy Beans Program
- •Skipping Numbers
- •Counting Backwards
- •Using a Foreach Loop to Break Up a Sentence
- •Using a While Loop
- •The Magic Word Program
- •Writing an Effective While Loop
- •Planning Your Program with the STAIR Process
- •S: State the Problem
- •T: Tool Identification
- •A: Algorithm
- •I: Implementation
- •R: Refinement
- •Applying STAIR to the Pig Latin Program
- •Stating the Problem
- •Identifying the Tools
- •Creating the Algorithm
- •Implementing and Refining
- •Writing the Pig Latin Program
- •Setting Up the Variables
- •Creating the Outside Loop
- •Dividing the Phrase into Words
- •Extracting the First Character
- •Checking for a Vowel
- •Adding Debugging Code
- •Closing Up the code
- •Summary
- •Introducing the Critter Program
- •Creating Methods to Reuse Code
- •The Song Program
- •Building the Main() Method
- •Creating a Simple Method
- •Adding a Parameter
- •Returning a Value
- •Creating a Menu
- •Creating a Main Loop
- •Creating the Sentry Variable
- •Calling a Method
- •Working with the Results
- •Writing the showMenu() Method
- •Getting Input from the User
- •Handling Exceptions
- •Returning a Value
- •Creating a New Object with the CritterName Program
- •Creating the Basic Critter
- •Using Scope Modifiers
- •Using a Public Instance Variable
- •Creating an Instance of the Critter
- •Adding a Method
- •Creating the talk() Method for the CritterTalk Program
- •Changing the Menu to Use the talk() Method
- •Creating a Property in the CritterProp Program
- •Examining the Critter Prop Program
- •Creating the Critter with a Name Property
- •Using Properties as Filters
- •Making the Critter More Lifelike
- •Adding More Private Variables
- •Adding the Age() Method
- •Adding the Eat() Method
- •Adding the Play() Method
- •Modifying the Talk() Method
- •Making Changes in the Main Class
- •Summary
- •Introducing the Snowball Fight
- •Inheritance and Encapsulation
- •Creating a Constructor
- •Adding a Constructor to the Critter Class
- •Creating the CritViewer Class
- •Reviewing the Static Keyword
- •Calling a Constructor from the Main() Method
- •Working with Multiple Files
- •Overloading Constructors
- •Viewing the Improved Critter Class
- •Adding Polymorphism to Your Objects
- •Modifying the Critter Viewer in CritOver to Demonstrate Overloaded Constructors
- •Using Inheritance to Make New Classes
- •Creating a Class to View the Clone
- •Creating the Critter Class
- •Improving an Existing Class
- •Introducing the Glitter Critter
- •Adding Methods to a New Class
- •Changing the Critter Viewer Again
- •Creating the Snowball Fight
- •Building the Fighter
- •Building the Robot Fighter
- •Creating the Main Menu Class
- •Summary
- •Overview
- •Introducing the Visual Critter
- •Thinking Like a GUI Programmer
- •Creating a Graphical User Interface (GUI)
- •Examining the Code of a Windows Program
- •Adding New Namespaces
- •Creating the Form Object
- •Creating a Destructor
- •Creating the Components
- •Setting Component Properties
- •Setting Up the Form
- •Writing the Main() Method
- •Creating an Interactive Program
- •Responding to a Simple Event
- •Creating and Adding the Components
- •Adding an Event to the Program
- •Creating an Event Handler
- •Allowing for Multiple Selections
- •Choosing a Font with Selection Controls
- •Creating the User Interface
- •Examining Selection Tools
- •Creating Instance Variables in the Font Chooser
- •Writing the AssignFont() Method
- •Writing the Event Handlers
- •Working with Images and Scroll Bars
- •Setting Up the Picture Box
- •Adding a Scroll Bar
- •Revisiting the Visual Critter
- •Designing the Program
- •Determining the Necessary Tools
- •Designing the Form
- •Writing the Code
- •Summary
- •Chapter 7: Timers and Animation: The Lunar Lander
- •Introducing the Lunar Lander
- •Reading Values from the Keyboard
- •Introducing the Key Reader Program
- •Setting Up the Key Reader Program
- •Coding the KeyPress Event
- •Coding the KeyDown Event
- •Determining Which Key Was Pressed
- •Animating Images
- •Introducing the ImageList Control
- •Setting Up an Image List
- •Looking at the Image Collection
- •Displaying an Image from the Image List
- •Using a Timer to Automate Animation
- •Introducing the Timer Control
- •Configuring the Timer
- •Adding Motion
- •Checking for Keyboard Input
- •Working with the Location Property
- •Detecting Collisions between Objects
- •Coding the Crasher Program
- •Getting Values for newX and newY
- •Bouncing the Ball off the Sides
- •Checking for Collisions
- •Extracting a Rectangle from a Component
- •Getting More from the MessageBox Object
- •Introducing the MsgDemo Program
- •Retrieving Values from the MessageBox
- •Coding the Lunar Lander
- •The Visual Design
- •The Constructor
- •The timer1_Tick() Method
- •The moveShip() Method
- •The checkLanding() Method
- •The theForm_KeyDown() Method
- •The showStats() Method
- •The killShip() Method
- •The initGame() Method
- •Summary
- •Chapter 8: Arrays: The Soccer Game
- •The Soccer Game
- •Introducing Arrays
- •Exploring the Counter Program
- •Creating an Array of Strings
- •Referring to Elements in an Array
- •Working with Arrays
- •Using the Array Demo Program to Explore Arrays
- •Building the Languages Array
- •Sorting the Array
- •Designing the Soccer Game
- •Solving a Subset of the Problem
- •Adding Percentages for the Other Players
- •Setting Up the Shot Demo Program
- •Setting Up the List Boxes
- •Using a Custom Event Handler
- •Writing the changeStatus() Method
- •Kicking the Ball
- •Designing Programs by Hand
- •Examining the Form by Hand Program
- •Adding Components in the Constructor
- •Responding to the Button Event
- •Building the Soccer Program
- •Setting Up the Variables
- •Examining the Constructor
- •Setting Up the Players
- •Setting Up the Opponents
- •Setting Up the Goalies
- •Responding to Player Clicks
- •Handling Good Shots
- •Handling Bad Shots
- •Setting a New Current Player
- •Handling the Passage of Time
- •Updating the Score
- •Summary
- •Chapter 9: File Handling: The Adventure Kit
- •Introducing the Adventure Kit
- •Viewing the Main Screen
- •Loading an Adventure
- •Playing an Adventure
- •Creating an Adventure
- •Reading and Writing Text Files
- •Exploring the File IO Program
- •Importing the IO Namespace
- •Writing to a Stream
- •Reading from a Stream
- •Creating Menus
- •Exploring the Menu Demo Program
- •Adding a MainMenu Object
- •Adding a Submenu
- •Setting Up the Properties of Menu Items
- •Writing Event Code for Menus
- •Using Dialog Boxes to Enhance Your Programs
- •Exploring the Dialog Demo Program
- •Adding Standard Dialogs to Your Form
- •Using the File Dialog Controls
- •Responding to File Dialog Events
- •Using the Font Dialog Control
- •Using the Color Dialog Control
- •Storing Entire Objects with Serialization
- •Exploring the Serialization Demo Program
- •Creating the Contact Class
- •Referencing the Serializable Namespace
- •Storing a Class
- •Retrieving a Class
- •Returning to the Adventure Kit Program
- •Examining the Room Class
- •Creating the Dungeon Class
- •Writing the Game Class
- •Writing the Editor Class
- •Writing the MainForm Class
- •Summary
- •Chapter 10: Chapter Basic XML: The Quiz Maker
- •Introducing the Quiz Maker Game
- •Taking a Quiz
- •Creating and Editing Quizzes
- •Investigating XML
- •Defining XML
- •Creating an XML Document in .NET
- •Creating an XML Schema for Your Language
- •Investigating the .NET View of XML
- •Exploring the XmlNode Class
- •Exploring the XmlDocument Class
- •Reading an Existing XML Document
- •Creating the XML Viewer Program
- •Writing New Values to an XML Document
- •Building the Document Structure
- •Adding an Element to the Document
- •Displaying the XML Code
- •Examining the Quizzer Program
- •Building the Main Form
- •Writing the Quiz Form
- •Writing the Editor Form
- •Summary
- •Overview
- •Introducing the SpyMaster Program
- •Creating a Simple Database
- •Accessing the Data Server
- •Accessing the Data in a Program
- •Using Queries to Modify Data Results
- •Limiting Data with the SELECT Statement
- •Using an Existing Database
- •Adding the Capability to Display Queries
- •Creating a Visual Query Builder
- •Working with Relational Databases
- •Improving Your Data with Normalization
- •Using a Join to Connect Two Tables
- •Creating a View
- •Referring to a View in a Program
- •Incorporating the Agent Specialty Attribute
- •Working with Other Databases
- •Creating a New Connection
- •Converting a Data Set to XML
- •Reading from XML to a Data Source
- •Creating the SpyMaster Database
- •Building the Main Form
- •Editing the Assignments
- •Editing the Specialties
- •Viewing the Agents
- •Editing the Agent Data
- •Summary
- •List of Figures
- •List of Tables
- •List of Sidebars
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 optA—optD), 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.
310
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.
Trick 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.
311
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
312
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.
Trick 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
313
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
314
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
315
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.
316