81
2002 Prentice Hall. All rights reserved. 1 Chapter 21 – ASP .NET and Web Services Outline 21.1 Introduction 21.2 Web Services 21.3 Simple Object Access Protocol (SOAP) and Web Services 21.4 Publishing and Consuming Web Services 21.5 Session Tracking in Web Services 21.6 Using Web Forms and Web Services 21.7 Case Study: Temperature Information Application 21.8 User-Defined Types in Web Services

2002 Prentice Hall. All rights reserved. 1 Chapter 21 – ASP.NET and Web Services Outline 21.1 Introduction 21.2 Web Services 21.3 Simple Object Access

Embed Size (px)

Citation preview

Page 1: 2002 Prentice Hall. All rights reserved. 1 Chapter 21 – ASP.NET and Web Services Outline 21.1 Introduction 21.2 Web Services 21.3 Simple Object Access

2002 Prentice Hall. All rights reserved.

1

Chapter 21 – ASP .NET and Web Services

Outline21.1 Introduction21.2 Web Services21.3 Simple Object Access Protocol (SOAP) and Web Services21.4 Publishing and Consuming Web Services21.5 Session Tracking in Web Services21.6 Using Web Forms and Web Services21.7 Case Study: Temperature Information Application21.8 User-Defined Types in Web Services

Page 2: 2002 Prentice Hall. All rights reserved. 1 Chapter 21 – ASP.NET and Web Services Outline 21.1 Introduction 21.2 Web Services 21.3 Simple Object Access

2002 Prentice Hall. All rights reserved.

2

21.2 Web Services

Fig. 21.1 ASMX file rendered in Internet Explorer.

Link to service description

Links to web service methods

Page 3: 2002 Prentice Hall. All rights reserved. 1 Chapter 21 – ASP.NET and Web Services Outline 21.1 Introduction 21.2 Web Services 21.3 Simple Object Access

2002 Prentice Hall. All rights reserved.

3

21.2 Web Services

Fig. 21.2 Service description for a Web service.

Page 4: 2002 Prentice Hall. All rights reserved. 1 Chapter 21 – ASP.NET and Web Services Outline 21.1 Introduction 21.2 Web Services 21.3 Simple Object Access

2002 Prentice Hall. All rights reserved.

4

21.2 Web Services

Fig. 21.3 Invoking a method of a Web service from a Web browser.

Page 5: 2002 Prentice Hall. All rights reserved. 1 Chapter 21 – ASP.NET and Web Services Outline 21.1 Introduction 21.2 Web Services 21.3 Simple Object Access

2002 Prentice Hall. All rights reserved.

5

21.2 Web Services

Fig. 21.4 Results of invoking a Web-service method from a Web browser.

Page 6: 2002 Prentice Hall. All rights reserved. 1 Chapter 21 – ASP.NET and Web Services Outline 21.1 Introduction 21.2 Web Services 21.3 Simple Object Access

2002 Prentice Hall. All rights reserved.

6

21.3 Simple Object Access Protocol (SOAP) and Web Services

1 POST /HugeIntegerWebService/HugeInteger.asmx HTTP/1.12 Host: localhost3 Content-Type: text/xml; charset=utf-84 Content-Length: length5 SOAPAction: "http://www.deitel.com/csphtp1/ch21/Bigger"6 7 <?xml version="1.0" encoding="utf-8"?>8 9 <soap:Envelope10 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"11 xmlns:xsd="http://www.w3.org/2001/XMLSchema"12 xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">13 14 <soap:Body>15 <Bigger xmlns="http://www.deitel.com/csphtp1/ch21/">16 <first>string</first>17 <second>string</second>18 </Bigger>19 </soap:Body>20 21 </soap:Envelope>

Fig. 21.5 SOAP request for the HugeInteger Web service.

Name of method

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.

Page 7: 2002 Prentice Hall. All rights reserved. 1 Chapter 21 – ASP.NET and Web Services Outline 21.1 Introduction 21.2 Web Services 21.3 Simple Object Access

2002 Prentice Hall.All rights reserved.

Outline7

HugeInteger.asmx.cs

1 // Fig. 21.6: HugeInteger.asmx.cs2 // 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 classes12 13 namespace HugeIntegerWebService14 {15 /// <summary>16 /// performs operations on large integers17 /// </summary>18 [ WebService( 19 Namespace = "http://www.deitel.com/csphtp1/ch21/",20 Description = "A Web service which provides methods that" +21 " can manipulate large integer values." ) ]22 public class HugeInteger : System.Web.Services.WebService23 {24 // default constructor25 public HugeInteger()26 {27 // CODEGEN: This call is required by the ASP .NET Web 28 // Services Designer29 InitializeComponent();30 31 number = new int[ MAXIMUM ];32 }33

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

Page 8: 2002 Prentice Hall. All rights reserved. 1 Chapter 21 – ASP.NET and Web Services Outline 21.1 Introduction 21.2 Web Services 21.3 Simple Object Access

2002 Prentice Hall.All rights reserved.

Outline8

HugeInteger.asmx.cs

34 #region Component Designer generated code35 /// <summary>36 /// Required method for Designer support - do not modify37 /// the contents of this method with the code editor.38 /// </summary>39 private void InitializeComponent()40 {41 }42 #endregion43 44 /// <summary>45 /// Clean up any resources being used.46 /// </summary>47 protected override void Dispose( bool disposing )48 {49 }50 51 // WEB SERVICE EXAMPLE52 // The HelloWorld() example service returns 53 // the string Hello World54 // To build, uncomment the following lines 55 // then save and build the project56 // To test this web service, press F557 58 // [WebMethod]59 // public string HelloWorld()60 // {61 // return "Hello World";62 // }63 64 private const int MAXIMUM = 100;65 66 public int[] number;67

Page 9: 2002 Prentice Hall. All rights reserved. 1 Chapter 21 – ASP.NET and Web Services Outline 21.1 Introduction 21.2 Web Services 21.3 Simple Object Access

2002 Prentice Hall.All rights reserved.

Outline9

HugeInteger.asmx.cs

68 // indexer that accepts an integer parameter69 public int this[ int index ]70 {71 get72 { 73 return number[ index ];74 }75 76 set77 {78 number[ index ] = value;79 }80 81 } // end indexer82 83 // returns string representation of HugeInteger84 public override string ToString()85 {86 StringBuilder returnString = new StringBuilder();87 88 foreach ( int digit in number )89 returnString.Insert( 0, digit );90 91 return returnString.ToString();92 }93 94 // creates HugeInteger based on argument95 public static HugeInteger FromString( string integer )96 {97 HugeInteger parsedInteger = new HugeInteger();98 99 for ( int i = 0; i < integer.Length; i++ )100 parsedInteger[ i ] = Int32.Parse( 101 integer[ integer.Length - i - 1 ].ToString() );

Indexer for class HugeInteger

Page 10: 2002 Prentice Hall. All rights reserved. 1 Chapter 21 – ASP.NET and Web Services Outline 21.1 Introduction 21.2 Web Services 21.3 Simple Object Access

2002 Prentice Hall.All rights reserved.

Outline10

HugeInteger.asmx.cs

102 103 return parsedInteger;104 }105 106 // WebMethod that performs integer addition107 // represented by string arguments108 [ WebMethod ( Description = "Adds two huge integers." ) ]109 public string Add( string first, string second )110 {111 int carry = 0;112 113 HugeInteger operand1 = HugeInteger.FromString( first );114 HugeInteger operand2 = 115 HugeInteger.FromString( second );116 117 // store result of addition118 HugeInteger result = new HugeInteger();119 120 // perform addition algorithm for each digit121 for ( int i = 0; i < MAXIMUM; i++ )122 {123 // add two digits in same column124 // result is their sum, plus carry from 125 // previous operation modulus 10126 result[ i ] = 127 ( operand1[ i ] + operand2[ i ] ) % 10 + carry;128 129 // store remainder of dividing130 // sums of two digits by 10131 carry = ( operand1[ i ] + operand2[ i ] ) / 10;132 }133 134 return result.ToString();135 136 } // end method Add

Method Add that adds two HugeIntegers

WebMethod attribute specifies that this method may be called by remote client applications

Description property of WebMethod attribute summarizes the function of the method

Page 11: 2002 Prentice Hall. All rights reserved. 1 Chapter 21 – ASP.NET and Web Services Outline 21.1 Introduction 21.2 Web Services 21.3 Simple Object Access

2002 Prentice Hall.All rights reserved.

Outline11

HugeInteger.asmx.cs

137 138 // WebMethod that performs the subtraction of integers 139 // represented by string arguments140 [ WebMethod ( 141 Description = "Subtracts two huge integers." ) ]142 public string Subtract( string first, string second )143 {144 HugeInteger operand1 = HugeInteger.FromString( first );145 HugeInteger operand2 = 146 HugeInteger.FromString( second );147 HugeInteger result = new HugeInteger();148 149 // subtract top digit from bottom digit150 for ( int i = 0; i < MAXIMUM; i++ )151 {152 // if top digit is smaller than bottom153 // digit we need to borrow154 if ( operand1[ i ] < operand2[ i ] )155 Borrow( operand1, i );156 157 // subtract bottom from top158 result[ i ] = operand1[ i ] - operand2[ i ];159 }160 161 return result.ToString();162 163 } // end method Subtract164 165 // borrows 1 from next digit166 private void Borrow( HugeInteger integer, int place )167 {168 // if no place to borrow from, signal problem169 if ( place >= MAXIMUM - 1 )170 throw new ArgumentException();171

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

Page 12: 2002 Prentice Hall. All rights reserved. 1 Chapter 21 – ASP.NET and Web Services Outline 21.1 Introduction 21.2 Web Services 21.3 Simple Object Access

2002 Prentice Hall.All rights reserved.

Outline12

HugeInteger.asmx.cs

172 // otherwise if next digit is zero, 173 // borrow from digit to left174 else if ( integer[ place + 1 ] == 0 )175 Borrow( integer, place + 1 );176 177 // add ten to current place because we borrowed178 // and subtract one from previous digit - 179 // this is digit borrowed from180 integer[ place ] += 10;181 integer[ place + 1 ] -= 1; 182 183 } // end method Borrow184 185 // WebMethod that returns true if first integer is 186 // bigger than second187 [ WebMethod ( Description = "Determines whether first " +188 "integer is larger than the second integer." ) ]189 public bool Bigger( string first, string second )190 {191 char[] zeroes = { '0' };192 193 try194 {195 // if elimination of all zeroes from result196 // of subtraction is an empty string,197 // numbers are equal, so return false, 198 // otherwise return true199 if ( Subtract( first, second ).Trim( zeroes ) == "" )200 return false;201 else202 return true;203 }204

Returns true if the first integer is bigger then the second and false otherwise

Page 13: 2002 Prentice Hall. All rights reserved. 1 Chapter 21 – ASP.NET and Web Services Outline 21.1 Introduction 21.2 Web Services 21.3 Simple Object Access

2002 Prentice Hall.All rights reserved.

Outline13

HugeInteger.asmx.cs

205 // if ArgumentException occurs, first number206 // was smaller, so return false207 catch ( ArgumentException )208 {209 return false;210 }211 212 } // end method Bigger213 214 // WebMethod returns true if first integer is 215 // smaller than second216 [ WebMethod ( Description = "Determines whether the " +217 "first integer is smaller than the second integer." ) ]218 public bool Smaller( string first, string second )219 {220 // if second is bigger than first, then first is 221 // smaller than second222 return Bigger( second, first );223 }224 225 // WebMethod that returns true if two integers are equal226 [ WebMethod ( Description = "Determines whether the " +227 "first integer is equal to the second integer." ) ]228 public bool EqualTo( string first, string second )229 {230 // if either first is bigger than second, or first is 231 // smaller than second, they are not equal232 if ( Bigger( first, second ) || 233 Smaller( first, second ) )234 return false;

Returns true if the first integer is smaller then the second and false otherwise

Returns true if the two integers are equal and false otherwise

Page 14: 2002 Prentice Hall. All rights reserved. 1 Chapter 21 – ASP.NET and Web Services Outline 21.1 Introduction 21.2 Web Services 21.3 Simple Object Access

2002 Prentice Hall.All rights reserved.

Outline14

HugeInteger.asmx.cs

Program Output

235 else236 return true;237 } 238 239 } // end class HugeInteger240 241 } // end namespace HugeIntegerWebService

Page 15: 2002 Prentice Hall. All rights reserved. 1 Chapter 21 – ASP.NET and Web Services Outline 21.1 Introduction 21.2 Web Services 21.3 Simple Object Access

2002 Prentice Hall. All rights reserved.

15

21.4 Publishing and Consuming Web Services

Fig. 21.7 Design view of a Web service.

Page 16: 2002 Prentice Hall. All rights reserved. 1 Chapter 21 – ASP.NET and Web Services Outline 21.1 Introduction 21.2 Web Services 21.3 Simple Object Access

2002 Prentice Hall. All rights reserved.

16

21.4 Publishing and Consuming Web Services

Fig. 21.8 Adding a Web service reference to a project.

Page 17: 2002 Prentice Hall. All rights reserved. 1 Chapter 21 – ASP.NET and Web Services Outline 21.1 Introduction 21.2 Web Services 21.3 Simple Object Access

2002 Prentice Hall. All rights reserved.

17

21.4 Publishing and Consuming Web Services

Fig. 21.9 Add Web Reference dialog.

Link to root directory of web server

Page 18: 2002 Prentice Hall. All rights reserved. 1 Chapter 21 – ASP.NET and Web Services Outline 21.1 Introduction 21.2 Web Services 21.3 Simple Object Access

2002 Prentice Hall. All rights reserved.

18

21.4 Publishing and Consuming Web Services

Fig. 21.10 Web services located on localhost.

Page 19: 2002 Prentice Hall. All rights reserved. 1 Chapter 21 – ASP.NET and Web Services Outline 21.1 Introduction 21.2 Web Services 21.3 Simple Object Access

2002 Prentice Hall. All rights reserved.

19

21.4 Publishing and Consuming Web Services

Fig. 21.11 Web reference selection and description.

Page 20: 2002 Prentice Hall. All rights reserved. 1 Chapter 21 – ASP.NET and Web Services Outline 21.1 Introduction 21.2 Web Services 21.3 Simple Object Access

2002 Prentice Hall. All rights reserved.

20

21.4 Publishing and Consuming Web Services

Fig. 21.12 Solution Explorer after adding a Web reference to a project.

Service description

Proxy class

Web service discovery file

Page 21: 2002 Prentice Hall. All rights reserved. 1 Chapter 21 – ASP.NET and Web Services Outline 21.1 Introduction 21.2 Web Services 21.3 Simple Object Access

2002 Prentice Hall.All rights reserved.

Outline21

UsingHugeIntegerService.cs

1 // Fig. 21.13: UsingHugeIntegerService.cs2 // 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 integers12 public class UsingHugeIntService : System.Windows.Forms.Form13 {14 private System.Windows.Forms.Label promptLabel;15 private System.Windows.Forms.Label resultLabel;16 17 private System.Windows.Forms.TextBox firstTextBox;18 private System.Windows.Forms.TextBox secondTextBox;19 20 private System.Windows.Forms.Button addButton;21 private System.Windows.Forms.Button subtractButton;22 private System.Windows.Forms.Button biggerButton;23 private System.Windows.Forms.Button smallerButton;24 private System.Windows.Forms.Button equalButton;25 26 private System.ComponentModel.Container components = null;27 28 // declare a reference Web service29 private localhost.HugeInteger remoteInteger;30 31 private char[] zeroes = { '0' };32

Page 22: 2002 Prentice Hall. All rights reserved. 1 Chapter 21 – ASP.NET and Web Services Outline 21.1 Introduction 21.2 Web Services 21.3 Simple Object Access

2002 Prentice Hall.All rights reserved.

Outline22

UsingHugeIntegerService.cs

33 // default constructor34 public UsingHugeIntService()35 {36 InitializeComponent();37 38 // instantiate remoteInteger39 remoteInteger = new localhost.HugeInteger();40 }41 42 // Visual Studio .NET generated code43 44 [STAThread]45 static void Main()46 {47 Application.Run( new UsingHugeIntService() );48 49 } // end Main50 51 // checks whether two numbers user input are equal52 protected void equalButton_Click( 53 object sender, System.EventArgs e )54 {55 // make sure HugeIntegers do not exceed 100 digits56 if ( CheckSize( firstTextBox, secondTextBox ) )57 return;58 59 // call Web-service method to determine 60 // whether integers are equal61 if ( remoteInteger.EqualTo( 62 firstTextBox.Text, secondTextBox.Text ) )63 64 resultLabel.Text = 65 firstTextBox.Text.TrimStart( zeroes ) +66 " is equal to " +67 secondTextBox.Text.TrimStart( zeroes );

Instantiate remoteInteger to be a new HugeInteger object

Call HugeInteger Web method EqualTo remotely

Page 23: 2002 Prentice Hall. All rights reserved. 1 Chapter 21 – ASP.NET and Web Services Outline 21.1 Introduction 21.2 Web Services 21.3 Simple Object Access

2002 Prentice Hall.All rights reserved.

Outline23

UsingHugeIntegerService.cs

68 else69 resultLabel.Text = 70 firstTextBox.Text.TrimStart( zeroes ) + 71 " is NOT equal to " + 72 secondTextBox.Text.TrimStart( zeroes );73 74 } // end method equalButton_Click75 76 // checks whether first integer input77 // by user is smaller than second78 protected void smallerButton_Click( 79 object sender, System.EventArgs e )80 {81 // make sure HugeIntegers do not exceed 100 digits82 if ( CheckSize( firstTextBox, secondTextBox ) )83 return;84 85 // call Web-service method to determine whether first86 // integer is smaller than second87 if ( remoteInteger.Smaller( 88 firstTextBox.Text, secondTextBox.Text ) )89 90 resultLabel.Text =91 firstTextBox.Text.TrimStart( zeroes ) + 92 " is smaller than " + 93 secondTextBox.Text.TrimStart( zeroes );94 else95 resultLabel.Text =96 firstTextBox.Text.TrimStart( zeroes ) + 97 " is NOT smaller than " + 98 secondTextBox.Text.TrimStart( zeroes );99 100 } // end method smallerButton_Click101

Call HugeInteger Web method Smaller remotely

Page 24: 2002 Prentice Hall. All rights reserved. 1 Chapter 21 – ASP.NET and Web Services Outline 21.1 Introduction 21.2 Web Services 21.3 Simple Object Access

2002 Prentice Hall.All rights reserved.

Outline24

UsingHugeIntegerService.cs

102 // checks whether first integer input 103 // by user is bigger than second104 protected void biggerButton_Click( 105 object sender, System.EventArgs e )106 {107 // make sure HugeIntegers do not exceed 100 digits108 if ( CheckSize( firstTextBox, secondTextBox ) )109 return;110 111 // call Web-service method to determine whether first112 // integer is larger than the second113 if ( remoteInteger.Bigger( firstTextBox.Text, 114 secondTextBox.Text ) )115 116 resultLabel.Text = 117 firstTextBox.Text.TrimStart( zeroes ) + 118 " is larger than " + 119 secondTextBox.Text.TrimStart( zeroes );120 else121 resultLabel.Text = 122 firstTextBox.Text.TrimStart( zeroes ) + 123 " is NOT larger than " + 124 secondTextBox.Text.TrimStart( zeroes );125 126 } // end method biggerButton_Click127 128 // subtract second integer from first129 protected void subtractButton_Click( 130 object sender, System.EventArgs e )131 {132 // make sure HugeIntegers do not exceed 100 digits133 if ( CheckSize( firstTextBox, secondTextBox ) )134 return;135

Call HugeInteger Web method Bigger remotely

Page 25: 2002 Prentice Hall. All rights reserved. 1 Chapter 21 – ASP.NET and Web Services Outline 21.1 Introduction 21.2 Web Services 21.3 Simple Object Access

2002 Prentice Hall.All rights reserved.

Outline25

UsingHugeIntegerService.cs

136 // perform subtraction137 try138 {139 string result = remoteInteger.Subtract( 140 firstTextBox.Text, 141 secondTextBox.Text ).TrimStart( zeroes );142 143 resultLabel.Text = ( ( result == "" ) ? "0" : result );144 }145 146 // if WebMethod throws an exception, then first147 // argument was smaller than second148 catch ( SoapException )149 {150 MessageBox.Show( 151 "First argument was smaller than the second" );152 }153 154 } // end method subtractButton_Click155 156 // adds two integers input by user157 protected void addButton_Click( 158 object sender, System.EventArgs e )159 {160 // make sure HugeInteger does not exceed 100 digits161 // and is not situation where both integers are 100162 // digits long--result in overflow163 if ( firstTextBox.Text.Length > 100 ||164 secondTextBox.Text.Length > 100 ||165 ( firstTextBox.Text.Length == 100 &&166 secondTextBox.Text.Length == 100 ) )167 {

Call HugeInteger Web method Subtract remotely

Page 26: 2002 Prentice Hall. All rights reserved. 1 Chapter 21 – ASP.NET and Web Services Outline 21.1 Introduction 21.2 Web Services 21.3 Simple Object Access

2002 Prentice Hall.All rights reserved.

Outline26

UsingHugeIntegerService.cs

168 MessageBox.Show( "HugeIntegers must not be more "169 + "than 100 digits\nBoth integers cannot be of"170 + " length 100: this causes an overflow", 171 "Error", MessageBoxButtons.OK,172 MessageBoxIcon.Information );173 174 return;175 }176 177 // perform addition178 resultLabel.Text = remoteInteger.Add( firstTextBox.Text,179 secondTextBox.Text ).TrimStart( zeroes ).ToString();180 181 } // end method addButton_Click182 183 // determines whether size of integers is too big184 private bool CheckSize( TextBox first, TextBox second )185 {186 if ( first.Text.Length > 100 || second.Text.Length > 100 )187 {188 MessageBox.Show( "HugeIntegers must be less than 100"189 + " digits", "Error", MessageBoxButtons.OK,190 MessageBoxIcon.Information );191 192 return true;193 }194 195 return false;196 197 } // end method CheckSize198 199 } // end class UsingHugeIntegerService

Call HugeInteger Web method Add remotely

Page 27: 2002 Prentice Hall. All rights reserved. 1 Chapter 21 – ASP.NET and Web Services Outline 21.1 Introduction 21.2 Web Services 21.3 Simple Object Access

2002 Prentice Hall.All rights reserved.

Outline27

UsingHugeIntegerService.csProgram Output

Page 28: 2002 Prentice Hall. All rights reserved. 1 Chapter 21 – ASP.NET and Web Services Outline 21.1 Introduction 21.2 Web Services 21.3 Simple Object Access

2002 Prentice Hall.All rights reserved.

Outline28

BlackjackService.asmx.cs

1 // Fig. 21.14: BlackjackService.asmx.cs2 // 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 BlackjackWebService13 {14 [ WebService( 15 Namespace = "http://www.deitel.com/csphtp1/ch21/",16 Description = "A Web service that provides methods " +17 "to manipulate a deck of cards." ) ]18 public class BlackjackService : System.Web.Services.WebService19 {20 21 // Visual Studio .NET generated code22 23 // deal new card24 [ WebMethod( EnableSession = true,25 Description = "Deal a new card from the deck." ) ]26 public string DealCard()27 {28 string card = "2 2";29

Method DealCard with WebMethod attribute which allows client applications to invoke itProperty EnableSession is set

to true allowing this method to maintain session information

Page 29: 2002 Prentice Hall. All rights reserved. 1 Chapter 21 – ASP.NET and Web Services Outline 21.1 Introduction 21.2 Web Services 21.3 Simple Object Access

2002 Prentice Hall.All rights reserved.

Outline29

BlackjackService.asmx.cs

30 // get client's deck31 ArrayList deck = ( ArrayList ) Session[ "deck" ];32 card = ( string ) deck[ 0 ];33 deck.RemoveAt( 0 );34 return card;35 36 } // end method DealCard37 38 [ WebMethod( EnableSession = true,39 Description = "Create and shuffle a deck of cards." ) ]40 public void Shuffle()41 {42 Random randomObject = new Random();43 44 ArrayList deck = new ArrayList();45 46 // generate all possible cards47 for ( int i = 2; i < 15; i++ ) {48 for ( int j = 0; j < 4; j++ ) {49 deck.Add( i + " " + j ); 50 }51 }52 53 // swap each card with another card randomly54 for ( int i = 0; i < deck.Count; i++ )55 {56 int newIndex = randomObject.Next( deck.Count );57 object temporary = deck[ i ]; 58 deck[ i ] = deck[ newIndex ];59 deck[ newIndex ] = temporary;60 }61 62 // add this deck to user's session state63 Session[ "deck" ] = deck;64 }

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)

Remove the first object from deck

Initialize deck to a new ArrayList object

Generate all possible cards and add them to deck

Swap each card with a random card from the deck

Assign the Session variable deck to reference ArrayList deck

Page 30: 2002 Prentice Hall. All rights reserved. 1 Chapter 21 – ASP.NET and Web Services Outline 21.1 Introduction 21.2 Web Services 21.3 Simple Object Access

2002 Prentice Hall.All rights reserved.

Outline30

BlackjackService.asmx.cs

65 66 // computes value of hand67 [ WebMethod ( Description = "Compute a " +68 "numerical value for the current hand." ) ]69 public int CountCards( string dealt )70 {71 // split string containing cards72 char[] tab = { '\t' };73 string[] cards = dealt.Split( tab );74 int total = 0, face, aceCount = 0;75 76 foreach ( string drawn in cards )77 {78 // get face of card79 face = 80 Int32.Parse( drawn.Substring(81 0, drawn.IndexOf( " " ) ) );82 83 switch ( face )84 {85 // if ace, increment number of aces in hand86 case 14:87 aceCount++;88 break;89 90 // if Jack, Queen or King, add 10 to total91 case 11: case 12: case 13:92 total += 10;93 break;94

Use method Split to create a string array containing the individual cards (stored in dealt and separated by tab characters)

Repeat loop for each member of cards

If the card is in Ace, increment aceCount but do not add to total

Add 10 to total if the card is a Jack, Queen or King

Page 31: 2002 Prentice Hall. All rights reserved. 1 Chapter 21 – ASP.NET and Web Services Outline 21.1 Introduction 21.2 Web Services 21.3 Simple Object Access

2002 Prentice Hall.All rights reserved.

Outline31

BlackjackService.asmx.cs

95 // otherwise, add value of face96 default:97 total += face;98 break;99 100 } // end switch101 102 } // end foreach103 104 // if any aces, calculate optimum total105 if ( aceCount > 0 )106 {107 // if it is possible to count one ace as 11, and rest108 // 1 each, do so; otherwise, count all aces as 1 each109 if ( total + 11 + aceCount - 1 <= 21 )110 total += 11 + aceCount - 1;111 else112 total += aceCount;113 }114 115 return total;116 117 } // end method CountCards118 119 } // end class BlackjackService120 121 } // end namespace BlackjackWebService

Otherwise, add the value of the card to totalIf it is possible to count one ace as 11,

do so; otherwise, count each ace as 1

Page 32: 2002 Prentice Hall. All rights reserved. 1 Chapter 21 – ASP.NET and Web Services Outline 21.1 Introduction 21.2 Web Services 21.3 Simple Object Access

2002 Prentice Hall.All rights reserved.

Outline32

Blackjack.cs

1 // Fig. 21.15: Blackjack.cs2 // 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 Service13 public class Blackjack : System.Windows.Forms.Form14 {15 private System.Windows.Forms.PictureBox pictureBox1;16 private System.Windows.Forms.PictureBox pictureBox2;17 private System.Windows.Forms.PictureBox pictureBox3;18 private System.Windows.Forms.PictureBox pictureBox4;19 private System.Windows.Forms.PictureBox pictureBox5;20 private System.Windows.Forms.PictureBox pictureBox6;21 private System.Windows.Forms.PictureBox pictureBox7;22 private System.Windows.Forms.PictureBox pictureBox8;23 private System.Windows.Forms.PictureBox pictureBox9;24 private System.Windows.Forms.PictureBox pictureBox10;25 private System.Windows.Forms.PictureBox pictureBox11;26 private System.Windows.Forms.PictureBox pictureBox12;27 private System.Windows.Forms.PictureBox pictureBox13;28 private System.Windows.Forms.PictureBox pictureBox14;29 private System.Windows.Forms.PictureBox pictureBox15;30 private System.Windows.Forms.PictureBox pictureBox16;31 private System.Windows.Forms.PictureBox pictureBox17;32 private System.Windows.Forms.PictureBox pictureBox18;33 private System.Windows.Forms.PictureBox pictureBox19;34 private System.Windows.Forms.PictureBox pictureBox20;35 private System.Windows.Forms.PictureBox pictureBox21;

Page 33: 2002 Prentice Hall. All rights reserved. 1 Chapter 21 – ASP.NET and Web Services Outline 21.1 Introduction 21.2 Web Services 21.3 Simple Object Access

2002 Prentice Hall.All rights reserved.

Outline33

Blackjack.cs

36 private System.Windows.Forms.PictureBox pictureBox22;37 38 private System.Windows.Forms.Button dealButton;39 private System.Windows.Forms.Button hitButton;40 private System.Windows.Forms.Button stayButton;41 42 private System.ComponentModel.Container components = null;43 44 private localhost.BlackjackService dealer;45 private string dealersCards, playersCards;46 private ArrayList cardBoxes;47 private int playerCard, dealerCard;48 49 // labels displaying game status, dealer and player50 private System.Windows.Forms.Label dealerLabel;51 private System.Windows.Forms.Label playerLabel;52 private System.Windows.Forms.Label statusLabel;53 54 public enum GameStatus : 55 int { PUSH, LOSE, WIN, BLACKJACK };56 57 public Blackjack()58 {59 InitializeComponent();60 61 dealer = new localhost.BlackjackService();62 63 // allow session state64 dealer.CookieContainer = new CookieContainer();65 66 cardBoxes = new ArrayList();67 68 // put PictureBoxes into cardBoxes69 cardBoxes.Add( pictureBox1 );70 cardBoxes.Add( pictureBox2 );

Instantiate a new BlackjackService object

Instantiate dealer’s CookieContainer property to allow the Web service to maintain session state information

Page 34: 2002 Prentice Hall. All rights reserved. 1 Chapter 21 – ASP.NET and Web Services Outline 21.1 Introduction 21.2 Web Services 21.3 Simple Object Access

2002 Prentice Hall.All rights reserved.

Outline34

Blackjack.cs

71 cardBoxes.Add( pictureBox3 );72 cardBoxes.Add( pictureBox4 );73 cardBoxes.Add( pictureBox5 );74 cardBoxes.Add( pictureBox6 );75 cardBoxes.Add( pictureBox7 );76 cardBoxes.Add( pictureBox8 );77 cardBoxes.Add( pictureBox9 );78 cardBoxes.Add( pictureBox10 );79 cardBoxes.Add( pictureBox11 );80 cardBoxes.Add( pictureBox12 );81 cardBoxes.Add( pictureBox13 );82 cardBoxes.Add( pictureBox14 );83 cardBoxes.Add( pictureBox15 );84 cardBoxes.Add( pictureBox16 );85 cardBoxes.Add( pictureBox17 );86 cardBoxes.Add( pictureBox18 );87 cardBoxes.Add( pictureBox19 );88 cardBoxes.Add( pictureBox20 );89 cardBoxes.Add( pictureBox21 );90 cardBoxes.Add( pictureBox22 );91 92 } // end method Blackjack93 94 // Visual Studio .NET generated code95 96 [STAThread]97 static void Main() 98 {99 Application.Run( new Blackjack() );100 101 } // end Main102

Page 35: 2002 Prentice Hall. All rights reserved. 1 Chapter 21 – ASP.NET and Web Services Outline 21.1 Introduction 21.2 Web Services 21.3 Simple Object Access

2002 Prentice Hall.All rights reserved.

Outline35

Blackjack.cs

103 // deals cards to dealer while dealer's total is 104 // less than 17, then computes value of each hand 105 // and determines winner106 protected void stayButton_Click( 107 object sender, System.EventArgs e )108 {109 stayButton.Enabled = false;110 hitButton.Enabled = false;111 dealButton.Enabled = true;112 DealerPlay();113 }114 115 // process dealers turn116 private void DealerPlay()117 {118 // while value of dealer's hand is below 17,119 // dealer must take cards120 while ( dealer.CountCards( dealersCards ) < 17 )121 {122 dealersCards += "\t" + dealer.DealCard();123 DisplayCard( dealerCard, "" );124 dealerCard++;125 MessageBox.Show( "Dealer takes a card" );126 }127 128 int dealersTotal = dealer.CountCards( dealersCards );129 int playersTotal = dealer.CountCards( playersCards );130 131 // if dealer busted, player wins132 if ( dealersTotal > 21 )133 { 134 GameOver( GameStatus.WIN );135 return;136 }137

Call method DealerPlay to process the dealer’s turn when the user wishes to stay

While the dealer’s hand totals less then 17, the dealer must take cards

If dealer went over 21, players wins

Page 36: 2002 Prentice Hall. All rights reserved. 1 Chapter 21 – ASP.NET and Web Services Outline 21.1 Introduction 21.2 Web Services 21.3 Simple Object Access

2002 Prentice Hall.All rights reserved.

Outline36

Blackjack.cs

138 // if dealer and player have not exceeded 21,139 // higher score wins; equal scores is a push.140 if ( dealersTotal > playersTotal )141 GameOver( GameStatus.LOSE );142 else if ( playersTotal > dealersTotal )143 GameOver( GameStatus.WIN );144 else145 GameOver( GameStatus.PUSH );146 147 } // end method DealerPlay148 149 // deal another card to player150 protected void hitButton_Click( 151 object sender, System.EventArgs e )152 {153 // get player another card154 string card = dealer.DealCard();155 playersCards += "\t" + card;156 DisplayCard( playerCard, card );157 playerCard++;158 159 int total = dealer.CountCards( playersCards );160 161 // if player exceeds 21, house wins162 if ( total > 21 )163 GameOver( GameStatus.LOSE );164

If neither the dealer nor the player have went over 21, higher score wins; equal scores result in a push

Deal the player a card as requested

If player went over 21, the house wins

Page 37: 2002 Prentice Hall. All rights reserved. 1 Chapter 21 – ASP.NET and Web Services Outline 21.1 Introduction 21.2 Web Services 21.3 Simple Object Access

2002 Prentice Hall.All rights reserved.

Outline37

Blackjack.cs

165 // if player has 21, they cannot take more cards166 // the dealer plays167 if ( total == 21 ) 168 {169 hitButton.Enabled = false;170 DealerPlay();171 }172 173 } // end method hitButton_Click174 175 // deal two cards each to dealer and player176 protected void dealButton_Click( 177 object sender, System.EventArgs e )178 {179 string card;180 181 // clear card images182 foreach ( PictureBox cardImage in cardBoxes )183 cardImage.Image = null;184 185 // clear status from previous game186 statusLabel.Text = "";187 188 // shuffle cards189 dealer.Shuffle();190 191 // deal two cards to player192 playersCards = dealer.DealCard();193 DisplayCard( 11, playersCards );194 card = dealer.DealCard();195 DisplayCard( 12, card );196 playersCards += "\t" + card;197

If the player has 21, the player cannot take more cards; dealer’s turn

Clear the PictureBoxes containing the card images

Shuffle the cards by calling BlackjackService method Shuffle

Deal two cards to player

Page 38: 2002 Prentice Hall. All rights reserved. 1 Chapter 21 – ASP.NET and Web Services Outline 21.1 Introduction 21.2 Web Services 21.3 Simple Object Access

2002 Prentice Hall.All rights reserved.

Outline38

Blackjack.cs

198 // deal two cards to dealer, only display face199 // of first card200 dealersCards = dealer.DealCard() ;201 DisplayCard( 0, dealersCards );202 card = dealer.DealCard();203 DisplayCard( 1, "" );204 dealersCards += "\t" + card;205 206 stayButton.Enabled = true;207 hitButton.Enabled = true;208 dealButton.Enabled = false;209 210 int dealersTotal = dealer.CountCards( dealersCards );211 int playersTotal = dealer.CountCards( playersCards );212 213 // if hands equal 21, it is a push214 if ( dealersTotal == playersTotal && 215 dealersTotal == 21 )216 GameOver( GameStatus.PUSH );217 218 // if player has 21 player wins with blackjack219 else if ( playersTotal == 21 )220 GameOver( GameStatus.BLACKJACK );221 222 // if dealer has 21, dealer wins223 else if ( dealersTotal == 21 )224 GameOver( GameStatus.LOSE );225 226 dealerCard = 2;227 playerCard = 13; 228 229 } // end method dealButton_Click230

Deal two cards to dealer but only display the face of the first one

If both hands equal 21, it is a push

If only the player has 21, the player wins

If only the dealer has 21, the dealer wins

Page 39: 2002 Prentice Hall. All rights reserved. 1 Chapter 21 – ASP.NET and Web Services Outline 21.1 Introduction 21.2 Web Services 21.3 Simple Object Access

2002 Prentice Hall.All rights reserved.

Outline39

Blackjack.cs

231 // displays card represented by cardValue in232 // PictureBox with number card233 public void DisplayCard( int card, string cardValue )234 {235 // retrieve appropriate PictureBox from ArrayList236 PictureBox displayBox = ( PictureBox ) cardBoxes[ card ];237 238 // if string representing card is empty,239 // set displayBox to display back of card240 if ( cardValue == "" )241 { 242 displayBox.Image = 243 Image.FromFile( "blackjack_images\\cardback.png" );244 return;245 }246 247 // retrieve face value of card from cardValue248 int faceNumber = Int32.Parse( cardValue.Substring( 0,249 cardValue.IndexOf( " " ) ) );250 251 string face = faceNumber.ToString();252 253 // retrieve the suit of the card from cardValue254 string suit = cardValue.Substring( 255 cardValue.IndexOf( " " ) + 1 );256 257 char suitLetter;258 259 // determine if suit is other than clubs260 switch ( Convert.ToInt32( suit ) )261 {262 // suit is clubs263 case 0:264 suitLetter = 'c';265 break;

If cardValue is an empty string, display the back of the card image

Retrieve face and suit of card from cardValue

Page 40: 2002 Prentice Hall. All rights reserved. 1 Chapter 21 – ASP.NET and Web Services Outline 21.1 Introduction 21.2 Web Services 21.3 Simple Object Access

2002 Prentice Hall.All rights reserved.

Outline40

Blackjack.cs

266 267 // suit is diamonds268 case 1: 269 suitLetter = 'd';270 break;271 272 // suit is hearts273 case 2: 274 suitLetter = 'h';275 break;276 277 // else suit is spades278 default: 279 suitLetter = 's';280 break;281 }282 283 // set displayBox to display appropriate image284 displayBox.Image = Image.FromFile( 285 "blackjack_images\\" + face + suitLetter + ".png" );286 287 } // end method DisplayCard288 289 // displays all player cards and shows 290 // appropriate game status message291 public void GameOver( GameStatus winner )292 {293 char[] tab = { '\t' }; 294 string[] cards = dealersCards.Split( tab );295 296 for ( int i = 0; i < cards.Length; i++ )297 DisplayCard( i, cards[ i ] );298

Display all of dealer’s cards

Page 41: 2002 Prentice Hall. All rights reserved. 1 Chapter 21 – ASP.NET and Web Services Outline 21.1 Introduction 21.2 Web Services 21.3 Simple Object Access

2002 Prentice Hall.All rights reserved.

Outline41

Blackjack.cs

299 // push300 if ( winner == GameStatus.PUSH )301 statusLabel.Text = "It's a tie!";302 303 // player loses304 else if ( winner == GameStatus.LOSE )305 statusLabel.Text = "You Lose Try Again!";306 307 // player wins308 else if ( winner == GameStatus.WIN )309 statusLabel.Text = "You Win!";310 311 // player has won with blackjack312 else313 statusLabel.Text = "BlackJack!";314 315 stayButton.Enabled = false;316 hitButton.Enabled = false;317 dealButton.Enabled = true;318 319 } // end method GameOver320 321 } // end class Blackjack

Display appropriate message in statusLabel

Page 42: 2002 Prentice Hall. All rights reserved. 1 Chapter 21 – ASP.NET and Web Services Outline 21.1 Introduction 21.2 Web Services 21.3 Simple Object Access

2002 Prentice Hall.All rights reserved.

Outline42

Blackjack.csProgram Output

Page 43: 2002 Prentice Hall. All rights reserved. 1 Chapter 21 – ASP.NET and Web Services Outline 21.1 Introduction 21.2 Web Services 21.3 Simple Object Access

2002 Prentice Hall.All rights reserved.

Outline43

Blackjack.csProgram Output

Page 44: 2002 Prentice Hall. All rights reserved. 1 Chapter 21 – ASP.NET and Web Services Outline 21.1 Introduction 21.2 Web Services 21.3 Simple Object Access

2002 Prentice Hall.All rights reserved.

Outline44

Blackjack.csProgram Output

Page 45: 2002 Prentice Hall. All rights reserved. 1 Chapter 21 – ASP.NET and Web Services Outline 21.1 Introduction 21.2 Web Services 21.3 Simple Object Access

2002 Prentice Hall.All rights reserved.

Outline45

Reservation.asmx.cs

1 // Fig. 21.16: Reservation.asmx.cs2 // 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 AirlineReservation12 { 13 // performs reservation of a seat14 [ WebService( Namespace = "http://www.deitel.com/csphtp1/ch21/",15 Description = "Service that enables a user to " +16 "reserve a seat on a plane." ) ]17 public class Reservation : System.Web.Services.WebService18 {19 private System.Data.OleDb.OleDbCommand 20 oleDbSelectCommand1;21 private System.Data.OleDb.OleDbCommand 22 oleDbInsertCommand1;23 private System.Data.OleDb.OleDbCommand 24 oleDbUpdateCommand1;25 private System.Data.OleDb.OleDbCommand 26 oleDbDeleteCommand1;27 private System.Data.OleDb.OleDbConnection 28 oleDbConnection1;29 private System.Data.OleDb.OleDbDataAdapter 30 oleDbDataAdapter1;31 32 // Visual Studio .NET generated code33

Page 46: 2002 Prentice Hall. All rights reserved. 1 Chapter 21 – ASP.NET and Web Services Outline 21.1 Introduction 21.2 Web Services 21.3 Simple Object Access

2002 Prentice Hall.All rights reserved.

Outline46

Reservation.asmx.cs

34 // checks database to determine whether35 // matching seat is available36 [ WebMethod ( Description = "Method to reserve seat." ) ]37 public bool Reserve( string seatType, string classType )38 {39 OleDbDataReader dataReader;40 41 // try database connection42 try 43 {44 // open database connection45 oleDbConnection1.Open();46 47 // set and execute SQL query48 oleDbDataAdapter1.SelectCommand.CommandText =49 "SELECT Number FROM Seats WHERE Type = '" +50 seatType + "' AND Class = '" + classType + 51 "' AND Taken = '0'" ;52 dataReader = 53 oleDbDataAdapter1.SelectCommand.ExecuteReader();54 55 // if there were results, seat is available56 if ( dataReader.Read() )57 {58 string seatNumber = dataReader.GetString( 0 );59 60 dataReader.Close();61

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)

Page 47: 2002 Prentice Hall. All rights reserved. 1 Chapter 21 – ASP.NET and Web Services Outline 21.1 Introduction 21.2 Web Services 21.3 Simple Object Access

2002 Prentice Hall.All rights reserved.

Outline47

Reservation.asmx.cs

62 // update first available seat to be taken63 oleDbDataAdapter1.UpdateCommand.CommandText =64 "Update Seats Set Taken = '1' WHERE Number = '"65 + seatNumber + "'";66 oleDbDataAdapter1.UpdateCommand.ExecuteNonQuery();67 68 return true;69 70 } // end if71 dataReader.Close();72 } 73 catch ( OleDbException ) // if connection problem74 {75 return false;76 }77 finally 78 {79 oleDbConnection1.Close();80 }81 82 // no seat was reserved83 return false;84 85 } // end method Reserve86 87 } // end class Reservation88 89 } // end namespace AirlineReservation

Set a query that updates the seat numbered seatNumber to be taken. Execute query.

Page 48: 2002 Prentice Hall. All rights reserved. 1 Chapter 21 – ASP.NET and Web Services Outline 21.1 Introduction 21.2 Web Services 21.3 Simple Object Access

2002 Prentice Hall. All rights reserved.

48

21.6 Using Web Forms and Web Services

Fig. 21.17 Airline Web Service in design view.

Page 49: 2002 Prentice Hall. All rights reserved. 1 Chapter 21 – ASP.NET and Web Services Outline 21.1 Introduction 21.2 Web Services 21.3 Simple Object Access

2002 Prentice Hall.All rights reserved.

Outline49

TicketReservation.aspx

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" 6 AutoEventWireup="false" 7 Inherits="MakeReservation.TicketReservation" %>8 9 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >10 <HTML>11 <HEAD>12 <meta name="GENERATOR" Content="Microsoft Visual Studio 7.0">13 <meta name="CODE_LANGUAGE" Content="C#">14 <meta name="vs_defaultClientScript" 15 content="JavaScript (ECMAScript)">16 <meta name="vs_targetSchema" 17 content="http://schemas.microsoft.com/intellisense/ie5">18 </HEAD>19 <body MS_POSITIONING="GridLayout">20 21 <form id="MakeReservation" method="post" runat="server">22 23 <asp:DropDownList id="seatList" style="Z-INDEX: 101; 24 LEFT: 16px; POSITION: absolute; TOP: 43px" 25 runat="server" Width="105px" Height="22px">26 27 <asp:ListItem Value="Aisle">Aisle</asp:ListItem>28 <asp:ListItem Value="Middle">Middle</asp:ListItem>29 <asp:ListItem Value="Window">Window</asp:ListItem>30 31 </asp:DropDownList>32

Page 50: 2002 Prentice Hall. All rights reserved. 1 Chapter 21 – ASP.NET and Web Services Outline 21.1 Introduction 21.2 Web Services 21.3 Simple Object Access

2002 Prentice Hall.All rights reserved.

Outline50

TicketReservation.aspx

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

Page 51: 2002 Prentice Hall. All rights reserved. 1 Chapter 21 – ASP.NET and Web Services Outline 21.1 Introduction 21.2 Web Services 21.3 Simple Object Access

2002 Prentice Hall.All rights reserved.

Outline51

TicketReservation.aspx.cs

1 // Fig. 21.19: TicketReservation.aspx.cs2 // 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 MakeReservation16 {17 // allows visitors to select seat type to reserve, and18 // then make reservation19 public class TicketReservation : System.Web.UI.Page20 {21 protected System.Web.UI.WebControls.DropDownList 22 seatList;23 protected System.Web.UI.WebControls.DropDownList 24 classList;25 26 protected System.Web.UI.WebControls.Button 27 reserveButton;28 protected System.Web.UI.WebControls.Label Label1;29 30 private localhost.Reservation agent =31 new localhost.Reservation();32

Page 52: 2002 Prentice Hall. All rights reserved. 1 Chapter 21 – ASP.NET and Web Services Outline 21.1 Introduction 21.2 Web Services 21.3 Simple Object Access

2002 Prentice Hall.All rights reserved.

Outline52

TicketReservation.aspx.cs

33 private void Page_Load( 34 object sender, System.EventArgs e )35 {36 if ( IsPostBack )37 {38 seatList.Visible = false;39 classList.Visible = false;40 reserveButton.Visible = false;41 Label1.Visible = false;42 }43 }44 45 // Visual Studio .NET generated code46 47 // calls Web Service to try to reserve specified seat48 public void reserveButton_Click ( 49 object sender, System.EventArgs e )50 { 51 // if Web-service method returned true, signal success52 if ( agent.Reserve( seatList.SelectedItem.Text, 53 classList.SelectedItem.Text ) )54 Response.Write( "Your reservation has been made." 55 + " Thank you." );56 57 // Web-service method returned false, so signal failure58 else59 Response.Write( "This seat is not available, " +60 "please hit the back button on your browser " +61 "and try again." );62 63 } // end method reserveButton_Click64 65 } // end class TicketReservation66 67 } // end namespace MakeReservation

Page 53: 2002 Prentice Hall. All rights reserved. 1 Chapter 21 – ASP.NET and Web Services Outline 21.1 Introduction 21.2 Web Services 21.3 Simple Object Access

2002 Prentice Hall.All rights reserved.

Outline53

TicketReservation.aspx.csProgram Output

Page 54: 2002 Prentice Hall. All rights reserved. 1 Chapter 21 – ASP.NET and Web Services Outline 21.1 Introduction 21.2 Web Services 21.3 Simple Object Access

2002 Prentice Hall.All rights reserved.

Outline54

TicketReservation.aspx.csProgram Output

Page 55: 2002 Prentice Hall. All rights reserved. 1 Chapter 21 – ASP.NET and Web Services Outline 21.1 Introduction 21.2 Web Services 21.3 Simple Object Access

2002 Prentice Hall.All rights reserved.

Outline55

TemperatureServer.asmx.cs

1 // Fig. 21.20: TemperatureServer.asmx.cs2 // 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 TemperatureWebService16 {17 [ WebService( Namespace = "http://www.deitel.com/csphtp1/ch21/",18 Description = "A Web service that provides information " +19 "from the National Weather Service." ) ]20 public class TemperatureServer : 21 System.Web.Services.WebService22 {23 // Visual Studio .NET generated code24 25 [ WebMethod( EnableSession = true, Description =26 "Method to read information from the weather service." ) ]27 public void UpdateWeatherConditions()28 {29 // create WebClient to get access to Web page30 WebClient myClient = new WebClient(); 31 ArrayList cityList = new ArrayList();32

Page 56: 2002 Prentice Hall. All rights reserved. 1 Chapter 21 – ASP.NET and Web Services Outline 21.1 Introduction 21.2 Web Services 21.3 Simple Object Access

2002 Prentice Hall.All rights reserved.

Outline56

TemperatureServer.asmx.cs

33 // get StreamReader for response so we can read page34 StreamReader input = new StreamReader(35 myClient.OpenRead(36 "http://iwin.nws.noaa.gov/iwin/us/" +37 "traveler.html" ) );38 39 string separator = "TAV12";40 41 // locate first horizontal line on Web page42 while ( !input.ReadLine().StartsWith( 43 separator ) ) ; // do nothing44 45 // day format and night format46 string dayFormat =47 "CITY WEA HI/LO WEA " + 48 "HI/LO";49 string nightFormat =50 "CITY WEA LO/HI WEA " + 51 "LO/HI";52 string inputLine = "";53 54 // locate header that begins weather information55 do56 {57 inputLine = input.ReadLine();58 } while ( !inputLine.Equals( dayFormat ) && 59 !inputLine.Equals( nightFormat ) );60 61 // get first city's data62 inputLine = input.ReadLine(); 63

Page 57: 2002 Prentice Hall. All rights reserved. 1 Chapter 21 – ASP.NET and Web Services Outline 21.1 Introduction 21.2 Web Services 21.3 Simple Object Access

2002 Prentice Hall.All rights reserved.

Outline57

TemperatureServer.asmx.cs

64 while ( inputLine.Length > 28 )65 {66 // create CityWeather object for city67 CityWeather weather = new CityWeather(68 inputLine.Substring( 0, 16 ),69 inputLine.Substring( 16, 7 ),70 inputLine.Substring( 23, 7 ) );71 72 // add to List73 cityList.Add( weather ); 74 75 // get next city's data76 inputLine = input.ReadLine(); 77 }78 79 // close connection to NWS server80 input.Close(); 81 82 // add city list to user session83 Session.Add( "cityList", cityList );84 85 } // end UpdateWeatherConditions86 87 // gets all city names88 [ WebMethod( EnableSession = true, Description = 89 "Method to retrieve a list of cities." ) ]90 public string[] Cities()91 {92 ArrayList cityList = ( ArrayList ) Session[ "cityList" ];93 string[] cities= new string[ cityList.Count ];94

Page 58: 2002 Prentice Hall. All rights reserved. 1 Chapter 21 – ASP.NET and Web Services Outline 21.1 Introduction 21.2 Web Services 21.3 Simple Object Access

2002 Prentice Hall.All rights reserved.

Outline58

TemperatureServer.asmx.cs

95 // retrieve names for cities96 for ( int i = 0; i < cityList.Count; i++ )97 {98 CityWeather weather = ( CityWeather ) cityList[ i ];99 100 cities[ i ] = weather.CityName;101 }102 103 return cities;104 105 } // end method Cities106 107 // gets all city descriptions108 [ WebMethod( EnableSession = true, Description = "Method" +109 " to retrieve weather descriptions for a " +110 "list of cities." )]111 public string[] Descriptions()112 {113 ArrayList cityList = ( ArrayList ) Session[ "cityList" ];114 string[] descriptions= new string[ cityList.Count ];115 116 // retrieve weather descriptions for all cities117 for ( int i = 0; i < cityList.Count; i++ )118 {119 CityWeather weather = ( CityWeather )cityList[ i ];120 121 descriptions[ i ] = weather.Description;122 } 123 124 return descriptions;125 126 } // end method Descriptions127

Page 59: 2002 Prentice Hall. All rights reserved. 1 Chapter 21 – ASP.NET and Web Services Outline 21.1 Introduction 21.2 Web Services 21.3 Simple Object Access

2002 Prentice Hall.All rights reserved.

Outline59

TemperatureServer.asmx.cs

128 // obtains each city temperature129 [ WebMethod( EnableSession = true, Description = "Method " +130 "to retrieve the temperature for a list of cities." ) ]131 public string[] Temperatures()132 {133 ArrayList cityList = ( ArrayList ) Session[ "cityList" ];134 string[] temperatures= new string[ cityList.Count ];135 136 // retrieve temperatures for all cities137 for ( int i = 0; i < cityList.Count; i++ )138 {139 CityWeather weather = ( CityWeather )cityList[ i ];140 temperatures[ i ] = weather.Temperature;141 }142 143 return temperatures;144 145 } // end method Temperatures146 147 } // end class TemperatureServer148 149 } // end namespace TemperatureWebService

Page 60: 2002 Prentice Hall. All rights reserved. 1 Chapter 21 – ASP.NET and Web Services Outline 21.1 Introduction 21.2 Web Services 21.3 Simple Object Access

2002 Prentice Hall.All rights reserved.

Outline60

CityWeather.cs

1 // Fig. 21.21: CityWeather.cs2 // Class representing the weather information for one city.3 4 using System;5 6 namespace TemperatureWebService7 {8 public class CityWeather9 {10 private string cityName;11 private string temperature;12 private string description;13 14 public CityWeather(15 string city, string information, string degrees )16 {17 cityName = city;18 description = information;19 temperature = degrees;20 }21 22 // city name23 public string CityName24 {25 get26 {27 return cityName;28 }29 }30

Page 61: 2002 Prentice Hall. All rights reserved. 1 Chapter 21 – ASP.NET and Web Services Outline 21.1 Introduction 21.2 Web Services 21.3 Simple Object Access

2002 Prentice Hall.All rights reserved.

Outline61

CityWeather.cs

31 // city temperature32 public string Temperature33 {34 get35 {36 return temperature;37 }38 }39 40 // forecast description41 public string Description42 {43 get44 {45 return description;46 }47 }48 49 } // end class CityWeather50 } // end namespace TemperatureWebService

Page 62: 2002 Prentice Hall. All rights reserved. 1 Chapter 21 – ASP.NET and Web Services Outline 21.1 Introduction 21.2 Web Services 21.3 Simple Object Access

2002 Prentice Hall.All rights reserved.

Outline62

Client.cs

1 // Fig. 21.22: Client.cs2 // Class that displays weather information that it receives3 // 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 TemperatureClient13 {14 public class Client : System.Windows.Forms.Form15 {16 private System.Windows.Forms.Label label1;17 private System.Windows.Forms.Label label2;18 private System.Windows.Forms.Label label3;19 private System.Windows.Forms.Label label4;20 private System.Windows.Forms.Label label5;21 private System.Windows.Forms.Label label6;22 private System.Windows.Forms.Label label7;23 private System.Windows.Forms.Label label8;24 private System.Windows.Forms.Label label9;25 private System.Windows.Forms.Label label10;26 private System.Windows.Forms.Label label11;27 private System.Windows.Forms.Label label12;28 private System.Windows.Forms.Label label13;29 private System.Windows.Forms.Label label14;30 private System.Windows.Forms.Label label15;31 private System.Windows.Forms.Label label16;32 private System.Windows.Forms.Label label17;33 private System.Windows.Forms.Label label18;34 private System.Windows.Forms.Label label19;35 private System.Windows.Forms.Label label20;

Page 63: 2002 Prentice Hall. All rights reserved. 1 Chapter 21 – ASP.NET and Web Services Outline 21.1 Introduction 21.2 Web Services 21.3 Simple Object Access

2002 Prentice Hall.All rights reserved.

Outline63

Client.cs

36 private System.Windows.Forms.Label label21;37 private System.Windows.Forms.Label label22;38 private System.Windows.Forms.Label label23;39 private System.Windows.Forms.Label label24;40 private System.Windows.Forms.Label label25;41 private System.Windows.Forms.Label label26;42 private System.Windows.Forms.Label label27;43 private System.Windows.Forms.Label label28;44 private System.Windows.Forms.Label label29;45 private System.Windows.Forms.Label label30;46 private System.Windows.Forms.Label label31;47 private System.Windows.Forms.Label label32;48 private System.Windows.Forms.Label label33;49 private System.Windows.Forms.Label label34;50 private System.Windows.Forms.Label label36;51 private System.Windows.Forms.Label label35;52 53 private System.ComponentModel.Container components = 54 null;55 56 public Client()57 {58 InitializeComponent();59 60 localhost.TemperatureServer client = 61 new localhost.TemperatureServer();62 client.CookieContainer = new CookieContainer();63 client.UpdateWeatherConditions();64 65 string[] cities = client.Cities();66 string[] descriptions = client.Descriptions();67 string[] temperatures = client.Temperatures();68 69 label35.BackgroundImage = new Bitmap( 70 "images/header.png" );

Page 64: 2002 Prentice Hall. All rights reserved. 1 Chapter 21 – ASP.NET and Web Services Outline 21.1 Introduction 21.2 Web Services 21.3 Simple Object Access

2002 Prentice Hall.All rights reserved.

Outline64

Client.cs

71 label36.BackgroundImage = new Bitmap( 72 "images/header.png" );73 74 // create Hashtable and populate it with every label75 Hashtable cityLabels = new Hashtable();76 cityLabels.Add( 1, label1 );77 cityLabels.Add( 2, label2 );78 cityLabels.Add( 3, label3 );79 cityLabels.Add( 4, label4 );80 cityLabels.Add( 5, label5 );81 cityLabels.Add( 6, label6 );82 cityLabels.Add( 7, label7 );83 cityLabels.Add( 8, label8 );84 cityLabels.Add( 9, label9 );85 cityLabels.Add( 10, label10 );86 cityLabels.Add( 11, label11 );87 cityLabels.Add( 12, label12 );88 cityLabels.Add( 13, label13 );89 cityLabels.Add( 14, label14 );90 cityLabels.Add( 15, label15 );91 cityLabels.Add( 16, label16 );92 cityLabels.Add( 17, label17 );93 cityLabels.Add( 18, label18 );94 cityLabels.Add( 19, label19 );95 cityLabels.Add( 20, label20 );96 cityLabels.Add( 21, label21 );97 cityLabels.Add( 22, label22 );98 cityLabels.Add( 23, label23 );99 cityLabels.Add( 24, label24 );100 cityLabels.Add( 25, label25 );101 cityLabels.Add( 26, label26 );102 cityLabels.Add( 27, label27 );103 cityLabels.Add( 28, label28 );104 cityLabels.Add( 29, label29 );105 cityLabels.Add( 30, label30 );

Page 65: 2002 Prentice Hall. All rights reserved. 1 Chapter 21 – ASP.NET and Web Services Outline 21.1 Introduction 21.2 Web Services 21.3 Simple Object Access

2002 Prentice Hall.All rights reserved.

Outline65

Client.cs

106 cityLabels.Add( 31, label31 );107 cityLabels.Add( 32, label32 );108 cityLabels.Add( 33, label33 );109 cityLabels.Add( 34, label34 );110 111 // create Hashtable and populate with 112 // all weather conditions113 Hashtable weather = new Hashtable();114 weather.Add( "SUNNY", "sunny" );115 weather.Add( "PTCLDY", "pcloudy" );116 weather.Add( "CLOUDY", "mcloudy" );117 weather.Add( "MOCLDY", "mcloudy" );118 weather.Add( "TSTRMS", "rain" );119 weather.Add( "RAIN", "rain" );120 weather.Add( "SNOW", "snow" );121 weather.Add( "VRYHOT", "vryhot" );122 weather.Add( "FAIR", "fair" );123 weather.Add( "RNSNOW", "rnsnow" );124 weather.Add( "SHWRS", "showers" );125 weather.Add( "WINDY", "windy" );126 weather.Add( "NOINFO", "noinfo" );127 weather.Add( "MISG", "noinfo" );128 weather.Add( "DRZL", "rain" );129 weather.Add( "HAZE", "noinfo" );130 weather.Add( "SMOKE", "mcloudy" );131 132 Bitmap background = new Bitmap( "images/back.png" );133 Font font = new Font( "Courier New", 8, 134 FontStyle.Bold );135 136 // for every city137 for ( int i = 0; i < cities.Length; i++ )138 {139 // use Hashtable cityLabels to find the next Label140 Label currentCity = ( Label )cityLabels[ i + 1 ];

Page 66: 2002 Prentice Hall. All rights reserved. 1 Chapter 21 – ASP.NET and Web Services Outline 21.1 Introduction 21.2 Web Services 21.3 Simple Object Access

2002 Prentice Hall.All rights reserved.

Outline66

Client.cs

141 142 // set current Label's image to image 143 // corresponding to the city's weather condition - 144 // find correct image name in Hashtable weather145 currentCity.Image = new Bitmap( "images/" + 146 weather[ descriptions[ i ].Trim() ] + ".png" );147 148 // set background image, font and forecolor 149 // of Label150 currentCity.BackgroundImage = background;151 currentCity.Font = font;152 currentCity.ForeColor = Color.White;153 154 // set label's text to city name155 currentCity.Text = "\r\n" + cities[ i ] + " " + 156 temperatures[ i ];157 }158 159 } // end of constructor160 161 // Visual Studio .NET generated code162 163 [STAThread]164 static void Main()165 {166 Application.Run( new Client() );167 }168 169 } // end class Client170 171 } // end namespace TemperatureClient

Page 67: 2002 Prentice Hall. All rights reserved. 1 Chapter 21 – ASP.NET and Web Services Outline 21.1 Introduction 21.2 Web Services 21.3 Simple Object Access

2002 Prentice Hall.All rights reserved.

Outline67

Client.csProgram Output

Page 68: 2002 Prentice Hall. All rights reserved. 1 Chapter 21 – ASP.NET and Web Services Outline 21.1 Introduction 21.2 Web Services 21.3 Simple Object Access

2002 Prentice Hall.All rights reserved.

Outline68

Equation.cs

1 // Fig. 21.23: Equation.cs2 // Class Equation that contains3 // information about an equation.4 5 using System;6 7 public class Equation8 {9 private int left, right, result;10 private string operation;11 12 // required default constructor13 public Equation() : this( 0, 0, "+" )14 {15 }16 17 // constructor for class Equation18 public Equation( int leftValue, int rightValue, 19 string operationType )20 {21 Left = leftValue;22 Right = rightValue;23 Operation = operationType;24 25 switch ( operationType )26 {27 case "+": 28 Result = Left + Right;29 break;30 case "-":31 Result = Left - Right;32 break;

Page 69: 2002 Prentice Hall. All rights reserved. 1 Chapter 21 – ASP.NET and Web Services Outline 21.1 Introduction 21.2 Web Services 21.3 Simple Object Access

2002 Prentice Hall.All rights reserved.

Outline69

Equation.cs

33 case "*": 34 Result = Left * Right;35 break;36 }37 }38 39 public override string ToString()40 { 41 return Left.ToString() + " " + Operation + " " + 42 Right.ToString() + " = " + Result.ToString();43 }44 45 // property returning string representing46 // left-hand side47 public string LeftHandSide48 {49 get50 {51 return Left.ToString() + " " + Operation + " " +52 Right.ToString();53 }54 55 set56 {57 }58 }59 60 // property returning string representing61 // right-hand side62 public string RightHandSide63 {64 get65 {66 return Result.ToString();67 }

Page 70: 2002 Prentice Hall. All rights reserved. 1 Chapter 21 – ASP.NET and Web Services Outline 21.1 Introduction 21.2 Web Services 21.3 Simple Object Access

2002 Prentice Hall.All rights reserved.

Outline70

Equation.cs

68 69 set70 {71 }72 }73 74 // left operand get and set property75 public int Left76 {77 get78 {79 return left;80 }81 82 set83 {84 left = value;85 }86 }87 88 // right operand get and set property89 public int Right90 {91 get92 {93 return right;94 }95 96 set97 {98 right = value;99 }100 }101

Page 71: 2002 Prentice Hall. All rights reserved. 1 Chapter 21 – ASP.NET and Web Services Outline 21.1 Introduction 21.2 Web Services 21.3 Simple Object Access

2002 Prentice Hall.All rights reserved.

Outline71

Equation.cs

102 // get and set property of result of applying103 // operation to left and right operands104 public int Result105 { 106 get107 {108 return result;109 }110 111 set112 {113 result = value;114 }115 }116 117 // get and set property for operation118 public string Operation119 {120 get121 {122 return operation;123 }124 125 set126 {127 operation = value;128 }129 }130 131 } // end class Equation

Page 72: 2002 Prentice Hall. All rights reserved. 1 Chapter 21 – ASP.NET and Web Services Outline 21.1 Introduction 21.2 Web Services 21.3 Simple Object Access

2002 Prentice Hall.All rights reserved.

Outline72

Generator.asmx.cs

1 // Fig. 21.24: Generator.asmx.cs2 // Web Service to generate random equations based on a3 // 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 EquationGenerator14 {15 [ WebService( Namespace = "http://www.deitel.com/csphtp1/ch21",16 Description = "A Web service that generates questions " +17 "based on the specified mathematical operation and " +18 "level of difficulty chosen." ) ]19 public class Generator : System.Web.Services.WebService20 {21 22 // Visual Studio .NET generated code23 24 [ WebMethod ( Description =25 "Method that generates a random equation." ) ]26 public Equation GenerateEquation( string operation, 27 int level )28 {29 // find maximum and minimum number to be used30 int maximum = ( int ) Math.Pow( 10, level ), 31 minimum = ( int ) Math.Pow( 10, level - 1 );32

Page 73: 2002 Prentice Hall. All rights reserved. 1 Chapter 21 – ASP.NET and Web Services Outline 21.1 Introduction 21.2 Web Services 21.3 Simple Object Access

2002 Prentice Hall.All rights reserved.

Outline73

Generator.asmx.cs

33 Random random = new Random();34 35 // create equation consisting of two random numbers36 // between minimum and maximum parameters37 Equation equation = new Equation(38 random.Next( minimum, maximum ), 39 random.Next( minimum, maximum ), operation );40 41 return equation;42 43 } // end method GenerateEquation44 45 } // end class Generator46 47 } // end namespace EquationGenerator

Page 74: 2002 Prentice Hall. All rights reserved. 1 Chapter 21 – ASP.NET and Web Services Outline 21.1 Introduction 21.2 Web Services 21.3 Simple Object Access

2002 Prentice Hall. All rights reserved.

74

21.8 User Defined Types in Web Services

Fig. 21.25 Returning an object from a Web-service method. (Part 1)

Create a subtraction exercise

Make exercise of user skill level 2

Page 75: 2002 Prentice Hall. All rights reserved. 1 Chapter 21 – ASP.NET and Web Services Outline 21.1 Introduction 21.2 Web Services 21.3 Simple Object Access

2002 Prentice Hall. All rights reserved.

75

21.8 User Defined Types in Web Services

Fig. 21.25 Returning an object from a Web-service method. (Part 2)

Page 76: 2002 Prentice Hall. All rights reserved. 1 Chapter 21 – ASP.NET and Web Services Outline 21.1 Introduction 21.2 Web Services 21.3 Simple Object Access

2002 Prentice Hall.All rights reserved.

Outline76

Tutor.cs

1 // Fig. 21.26: Tutor.cs2 // 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 EquationGeneratorClient11 {12 public class Tutor : System.Windows.Forms.Form13 {14 private System.Windows.Forms.Panel panel1;15 private System.Windows.Forms.Panel panel2;16 17 private System.Windows.Forms.Label questionLabel;18 private System.Windows.Forms.TextBox answerTextBox;19 private System.Windows.Forms.Button okButton;20 private System.Windows.Forms.Button generateButton;21 22 private System.Windows.Forms.RadioButton oneRadioButton;23 private System.Windows.Forms.RadioButton twoRadioButton;24 private System.Windows.Forms.RadioButton 25 threeRadioButton;26 private System.Windows.Forms.RadioButton addRadioButton;27 private System.Windows.Forms.RadioButton 28 subtractRadioButton;29 private System.Windows.Forms.RadioButton 30 multiplyRadioButton;31 32 private System.ComponentModel.Container components = 33 null;34 private int level = 1;35

Page 77: 2002 Prentice Hall. All rights reserved. 1 Chapter 21 – ASP.NET and Web Services Outline 21.1 Introduction 21.2 Web Services 21.3 Simple Object Access

2002 Prentice Hall.All rights reserved.

Outline77

Tutor.cs

36 private localhost.Equation equation;37 private localhost.Generator generator = 38 new localhost.Generator();39 private string operation = "+";40 41 // Visual Studio .NET generated code42 43 [STAThread]44 static void Main()45 {46 Application.Run( new Tutor() );47 }48 49 // generates new equation on click event50 protected void generateButton_Click( object sender, 51 System.EventArgs e )52 {53 // generate equation using current operation54 // and level55 equation = generator.GenerateEquation( operation, 56 level );57 58 // display left-hand side of equation59 questionLabel.Text = equation.LeftHandSide;60 61 okButton.Enabled = true;62 answerTextBox.Enabled = true; 63 64 } // end method generateButton_Click65

Page 78: 2002 Prentice Hall. All rights reserved. 1 Chapter 21 – ASP.NET and Web Services Outline 21.1 Introduction 21.2 Web Services 21.3 Simple Object Access

2002 Prentice Hall.All rights reserved.

Outline78

Tutor.cs

66 // check users answer67 protected void okButton_Click( object sender, 68 System.EventArgs e )69 {70 // determine correct result from Equation 71 // object72 int answer = equation.Result;73 74 // get user's answer75 int myAnswer = Int32.Parse( answerTextBox.Text );76 77 // test if user's answer is correct78 if ( answer == myAnswer )79 {80 questionLabel.Text = "";81 answerTextBox.Text = "";82 okButton.Enabled = false;83 MessageBox.Show( "Correct! Good job!" );84 }85 else86 MessageBox.Show( "Incorrect. Try again." );87 88 } // end method okButton_Click89 90 // set the selected operation91 protected void operationRadioButtons_Click( object sender,92 EventArgs e )93 { 94 RadioButton item = ( RadioButton ) sender;95

Page 79: 2002 Prentice Hall. All rights reserved. 1 Chapter 21 – ASP.NET and Web Services Outline 21.1 Introduction 21.2 Web Services 21.3 Simple Object Access

2002 Prentice Hall.All rights reserved.

Outline79

Tutor.cs

96 // set the operation to be the appropriate symbol97 if ( item == addRadioButton )98 operation = "+";99 else if ( item == subtractRadioButton )100 operation = "-";101 else102 operation = "*";103 104 generateButton.Text = "Generate " + item.Text +105 " Example";106 107 } // end method operationRadioButtons_Click108 109 // set the current level110 protected void levelRadioButtons_Click( object sender,111 EventArgs e )112 {113 if ( sender == oneRadioButton )114 level = 1;115 else if ( sender == twoRadioButton )116 level = 2;117 else118 level = 3;119 120 } // end method levelRadioButtons_Click121 122 } // end class Tutor123 124 } // end namespace EquationGeneratorClient

Page 80: 2002 Prentice Hall. All rights reserved. 1 Chapter 21 – ASP.NET and Web Services Outline 21.1 Introduction 21.2 Web Services 21.3 Simple Object Access

2002 Prentice Hall.All rights reserved.

Outline80

Tutor.csProgram Output

Page 81: 2002 Prentice Hall. All rights reserved. 1 Chapter 21 – ASP.NET and Web Services Outline 21.1 Introduction 21.2 Web Services 21.3 Simple Object Access

2002 Prentice Hall.All rights reserved.

Outline81

Tutor.csProgram Output