Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 21 – ASP .NET and Web Services

Similar presentations


Presentation on theme: "Chapter 21 – ASP .NET and Web Services"— Presentation transcript:

1 Chapter 21 – ASP .NET and Web Services
Outline Introduction Web Services Simple Object Access Protocol (SOAP) and Web Services Publishing and Consuming Web Services Session Tracking in Web Services Using Web Forms and Web Services Case Study: Temperature Information Application User-Defined Types in Web Services

2 21.2 Web Services Link to service description
Links to web service methods Fig ASMX file rendered in Internet Explorer.

3 21.2 Web Services Fig Service description for a Web service.

4 21.2 Web Services Fig Invoking a method of a Web service from a Web browser.

5 21.2 Web Services Fig Results of invoking a Web-service method from a Web browser.

6 21.3 Simple Object Access Protocol (SOAP) and Web Services
Represent arguments named first and second. The value string indicates that they need to be of type string, but in a method call they would be replaced with the argument values. Name of method Fig SOAP request for the HugeInteger Web service.

7 Class HugeInteger inherits from System.Web.Services.WebService
1 // Fig. 21.6: HugeInteger.asmx.cs 2 // HugeInteger Web Service. 3 4 using System; 5 using System.Text; 6 using System.Collections; 7 using System.ComponentModel; 8 using System.Data; 9 using System.Diagnostics; 10 using System.Web; 11 using System.Web.Services; // contains Web service related classes 12 13 namespace HugeIntegerWebService 14 { /// <summary> /// performs operations on large integers /// </summary> [ WebService( Namespace = "http://www.deitel.com/csphtp1/ch21/", Description = "A Web service which provides methods that" + " can manipulate large integer values." ) ] public class HugeInteger : System.Web.Services.WebService { // default constructor public HugeInteger() { // CODEGEN: This call is required by the ASP .NET Web // Services Designer InitializeComponent(); 30 number = new int[ MAXIMUM ]; } 33 HugeInteger.asmx.cs Set Namespace property of WebService attribute to specify the namespace that the Web service belongs to Set Description property of WebService attribute to describe the function of the Web Service Class HugeInteger inherits from System.Web.Services.WebService

8 HugeInteger.asmx.cs 34 #region Component Designer generated code
/// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { } #endregion 43 /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { } 50 // WEB SERVICE EXAMPLE // The HelloWorld() example service returns // the string Hello World // To build, uncomment the following lines // then save and build the project // To test this web service, press F5 57 // [WebMethod] // public string HelloWorld() // { // return "Hello World"; // } 63 private const int MAXIMUM = 100; 65 public int[] number; 67 HugeInteger.asmx.cs

9 Indexer for class HugeInteger HugeInteger.asmx.cs
// indexer that accepts an integer parameter public int this[ int index ] { get { return number[ index ]; } 75 set { number[ index ] = value; } 80 } // end indexer 82 // returns string representation of HugeInteger public override string ToString() { StringBuilder returnString = new StringBuilder(); 87 foreach ( int digit in number ) returnString.Insert( 0, digit ); 90 return returnString.ToString(); } 93 // creates HugeInteger based on argument public static HugeInteger FromString( string integer ) { HugeInteger parsedInteger = new HugeInteger(); 98 for ( int i = 0; i < integer.Length; i++ ) parsedInteger[ i ] = Int32.Parse( integer[ integer.Length - i - 1 ].ToString() ); Indexer for class HugeInteger HugeInteger.asmx.cs

10 Method Add that adds two HugeIntegers
102 return parsedInteger; } 105 // WebMethod that performs integer addition // represented by string arguments [ WebMethod ( Description = "Adds two huge integers." ) ] public string Add( string first, string second ) { int carry = 0; 112 HugeInteger operand1 = HugeInteger.FromString( first ); HugeInteger operand2 = HugeInteger.FromString( second ); 116 // store result of addition HugeInteger result = new HugeInteger(); 119 // perform addition algorithm for each digit for ( int i = 0; i < MAXIMUM; i++ ) { // add two digits in same column // result is their sum, plus carry from // previous operation modulus 10 result[ i ] = ( operand1[ i ] + operand2[ i ] ) % 10 + carry; 128 // store remainder of dividing // sums of two digits by 10 carry = ( operand1[ i ] + operand2[ i ] ) / 10; } 133 return result.ToString(); 135 } // end method Add HugeInteger.asmx.cs WebMethod attribute specifies that this method may be called by remote client applications Description property of WebMethod attribute summarizes the function of the method Method Add that adds two HugeIntegers

11 Method Subtract that subtracts one HugeInteger from another
137 // WebMethod that performs the subtraction of integers // represented by string arguments [ WebMethod ( Description = "Subtracts two huge integers." ) ] public string Subtract( string first, string second ) { HugeInteger operand1 = HugeInteger.FromString( first ); HugeInteger operand2 = HugeInteger.FromString( second ); HugeInteger result = new HugeInteger(); 148 // subtract top digit from bottom digit for ( int i = 0; i < MAXIMUM; i++ ) { // if top digit is smaller than bottom // digit we need to borrow if ( operand1[ i ] < operand2[ i ] ) Borrow( operand1, i ); 156 // subtract bottom from top result[ i ] = operand1[ i ] - operand2[ i ]; } 160 return result.ToString(); 162 } // end method Subtract 164 // borrows 1 from next digit private void Borrow( HugeInteger integer, int place ) { // if no place to borrow from, signal problem if ( place >= MAXIMUM - 1 ) throw new ArgumentException(); 171 HugeInteger.asmx.cs Method Subtract that subtracts one HugeInteger from another Helper method Borrow used by method Subtract when 1 needs to be borrowed from the next number

12 172 // otherwise if next digit is zero,
// borrow from digit to left else if ( integer[ place + 1 ] == 0 ) Borrow( integer, place + 1 ); 176 // add ten to current place because we borrowed // and subtract one from previous digit - // this is digit borrowed from integer[ place ] += 10; integer[ place + 1 ] -= 1; 182 } // end method Borrow 184 // WebMethod that returns true if first integer is // bigger than second [ WebMethod ( Description = "Determines whether first " + "integer is larger than the second integer." ) ] public bool Bigger( string first, string second ) { char[] zeroes = { '0' }; 192 try { // if elimination of all zeroes from result // of subtraction is an empty string, // numbers are equal, so return false, // otherwise return true if ( Subtract( first, second ).Trim( zeroes ) == "" ) return false; else return true; } 204 HugeInteger.asmx.cs Returns true if the first integer is bigger then the second and false otherwise

13 Returns true if the two integers are equal and false otherwise
// if ArgumentException occurs, first number // was smaller, so return false catch ( ArgumentException ) { return false; } 211 } // end method Bigger 213 // WebMethod returns true if first integer is // smaller than second [ WebMethod ( Description = "Determines whether the " + "first integer is smaller than the second integer." ) ] public bool Smaller( string first, string second ) { // if second is bigger than first, then first is // smaller than second return Bigger( second, first ); } 224 // WebMethod that returns true if two integers are equal [ WebMethod ( Description = "Determines whether the " + "first integer is equal to the second integer." ) ] public bool EqualTo( string first, string second ) { // if either first is bigger than second, or first is // smaller than second, they are not equal if ( Bigger( first, second ) || Smaller( first, second ) ) return false; Returns true if the first integer is smaller then the second and false otherwise HugeInteger.asmx.cs Returns true if the two integers are equal and false otherwise

14 HugeInteger.asmx.cs Program Output
else return true; } 238 } // end class HugeInteger 240 241 } // end namespace HugeIntegerWebService HugeInteger.asmx.cs Program Output

15 21.4 Publishing and Consuming Web Services
Fig Design view of a Web service.

16 21.4 Publishing and Consuming Web Services
Fig Adding a Web service reference to a project.

17 21.4 Publishing and Consuming Web Services
Link to root directory of web server Fig Add Web Reference dialog.

18 21.4 Publishing and Consuming Web Services
Fig Web services located on localhost.

19 21.4 Publishing and Consuming Web Services
Fig Web reference selection and description.

20 21.4 Publishing and Consuming Web Services
Service description Web service discovery file Proxy class Fig Solution Explorer after adding a Web reference to a project.

21 UsingHugeIntegerService.cs 1 // Fig. 21.13: UsingHugeIntegerService.cs
2 // Using the HugeInteger Web Service. 3 4 using System; 5 using System.Drawing; 6 using System.Collections; 7 using System.ComponentModel; 8 using System.Windows.Forms; 9 using System.Web.Services.Protocols; 10 11 // allows user to perform operations on large integers 12 public class UsingHugeIntService : System.Windows.Forms.Form 13 { private System.Windows.Forms.Label promptLabel; private System.Windows.Forms.Label resultLabel; 16 private System.Windows.Forms.TextBox firstTextBox; private System.Windows.Forms.TextBox secondTextBox; 19 private System.Windows.Forms.Button addButton; private System.Windows.Forms.Button subtractButton; private System.Windows.Forms.Button biggerButton; private System.Windows.Forms.Button smallerButton; private System.Windows.Forms.Button equalButton; 25 private System.ComponentModel.Container components = null; 27 // declare a reference Web service private localhost.HugeInteger remoteInteger; 30 private char[] zeroes = { '0' }; 32 UsingHugeIntegerService.cs

22 Instantiate remoteInteger to be a new HugeInteger object
// default constructor public UsingHugeIntService() { InitializeComponent(); 37 // instantiate remoteInteger remoteInteger = new localhost.HugeInteger(); } 41 // Visual Studio .NET generated code 43 [STAThread] static void Main() { Application.Run( new UsingHugeIntService() ); 48 } // end Main 50 // checks whether two numbers user input are equal protected void equalButton_Click( object sender, System.EventArgs e ) { // make sure HugeIntegers do not exceed 100 digits if ( CheckSize( firstTextBox, secondTextBox ) ) return; 58 // call Web-service method to determine // whether integers are equal if ( remoteInteger.EqualTo( firstTextBox.Text, secondTextBox.Text ) ) 63 resultLabel.Text = firstTextBox.Text.TrimStart( zeroes ) + " is equal to " + secondTextBox.Text.TrimStart( zeroes ); Instantiate remoteInteger to be a new HugeInteger object UsingHugeIntegerService.cs Call HugeInteger Web method EqualTo remotely

23 Call HugeInteger Web method Smaller remotely
else resultLabel.Text = firstTextBox.Text.TrimStart( zeroes ) + " is NOT equal to " + secondTextBox.Text.TrimStart( zeroes ); 73 } // end method equalButton_Click 75 // checks whether first integer input // by user is smaller than second protected void smallerButton_Click( object sender, System.EventArgs e ) { // make sure HugeIntegers do not exceed 100 digits if ( CheckSize( firstTextBox, secondTextBox ) ) return; 84 // call Web-service method to determine whether first // integer is smaller than second if ( remoteInteger.Smaller( firstTextBox.Text, secondTextBox.Text ) ) 89 resultLabel.Text = firstTextBox.Text.TrimStart( zeroes ) + " is smaller than " + secondTextBox.Text.TrimStart( zeroes ); else resultLabel.Text = firstTextBox.Text.TrimStart( zeroes ) + " is NOT smaller than " + secondTextBox.Text.TrimStart( zeroes ); 99 } // end method smallerButton_Click 101 Call HugeInteger Web method Smaller remotely UsingHugeIntegerService.cs

24 Call HugeInteger Web method Bigger remotely UsingHugeIntegerService.cs
// checks whether first integer input // by user is bigger than second protected void biggerButton_Click( object sender, System.EventArgs e ) { // make sure HugeIntegers do not exceed 100 digits if ( CheckSize( firstTextBox, secondTextBox ) ) return; 110 // call Web-service method to determine whether first // integer is larger than the second if ( remoteInteger.Bigger( firstTextBox.Text, secondTextBox.Text ) ) 115 resultLabel.Text = firstTextBox.Text.TrimStart( zeroes ) + " is larger than " + secondTextBox.Text.TrimStart( zeroes ); else resultLabel.Text = firstTextBox.Text.TrimStart( zeroes ) + " is NOT larger than " + secondTextBox.Text.TrimStart( zeroes ); 125 } // end method biggerButton_Click 127 // subtract second integer from first protected void subtractButton_Click( object sender, System.EventArgs e ) { // make sure HugeIntegers do not exceed 100 digits if ( CheckSize( firstTextBox, secondTextBox ) ) return; 135 Call HugeInteger Web method Bigger remotely UsingHugeIntegerService.cs

25 Call HugeInteger Web method Subtract remotely
// perform subtraction try { string result = remoteInteger.Subtract( firstTextBox.Text, secondTextBox.Text ).TrimStart( zeroes ); 142 resultLabel.Text = ( ( result == "" ) ? "0" : result ); } 145 // if WebMethod throws an exception, then first // argument was smaller than second catch ( SoapException ) { MessageBox.Show( "First argument was smaller than the second" ); } 153 } // end method subtractButton_Click 155 // adds two integers input by user protected void addButton_Click( object sender, System.EventArgs e ) { // make sure HugeInteger does not exceed 100 digits // and is not situation where both integers are 100 // digits long--result in overflow if ( firstTextBox.Text.Length > 100 || secondTextBox.Text.Length > 100 || ( firstTextBox.Text.Length == 100 && secondTextBox.Text.Length == 100 ) ) { UsingHugeIntegerService.cs Call HugeInteger Web method Subtract remotely

26 Call HugeInteger Web method Add remotely UsingHugeIntegerService.cs
MessageBox.Show( "HugeIntegers must not be more " "than 100 digits\nBoth integers cannot be of" " length 100: this causes an overflow", "Error", MessageBoxButtons.OK, MessageBoxIcon.Information ); 173 return; } 176 // perform addition resultLabel.Text = remoteInteger.Add( firstTextBox.Text, secondTextBox.Text ).TrimStart( zeroes ).ToString(); 180 } // end method addButton_Click 182 // determines whether size of integers is too big private bool CheckSize( TextBox first, TextBox second ) { if ( first.Text.Length > 100 || second.Text.Length > 100 ) { MessageBox.Show( "HugeIntegers must be less than 100" " digits", "Error", MessageBoxButtons.OK, MessageBoxIcon.Information ); 191 return true; } 194 return false; 196 } // end method CheckSize 198 199 } // end class UsingHugeIntegerService Call HugeInteger Web method Add remotely UsingHugeIntegerService.cs

27 UsingHugeIntegerService.cs Program Output

28 1 // Fig. 21.14: BlackjackService.asmx.cs
2 // Blackjack Web Service which manipulates a deck of cards. 3 4 using System; 5 using System.Collections; 6 using System.ComponentModel; 7 using System.Data; 8 using System.Diagnostics; 9 using System.Web; 10 using System.Web.Services; 11 12 namespace BlackjackWebService 13 { [ WebService( Namespace = "http://www.deitel.com/csphtp1/ch21/", Description = "A Web service that provides methods " + "to manipulate a deck of cards." ) ] public class BlackjackService : System.Web.Services.WebService { 20 // Visual Studio .NET generated code 22 // deal new card [ WebMethod( EnableSession = true, Description = "Deal a new card from the deck." ) ] public string DealCard() { string card = "2 2"; 29 BlackjackService.asmx.cs Method DealCard with WebMethod attribute which allows client applications to invoke it Property EnableSession is set to true allowing this method to maintain session information

29 Set card to be the first object in deck (cast to a string)
// get client's deck ArrayList deck = ( ArrayList ) Session[ "deck" ]; card = ( string ) deck[ 0 ]; deck.RemoveAt( 0 ); return card; 35 } // end method DealCard 37 [ WebMethod( EnableSession = true, Description = "Create and shuffle a deck of cards." ) ] public void Shuffle() { Random randomObject = new Random(); 43 ArrayList deck = new ArrayList(); 45 // generate all possible cards for ( int i = 2; i < 15; i++ ) { for ( int j = 0; j < 4; j++ ) { deck.Add( i + " " + j ); } } 52 // swap each card with another card randomly for ( int i = 0; i < deck.Count; i++ ) { int newIndex = randomObject.Next( deck.Count ); object temporary = deck[ i ]; deck[ i ] = deck[ newIndex ]; deck[ newIndex ] = temporary; } 61 // add this deck to user's session state Session[ "deck" ] = deck; } Retrieve the deck variable from the Session object. Cast the resulting object to an ArrayList and assign local variable deck to reference it Set card to be the first object in deck (cast to a string) Generate all possible cards and add them to deck BlackjackService.asmx.cs Remove the first object from deck Initialize deck to a new ArrayList object Swap each card with a random card from the deck Assign the Session variable deck to reference ArrayList deck

30 If the card is in Ace, increment aceCount but do not add to total
65 // computes value of hand [ WebMethod ( Description = "Compute a " + "numerical value for the current hand." ) ] public int CountCards( string dealt ) { // split string containing cards char[] tab = { '\t' }; string[] cards = dealt.Split( tab ); int total = 0, face, aceCount = 0; 75 foreach ( string drawn in cards ) { // get face of card face = Int32.Parse( drawn.Substring( , drawn.IndexOf( " " ) ) ); 82 switch ( face ) { // if ace, increment number of aces in hand case 14: aceCount++; break; 89 // if Jack, Queen or King, add 10 to total case 11: case 12: case 13: total += 10; break; 94 BlackjackService.asmx.cs If the card is in Ace, increment aceCount but do not add to total Use method Split to create a string array containing the individual cards (stored in dealt and separated by tab characters) Add 10 to total if the card is a Jack, Queen or King Repeat loop for each member of cards

31 Otherwise, add the value of the card to total BlackjackService.asmx.cs
// otherwise, add value of face default: total += face; break; 99 } // end switch 101 } // end foreach 103 // if any aces, calculate optimum total if ( aceCount > 0 ) { // if it is possible to count one ace as 11, and rest // 1 each, do so; otherwise, count all aces as 1 each if ( total aceCount - 1 <= 21 ) total += 11 + aceCount - 1; else total += aceCount; } 114 return total; 116 } // end method CountCards 118 } // end class BlackjackService 120 121 } // end namespace BlackjackWebService Otherwise, add the value of the card to total BlackjackService.asmx.cs If it is possible to count one ace as 11, do so; otherwise, count each ace as 1

32 Blackjack.cs 1 // Fig. 21.15: Blackjack.cs
2 // Blackjack game that uses the Blackjack Web service. 3 4 using System; 5 using System.Drawing; 6 using System.Collections; 7 using System.ComponentModel; 8 using System.Windows.Forms; 9 using System.Data; 10 using System.Net; 11 12 // game that uses Blackjack Web Service 13 public class Blackjack : System.Windows.Forms.Form 14 { private System.Windows.Forms.PictureBox pictureBox1; private System.Windows.Forms.PictureBox pictureBox2; private System.Windows.Forms.PictureBox pictureBox3; private System.Windows.Forms.PictureBox pictureBox4; private System.Windows.Forms.PictureBox pictureBox5; private System.Windows.Forms.PictureBox pictureBox6; private System.Windows.Forms.PictureBox pictureBox7; private System.Windows.Forms.PictureBox pictureBox8; private System.Windows.Forms.PictureBox pictureBox9; private System.Windows.Forms.PictureBox pictureBox10; private System.Windows.Forms.PictureBox pictureBox11; private System.Windows.Forms.PictureBox pictureBox12; private System.Windows.Forms.PictureBox pictureBox13; private System.Windows.Forms.PictureBox pictureBox14; private System.Windows.Forms.PictureBox pictureBox15; private System.Windows.Forms.PictureBox pictureBox16; private System.Windows.Forms.PictureBox pictureBox17; private System.Windows.Forms.PictureBox pictureBox18; private System.Windows.Forms.PictureBox pictureBox19; private System.Windows.Forms.PictureBox pictureBox20; private System.Windows.Forms.PictureBox pictureBox21; Blackjack.cs

33 Instantiate a new BlackjackService object
private System.Windows.Forms.PictureBox pictureBox22; 37 private System.Windows.Forms.Button dealButton; private System.Windows.Forms.Button hitButton; private System.Windows.Forms.Button stayButton; 41 private System.ComponentModel.Container components = null; 43 private localhost.BlackjackService dealer; private string dealersCards, playersCards; private ArrayList cardBoxes; private int playerCard, dealerCard; 48 // labels displaying game status, dealer and player private System.Windows.Forms.Label dealerLabel; private System.Windows.Forms.Label playerLabel; private System.Windows.Forms.Label statusLabel; 53 public enum GameStatus : int { PUSH, LOSE, WIN, BLACKJACK }; 56 public Blackjack() { InitializeComponent(); 60 dealer = new localhost.BlackjackService(); 62 // allow session state dealer.CookieContainer = new CookieContainer(); 65 cardBoxes = new ArrayList(); 67 // put PictureBoxes into cardBoxes cardBoxes.Add( pictureBox1 ); cardBoxes.Add( pictureBox2 ); Blackjack.cs Instantiate a new BlackjackService object Instantiate dealer’s CookieContainer property to allow the Web service to maintain session state information

34 Blackjack.cs 71 cardBoxes.Add( pictureBox3 );
91 } // end method Blackjack 93 // Visual Studio .NET generated code 95 [STAThread] static void Main() { Application.Run( new Blackjack() ); 100 } // end Main 102 Blackjack.cs

35 If dealer went over 21, players wins
// deals cards to dealer while dealer's total is // less than 17, then computes value of each hand // and determines winner protected void stayButton_Click( object sender, System.EventArgs e ) { stayButton.Enabled = false; hitButton.Enabled = false; dealButton.Enabled = true; DealerPlay(); } 114 // process dealers turn private void DealerPlay() { // while value of dealer's hand is below 17, // dealer must take cards while ( dealer.CountCards( dealersCards ) < 17 ) { dealersCards += "\t" + dealer.DealCard(); DisplayCard( dealerCard, "" ); dealerCard++; MessageBox.Show( "Dealer takes a card" ); } 127 int dealersTotal = dealer.CountCards( dealersCards ); int playersTotal = dealer.CountCards( playersCards ); 130 // if dealer busted, player wins if ( dealersTotal > 21 ) { GameOver( GameStatus.WIN ); return; } 137 Blackjack.cs While the dealer’s hand totals less then 17, the dealer must take cards If dealer went over 21, players wins Call method DealerPlay to process the dealer’s turn when the user wishes to stay

36 Deal the player a card as requested
// if dealer and player have not exceeded 21, // higher score wins; equal scores is a push. if ( dealersTotal > playersTotal ) GameOver( GameStatus.LOSE ); else if ( playersTotal > dealersTotal ) GameOver( GameStatus.WIN ); else GameOver( GameStatus.PUSH ); 146 } // end method DealerPlay 148 // deal another card to player protected void hitButton_Click( object sender, System.EventArgs e ) { // get player another card string card = dealer.DealCard(); playersCards += "\t" + card; DisplayCard( playerCard, card ); playerCard++; 158 int total = dealer.CountCards( playersCards ); 160 // if player exceeds 21, house wins if ( total > 21 ) GameOver( GameStatus.LOSE ); 164 If neither the dealer nor the player have went over 21, higher score wins; equal scores result in a push Blackjack.cs Deal the player a card as requested If player went over 21, the house wins

37 If the player has 21, the player cannot take more cards; dealer’s turn
// if player has 21, they cannot take more cards // the dealer plays if ( total == 21 ) { hitButton.Enabled = false; DealerPlay(); } 172 } // end method hitButton_Click 174 // deal two cards each to dealer and player protected void dealButton_Click( object sender, System.EventArgs e ) { string card; 180 // clear card images foreach ( PictureBox cardImage in cardBoxes ) cardImage.Image = null; 184 // clear status from previous game statusLabel.Text = ""; 187 // shuffle cards dealer.Shuffle(); 190 // deal two cards to player playersCards = dealer.DealCard(); DisplayCard( 11, playersCards ); card = dealer.DealCard(); DisplayCard( 12, card ); playersCards += "\t" + card; 197 If the player has 21, the player cannot take more cards; dealer’s turn Blackjack.cs Clear the PictureBoxes containing the card images Shuffle the cards by calling BlackjackService method Shuffle Deal two cards to player

38 Deal two cards to dealer but only display the face of the first one
// deal two cards to dealer, only display face // of first card dealersCards = dealer.DealCard() ; DisplayCard( 0, dealersCards ); card = dealer.DealCard(); DisplayCard( 1, "" ); dealersCards += "\t" + card; 205 stayButton.Enabled = true; hitButton.Enabled = true; dealButton.Enabled = false; 209 int dealersTotal = dealer.CountCards( dealersCards ); int playersTotal = dealer.CountCards( playersCards ); 212 // if hands equal 21, it is a push if ( dealersTotal == playersTotal && dealersTotal == 21 ) GameOver( GameStatus.PUSH ); 217 // if player has 21 player wins with blackjack else if ( playersTotal == 21 ) GameOver( GameStatus.BLACKJACK ); 221 // if dealer has 21, dealer wins else if ( dealersTotal == 21 ) GameOver( GameStatus.LOSE ); 225 dealerCard = 2; playerCard = 13; 228 } // end method dealButton_Click 230 Deal two cards to dealer but only display the face of the first one Blackjack.cs If only the dealer has 21, the dealer wins If only the player has 21, the player wins If both hands equal 21, it is a push

39 Retrieve face and suit of card from cardValue
// displays card represented by cardValue in // PictureBox with number card public void DisplayCard( int card, string cardValue ) { // retrieve appropriate PictureBox from ArrayList PictureBox displayBox = ( PictureBox ) cardBoxes[ card ]; 237 // if string representing card is empty, // set displayBox to display back of card if ( cardValue == "" ) { displayBox.Image = Image.FromFile( "blackjack_images\\cardback.png" ); return; } 246 // retrieve face value of card from cardValue int faceNumber = Int32.Parse( cardValue.Substring( 0, cardValue.IndexOf( " " ) ) ); 250 string face = faceNumber.ToString(); 252 // retrieve the suit of the card from cardValue string suit = cardValue.Substring( cardValue.IndexOf( " " ) + 1 ); 256 char suitLetter; 258 // determine if suit is other than clubs switch ( Convert.ToInt32( suit ) ) { // suit is clubs case 0: suitLetter = 'c'; break; Blackjack.cs Retrieve face and suit of card from cardValue If cardValue is an empty string, display the back of the card image

40 Display all of dealer’s cards
266 // suit is diamonds case 1: suitLetter = 'd'; break; 271 // suit is hearts case 2: suitLetter = 'h'; break; 276 // else suit is spades default: suitLetter = 's'; break; } 282 // set displayBox to display appropriate image displayBox.Image = Image.FromFile( "blackjack_images\\" + face + suitLetter + ".png" ); 286 } // end method DisplayCard 288 // displays all player cards and shows // appropriate game status message public void GameOver( GameStatus winner ) { char[] tab = { '\t' }; string[] cards = dealersCards.Split( tab ); 295 for ( int i = 0; i < cards.Length; i++ ) DisplayCard( i, cards[ i ] ); 298 Blackjack.cs Display all of dealer’s cards

41 Display appropriate message in statusLabel Blackjack.cs
// push if ( winner == GameStatus.PUSH ) statusLabel.Text = "It's a tie!"; 302 // player loses else if ( winner == GameStatus.LOSE ) statusLabel.Text = "You Lose Try Again!"; 306 // player wins else if ( winner == GameStatus.WIN ) statusLabel.Text = "You Win!"; 310 // player has won with blackjack else statusLabel.Text = "BlackJack!"; 314 stayButton.Enabled = false; hitButton.Enabled = false; dealButton.Enabled = true; 318 } // end method GameOver 320 321 } // end class Blackjack Display appropriate message in statusLabel Blackjack.cs

42 Blackjack.cs Program Output

43 Blackjack.cs Program Output

44 Blackjack.cs Program Output

45 Reservation.asmx.cs 1 // Fig. 21.16: Reservation.asmx.cs
2 // Airline reservation Web Service. 3 4 using System; 5 using System.Data; 6 using System.Diagnostics; 7 using System.Web; 8 using System.Web.Services; 9 using System.Data.OleDb; 10 11 namespace AirlineReservation 12 { // performs reservation of a seat [ WebService( Namespace = "http://www.deitel.com/csphtp1/ch21/", Description = "Service that enables a user to " + "reserve a seat on a plane." ) ] public class Reservation : System.Web.Services.WebService { private System.Data.OleDb.OleDbCommand oleDbSelectCommand1; private System.Data.OleDb.OleDbCommand oleDbInsertCommand1; private System.Data.OleDb.OleDbCommand oleDbUpdateCommand1; private System.Data.OleDb.OleDbCommand oleDbDeleteCommand1; private System.Data.OleDb.OleDbConnection oleDbConnection1; private System.Data.OleDb.OleDbDataAdapter oleDbDataAdapter1; 31 // Visual Studio .NET generated code 33 Reservation.asmx.cs

46 Set a query to find seats of the specified criteria. Execute query.
// checks database to determine whether // matching seat is available [ WebMethod ( Description = "Method to reserve seat." ) ] public bool Reserve( string seatType, string classType ) { OleDbDataReader dataReader; 40 // try database connection try { // open database connection oleDbConnection1.Open(); 46 // set and execute SQL query oleDbDataAdapter1.SelectCommand.CommandText = "SELECT Number FROM Seats WHERE Type = '" + seatType + "' AND Class = '" + classType + "' AND Taken = '0'" ; dataReader = oleDbDataAdapter1.SelectCommand.ExecuteReader(); 54 // if there were results, seat is available if ( dataReader.Read() ) { string seatNumber = dataReader.GetString( 0 ); 59 dataReader.Close(); 61 Reservation.asmx.cs Set a query to find seats of the specified criteria. Execute query. If Read method returned true, then query returned result(s) Retrieve the first string in the row (the seat number)

47 62 // update first available seat to be taken
oleDbDataAdapter1.UpdateCommand.CommandText = "Update Seats Set Taken = '1' WHERE Number = '" seatNumber + "'"; oleDbDataAdapter1.UpdateCommand.ExecuteNonQuery(); 67 return true; 69 } // end if dataReader.Close(); } catch ( OleDbException ) // if connection problem { return false; } finally { oleDbConnection1.Close(); } 81 // no seat was reserved return false; 84 } // end method Reserve 86 } // end class Reservation 88 89 } // end namespace AirlineReservation Set a query that updates the seat numbered seatNumber to be taken. Execute query. Reservation.asmx.cs

48 21.6 Using Web Forms and Web Services
Fig Airline Web Service in design view.

49 1 <%-- Fig. 21.18: TicketReservation.aspx --%>
2 <%-- A Web Form to allow users to select the kind of seat --%> 3 <%-- they wish to reserve %> 4 5 Page language="c#" Codebehind="TicketReservation.aspx.cs" AutoEventWireup="false" Inherits="MakeReservation.TicketReservation" %> 8 9 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" > 10 <HTML> <HEAD> <meta name="GENERATOR" Content="Microsoft Visual Studio 7.0"> <meta name="CODE_LANGUAGE" Content="C#"> <meta name="vs_defaultClientScript" content="JavaScript (ECMAScript)"> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5"> </HEAD> <body MS_POSITIONING="GridLayout"> 20 <form id="MakeReservation" method="post" runat="server"> 22 <asp:DropDownList id="seatList" style="Z-INDEX: 101; LEFT: 16px; POSITION: absolute; TOP: 43px" runat="server" Width="105px" Height="22px"> 26 <asp:ListItem Value="Aisle">Aisle</asp:ListItem> <asp:ListItem Value="Middle">Middle</asp:ListItem> <asp:ListItem Value="Window">Window</asp:ListItem> 30 </asp:DropDownList> 32 TicketReservation.aspx

50 33 <asp:DropDownList id="classList" style="Z-INDEX: 102;
LEFT: 145px; POSITION: absolute; TOP: 43px" runat="server" Width="98px" Height="22px"> 36 <asp:ListItem Value="Economy">Economy</asp:ListItem> <asp:ListItem Value="First">First</asp:ListItem> 39 </asp:DropDownList> 41 <asp:Button id="reserveButton" style="Z-INDEX: 103; LEFT: 21px; POSITION: absolute; TOP: 83px" runat="server"Text="Reserve"> </asp:Button> 46 <asp:Label id="Label1" style="Z-INDEX: 104; LEFT: 17px; POSITION: absolute; TOP: 13px" runat="server">Please select the type of seat and class you wish to reserve: </asp:Label> 52 </form> </body> 55 </HTML> TicketReservation.aspx

51 TicketReservation.aspx.cs 1 // Fig. 21.19: TicketReservation.aspx.cs
2 // Making a Reservation using a Web Service. 3 4 using System; 5 using System.Collections; 6 using System.ComponentModel; 7 using System.Data; 8 using System.Drawing; 9 using System.Web; 10 using System.Web.SessionState; 11 using System.Web.UI; 12 using System.Web.UI.WebControls; 13 using System.Web.UI.HtmlControls; 14 15 namespace MakeReservation 16 { // allows visitors to select seat type to reserve, and // then make reservation public class TicketReservation : System.Web.UI.Page { protected System.Web.UI.WebControls.DropDownList seatList; protected System.Web.UI.WebControls.DropDownList classList; 25 protected System.Web.UI.WebControls.Button reserveButton; protected System.Web.UI.WebControls.Label Label1; 29 private localhost.Reservation agent = new localhost.Reservation(); 32 TicketReservation.aspx.cs

52 TicketReservation.aspx.cs 33 private void Page_Load(
object sender, System.EventArgs e ) { if ( IsPostBack ) { seatList.Visible = false; classList.Visible = false; reserveButton.Visible = false; Label1.Visible = false; } } 44 // Visual Studio .NET generated code 46 // calls Web Service to try to reserve specified seat public void reserveButton_Click ( object sender, System.EventArgs e ) { // if Web-service method returned true, signal success if ( agent.Reserve( seatList.SelectedItem.Text, classList.SelectedItem.Text ) ) Response.Write( "Your reservation has been made." " Thank you." ); 56 // Web-service method returned false, so signal failure else Response.Write( "This seat is not available, " + "please hit the back button on your browser " + "and try again." ); 62 } // end method reserveButton_Click 64 } // end class TicketReservation 66 67 } // end namespace MakeReservation TicketReservation.aspx.cs

53 TicketReservation.aspx.cs Program Output

54 TicketReservation.aspx.cs Program Output

55 TemperatureServer.asmx.cs 1 // Fig. 21.20: TemperatureServer.asmx.cs
2 // TemperatureServer Web Service that extracts weather 3 // information from a Web page. 4 5 using System; 6 using System.Collections; 7 using System.ComponentModel; 8 using System.Data; 9 using System.Diagnostics; 10 using System.Web; 11 using System.Web.Services; 12 using System.IO; 13 using System.Net; 14 15 namespace TemperatureWebService 16 { [ WebService( Namespace = "http://www.deitel.com/csphtp1/ch21/", Description = "A Web service that provides information " + "from the National Weather Service." ) ] public class TemperatureServer : System.Web.Services.WebService { // Visual Studio .NET generated code 24 [ WebMethod( EnableSession = true, Description = "Method to read information from the weather service." ) ] public void UpdateWeatherConditions() { // create WebClient to get access to Web page WebClient myClient = new WebClient(); ArrayList cityList = new ArrayList(); 32 TemperatureServer.asmx.cs

56 33 // get StreamReader for response so we can read page
StreamReader input = new StreamReader( myClient.OpenRead( "http://iwin.nws.noaa.gov/iwin/us/" + "traveler.html" ) ); 38 string separator = "TAV12"; 40 // locate first horizontal line on Web page while ( !input.ReadLine().StartsWith( separator ) ) ; // do nothing 44 // day format and night format string dayFormat = "CITY WEA HI/LO WEA " + "HI/LO"; string nightFormat = "CITY WEA LO/HI WEA " + "LO/HI"; string inputLine = ""; 53 // locate header that begins weather information do { inputLine = input.ReadLine(); } while ( !inputLine.Equals( dayFormat ) && !inputLine.Equals( nightFormat ) ); 60 // get first city's data inputLine = input.ReadLine(); 63 TemperatureServer.asmx.cs

57 TemperatureServer.asmx.cs 64 while ( inputLine.Length > 28 ) 65 {
{ // create CityWeather object for city CityWeather weather = new CityWeather( inputLine.Substring( 0, 16 ), inputLine.Substring( 16, 7 ), inputLine.Substring( 23, 7 ) ); 71 // add to List cityList.Add( weather ); 74 // get next city's data inputLine = input.ReadLine(); } 78 // close connection to NWS server input.Close(); 81 // add city list to user session Session.Add( "cityList", cityList ); 84 } // end UpdateWeatherConditions 86 // gets all city names [ WebMethod( EnableSession = true, Description = "Method to retrieve a list of cities." ) ] public string[] Cities() { ArrayList cityList = ( ArrayList ) Session[ "cityList" ]; string[] cities= new string[ cityList.Count ]; 94 TemperatureServer.asmx.cs

58 TemperatureServer.asmx.cs 95 // retrieve names for cities
for ( int i = 0; i < cityList.Count; i++ ) { CityWeather weather = ( CityWeather ) cityList[ i ]; 99 cities[ i ] = weather.CityName; } 102 return cities; 104 } // end method Cities 106 // gets all city descriptions [ WebMethod( EnableSession = true, Description = "Method" + " to retrieve weather descriptions for a " + "list of cities." )] public string[] Descriptions() { ArrayList cityList = ( ArrayList ) Session[ "cityList" ]; string[] descriptions= new string[ cityList.Count ]; 115 // retrieve weather descriptions for all cities for ( int i = 0; i < cityList.Count; i++ ) { CityWeather weather = ( CityWeather )cityList[ i ]; 120 descriptions[ i ] = weather.Description; } 123 return descriptions; 125 } // end method Descriptions 127 TemperatureServer.asmx.cs

59 TemperatureServer.asmx.cs 128 // obtains each city temperature
[ WebMethod( EnableSession = true, Description = "Method " + "to retrieve the temperature for a list of cities." ) ] public string[] Temperatures() { ArrayList cityList = ( ArrayList ) Session[ "cityList" ]; string[] temperatures= new string[ cityList.Count ]; 135 // retrieve temperatures for all cities for ( int i = 0; i < cityList.Count; i++ ) { CityWeather weather = ( CityWeather )cityList[ i ]; temperatures[ i ] = weather.Temperature; } 142 return temperatures; 144 } // end method Temperatures 146 } // end class TemperatureServer 148 149 } // end namespace TemperatureWebService TemperatureServer.asmx.cs

60 CityWeather.cs 1 // Fig. 21.21: CityWeather.cs
2 // Class representing the weather information for one city. 3 4 using System; 5 6 namespace TemperatureWebService 7 { public class CityWeather { private string cityName; private string temperature; private string description; 13 public CityWeather( string city, string information, string degrees ) { cityName = city; description = information; temperature = degrees; } 21 // city name public string CityName { get { return cityName; } } 30 CityWeather.cs

61 CityWeather.cs 31 // city temperature 32 public string Temperature
{ get { return temperature; } } 39 // forecast description public string Description { get { return description; } } 48 } // end class CityWeather 50 } // end namespace TemperatureWebService CityWeather.cs

62 Client.cs 1 // Fig. 21.22: Client.cs
2 // Class that displays weather information that it receives 3 // from a Web service. 4 5 using System; 6 using System.Drawing; 7 using System.Collections; 8 using System.ComponentModel; 9 using System.Windows.Forms; 10 using System.Net; 11 12 namespace TemperatureClient 13 { public class Client : System.Windows.Forms.Form { private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label3; private System.Windows.Forms.Label label4; private System.Windows.Forms.Label label5; private System.Windows.Forms.Label label6; private System.Windows.Forms.Label label7; private System.Windows.Forms.Label label8; private System.Windows.Forms.Label label9; private System.Windows.Forms.Label label10; private System.Windows.Forms.Label label11; private System.Windows.Forms.Label label12; private System.Windows.Forms.Label label13; private System.Windows.Forms.Label label14; private System.Windows.Forms.Label label15; private System.Windows.Forms.Label label16; private System.Windows.Forms.Label label17; private System.Windows.Forms.Label label18; private System.Windows.Forms.Label label19; private System.Windows.Forms.Label label20; Client.cs

63 Client.cs 36 private System.Windows.Forms.Label label21;
52 private System.ComponentModel.Container components = null; 55 public Client() { InitializeComponent(); 59 localhost.TemperatureServer client = new localhost.TemperatureServer(); client.CookieContainer = new CookieContainer(); client.UpdateWeatherConditions(); 64 string[] cities = client.Cities(); string[] descriptions = client.Descriptions(); string[] temperatures = client.Temperatures(); 68 label35.BackgroundImage = new Bitmap( "images/header.png" ); Client.cs

64 Client.cs 71 label36.BackgroundImage = new Bitmap(
"images/header.png" ); 73 // create Hashtable and populate it with every label Hashtable cityLabels = new Hashtable(); cityLabels.Add( 1, label1 ); cityLabels.Add( 2, label2 ); cityLabels.Add( 3, label3 ); cityLabels.Add( 4, label4 ); cityLabels.Add( 5, label5 ); cityLabels.Add( 6, label6 ); cityLabels.Add( 7, label7 ); cityLabels.Add( 8, label8 ); cityLabels.Add( 9, label9 ); cityLabels.Add( 10, label10 ); cityLabels.Add( 11, label11 ); cityLabels.Add( 12, label12 ); cityLabels.Add( 13, label13 ); cityLabels.Add( 14, label14 ); cityLabels.Add( 15, label15 ); cityLabels.Add( 16, label16 ); cityLabels.Add( 17, label17 ); cityLabels.Add( 18, label18 ); cityLabels.Add( 19, label19 ); cityLabels.Add( 20, label20 ); cityLabels.Add( 21, label21 ); cityLabels.Add( 22, label22 ); cityLabels.Add( 23, label23 ); cityLabels.Add( 24, label24 ); cityLabels.Add( 25, label25 ); cityLabels.Add( 26, label26 ); cityLabels.Add( 27, label27 ); cityLabels.Add( 28, label28 ); cityLabels.Add( 29, label29 ); cityLabels.Add( 30, label30 ); Client.cs

65 Client.cs 106 cityLabels.Add( 31, label31 );
110 // create Hashtable and populate with // all weather conditions Hashtable weather = new Hashtable(); weather.Add( "SUNNY", "sunny" ); weather.Add( "PTCLDY", "pcloudy" ); weather.Add( "CLOUDY", "mcloudy" ); weather.Add( "MOCLDY", "mcloudy" ); weather.Add( "TSTRMS", "rain" ); weather.Add( "RAIN", "rain" ); weather.Add( "SNOW", "snow" ); weather.Add( "VRYHOT", "vryhot" ); weather.Add( "FAIR", "fair" ); weather.Add( "RNSNOW", "rnsnow" ); weather.Add( "SHWRS", "showers" ); weather.Add( "WINDY", "windy" ); weather.Add( "NOINFO", "noinfo" ); weather.Add( "MISG", "noinfo" ); weather.Add( "DRZL", "rain" ); weather.Add( "HAZE", "noinfo" ); weather.Add( "SMOKE", "mcloudy" ); 131 Bitmap background = new Bitmap( "images/back.png" ); Font font = new Font( "Courier New", 8, FontStyle.Bold ); 135 // for every city for ( int i = 0; i < cities.Length; i++ ) { // use Hashtable cityLabels to find the next Label Label currentCity = ( Label )cityLabels[ i + 1 ]; Client.cs

66 Client.cs 141 142 // set current Label's image to image
// corresponding to the city's weather condition - // find correct image name in Hashtable weather currentCity.Image = new Bitmap( "images/" + weather[ descriptions[ i ].Trim() ] + ".png" ); 147 // set background image, font and forecolor // of Label currentCity.BackgroundImage = background; currentCity.Font = font; currentCity.ForeColor = Color.White; 153 // set label's text to city name currentCity.Text = "\r\n" + cities[ i ] + " " + temperatures[ i ]; } 158 } // end of constructor 160 // Visual Studio .NET generated code 162 [STAThread] static void Main() { Application.Run( new Client() ); } 168 } // end class Client 170 171 } // end namespace TemperatureClient Client.cs

67 Client.cs Program Output

68 Equation.cs 1 // Fig. 21.23: Equation.cs
2 // Class Equation that contains 3 // information about an equation. 4 5 using System; 6 7 public class Equation 8 { private int left, right, result; private string operation; 11 // required default constructor public Equation() : this( 0, 0, "+" ) { } 16 // constructor for class Equation public Equation( int leftValue, int rightValue, string operationType ) { Left = leftValue; Right = rightValue; Operation = operationType; 24 switch ( operationType ) { case "+": Result = Left + Right; break; case "-": Result = Left - Right; break; Equation.cs

69 Equation.cs 33 case "*": 34 Result = Left * Right; 35 break; 36 } 37 }
} } 38 public override string ToString() { return Left.ToString() + " " + Operation + " " + Right.ToString() + " = " + Result.ToString(); } 44 // property returning string representing // left-hand side public string LeftHandSide { get { return Left.ToString() + " " + Operation + " " + Right.ToString(); } 54 set { } } 59 // property returning string representing // right-hand side public string RightHandSide { get { return Result.ToString(); } Equation.cs

70 68 set { } } 73 // left operand get and set property public int Left { get { return left; } 81 set { left = value; } } 87 // right operand get and set property public int Right { get { return right; } 95 set { right = value; } } 101 Equation.cs

71 Equation.cs 102 // get and set property of result of applying
// operation to left and right operands public int Result { get { return result; } 110 set { result = value; } } 116 // get and set property for operation public string Operation { get { return operation; } 124 set { operation = value; } } 130 131 } // end class Equation Equation.cs

72 Generator.asmx.cs 1 // Fig. 21.24: Generator.asmx.cs
2 // Web Service to generate random equations based on a 3 // specified operation and difficulty level. 4 5 using System; 6 using System.Collections; 7 using System.ComponentModel; 8 using System.Data; 9 using System.Diagnostics; 10 using System.Web; 11 using System.Web.Services; 12 13 namespace EquationGenerator 14 { [ WebService( Namespace = "http://www.deitel.com/csphtp1/ch21", Description = "A Web service that generates questions " + "based on the specified mathematical operation and " + "level of difficulty chosen." ) ] public class Generator : System.Web.Services.WebService { 21 // Visual Studio .NET generated code 23 [ WebMethod ( Description = "Method that generates a random equation." ) ] public Equation GenerateEquation( string operation, int level ) { // find maximum and minimum number to be used int maximum = ( int ) Math.Pow( 10, level ), minimum = ( int ) Math.Pow( 10, level - 1 ); 32 Generator.asmx.cs

73 Generator.asmx.cs 33 Random random = new Random(); 34
// create equation consisting of two random numbers // between minimum and maximum parameters Equation equation = new Equation( random.Next( minimum, maximum ), random.Next( minimum, maximum ), operation ); 40 return equation; 42 } // end method GenerateEquation 44 } // end class Generator 46 47 } // end namespace EquationGenerator Generator.asmx.cs

74 21.8 User Defined Types in Web Services
Create a subtraction exercise Make exercise of user skill level 2 Fig Returning an object from a Web-service method. (Part 1)

75 21.8 User Defined Types in Web Services
Fig Returning an object from a Web-service method. (Part 2)

76 Tutor.cs 1 // Fig. 21.26: Tutor.cs 2 // Math tutor program. 3
4 using System; 5 using System.Drawing; 6 using System.Collections; 7 using System.ComponentModel; 8 using System.Windows.Forms; 9 10 namespace EquationGeneratorClient 11 { public class Tutor : System.Windows.Forms.Form { private System.Windows.Forms.Panel panel1; private System.Windows.Forms.Panel panel2; 16 private System.Windows.Forms.Label questionLabel; private System.Windows.Forms.TextBox answerTextBox; private System.Windows.Forms.Button okButton; private System.Windows.Forms.Button generateButton; 21 private System.Windows.Forms.RadioButton oneRadioButton; private System.Windows.Forms.RadioButton twoRadioButton; private System.Windows.Forms.RadioButton threeRadioButton; private System.Windows.Forms.RadioButton addRadioButton; private System.Windows.Forms.RadioButton subtractRadioButton; private System.Windows.Forms.RadioButton multiplyRadioButton; 31 private System.ComponentModel.Container components = null; private int level = 1; 35 Tutor.cs

77 Tutor.cs 36 private localhost.Equation equation;
private localhost.Generator generator = new localhost.Generator(); private string operation = "+"; 40 // Visual Studio .NET generated code 42 [STAThread] static void Main() { Application.Run( new Tutor() ); } 48 // generates new equation on click event protected void generateButton_Click( object sender, System.EventArgs e ) { // generate equation using current operation // and level equation = generator.GenerateEquation( operation, level ); 57 // display left-hand side of equation questionLabel.Text = equation.LeftHandSide; 60 okButton.Enabled = true; answerTextBox.Enabled = true; 63 } // end method generateButton_Click 65 Tutor.cs

78 Tutor.cs 66 // check users answer
protected void okButton_Click( object sender, System.EventArgs e ) { // determine correct result from Equation // object int answer = equation.Result; 73 // get user's answer int myAnswer = Int32.Parse( answerTextBox.Text ); 76 // test if user's answer is correct if ( answer == myAnswer ) { questionLabel.Text = ""; answerTextBox.Text = ""; okButton.Enabled = false; MessageBox.Show( "Correct! Good job!" ); } else MessageBox.Show( "Incorrect. Try again." ); 87 } // end method okButton_Click 89 // set the selected operation protected void operationRadioButtons_Click( object sender, EventArgs e ) { RadioButton item = ( RadioButton ) sender; 95 Tutor.cs

79 Tutor.cs 96 // set the operation to be the appropriate symbol
if ( item == addRadioButton ) operation = "+"; else if ( item == subtractRadioButton ) operation = "-"; else operation = "*"; 103 generateButton.Text = "Generate " + item.Text + " Example"; 106 } // end method operationRadioButtons_Click 108 // set the current level protected void levelRadioButtons_Click( object sender, EventArgs e ) { if ( sender == oneRadioButton ) level = 1; else if ( sender == twoRadioButton ) level = 2; else level = 3; 119 } // end method levelRadioButtons_Click 121 } // end class Tutor 123 124 } // end namespace EquationGeneratorClient Tutor.cs

80 Tutor.cs Program Output

81 Tutor.cs Program Output


Download ppt "Chapter 21 – ASP .NET and Web Services"

Similar presentations


Ads by Google