Top Banner
1 2006 Pearson Education, Inc. All rights rese 2 2 Web Services
115

2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

Dec 19, 2015

Download

Documents

Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

1

2006 Pearson Education, Inc. All rights reserved.

2222

Web Services

Page 2: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

2

2006 Pearson Education, Inc. All rights reserved.

A client is to me a mere unit, a factor in a problem.

— Sir Arthur Conan Doyle

...if the simplest things of nature have a message that you understand, rejoice, for your soul is alive.

— Eleonora Duse

Protocol is everything.— Francoise Giuliani

They also serve who only stand and wait. — John Milton

Page 3: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

3

2006 Pearson Education, Inc. All rights reserved.

OBJECTIVESIn this chapter you will learn: What a Web service is. How to create Web services. The important part that XML and the XML-based

Simple Object Access Protocol play in enabling Web services.

The elements that comprise Web services, such as service descriptions and discovery files.

How to create a client that uses a Web service. How to use Web services with Windows applications

and Web applications. How to use session tracking in Web services to

maintain state information for the client. How to pass user-defined types to a Web service.

Page 4: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

4

2006 Pearson Education, Inc. All rights reserved.

22.1 Introduction

22.2 .NET Web Services Basics

22.2.1 Creating a Web Service in Visual Web Developer

22.2.2 Discovering Web Services

22.2.3 Determining a Web Service’s Functionality

22.2.4 Testing a Web Service’s Methods

22.2.5 Building a Client to Use a Web Service

22.3 Simple Object Access Protocol (SOAP)

22.4 Publishing and Consuming Web Services

22.4.1 Defining the HugeInteger Web Service

22.4.2 Building a Web Service in Visual Web Developer

22.4.3 Deploying the HugeInteger Web Service

Page 5: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

5

2006 Pearson Education, Inc. All rights reserved.

22.4.4 Creating a Client to Consume the HugeInteger Web Service

22.4.5  Consuming the HugeInteger Web Service

22.5 Session Tracking in Web Services

22.5.1 Creating a Blackjack Web Service

22.5.2 Consuming the Blackjack Web Service

22.6 Using Web Forms and Web Services

22.6.1 Adding Data Components to a Web Service

22.6.2 Creating a Web Form to Interact with the Airline Reservation Web Service

22.7 User-Defined Types in Web Services

22.8  Wrap-Up

22.9 Web Resources

Page 6: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

6

2006 Pearson Education, Inc. All rights reserved.

22.1 Introduction

• Web Services- A class that allows its methods to be called by methods on other

machines via common data formats and protocol • Ex: HTTP and XML

- The over-the-network method calls are commonly implemented through the Simple Object Access Protocol (SOAP)

• An XML-based protocol describes how to mark up requests and responses so that they can be transferred via protocols

- Applications represent and transmit data in a standardized XML-based format using SOAP

- Visual Web Developer and the .NET Framework provide a simple, user-friendly way to create Web services

Page 7: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

7

2006 Pearson Education, Inc. All rights reserved.

22.2 .NET Web Services Basics

• Basics- Remote machine

• The machine on which the Web service resides

- A Web service is typically implemented as a class

- A compiled version of the Web service class is not placed in the current application’s directory

- Requests to and responses from Web services created with Visual Web Developer are typically transmitted via SOAP

• Any client capable of generating and processing SOAP messages can interact with a Web service

- Regardless of the language in which the Web service is written

- Web services and SOAP are platform and language independent

Page 8: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

8

2006 Pearson Education, Inc. All rights reserved.

Performance Tip 22.1

Web services are not the best solution for certain performance-intensive applications, because applications that invoke Web services experience network delays. Also, data transfers are typically larger because data is transmitted in text-based XML formats.

Page 9: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

9

2006 Pearson Education, Inc. All rights reserved.

22.2.1 Creating a Web Service in Visual Web Developer• Creating Web Services

- Create a project of type ASP.NET Web Service. • Visual Web Developer then generates the following:

- Files to contain the Web service code • Implements the Web service

- An ASMX file • Provides access to the Web service

- A DISCO file • Potential clients use to discover the Web service

- Methods in a Web service are invoked through a Remote Procedure Call (RPC)

• These methods are marked with the WebMethod attribute- Makes the method accessible to other classes through RPCs

• Known as exposing

Page 10: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

10

2006 Pearson Education, Inc. All rights reserved.

Fig. 22.1 | Web service components.

Page 11: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

11

2006 Pearson Education, Inc. All rights reserved.

22.2.2 Discovering Web Services• Discovery of Web services (DISCO)

- Microsoft-specific technology used to locate Web services on a server- Four types of DISCO files facilitate the discovery process:- .disco files

• XML markup that describes for clients the location of Web services• Accessed via a Web service’s ASMX page• Contains references only to files in the current Web service

- .vsdisco files• XML markup that describes the locations of Web services is generated

dynamically, then returned to the client• Does not store the markup generated in response to a request• Contain only a small amount of data and provide up-to-date information

about a server’s available Web services• Generate more overhead than .disco files do

- A search must be performed every time a .vsdisco file is accessed

- .discomap files • The resulting data that is returned from accessing a .disco file

- .map files

Page 12: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

12

2006 Pearson Education, Inc. All rights reserved.

22.2.3 Determining a Web Service’s Functionality

• Web Service’s Functionality- Web services normally contain a service description

• An XML document that conforms to Web Service Description Language (WSDL)

- An XML vocabulary that defines the methods a Web service

- Specifies lower-level information that clients might need

Page 13: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

13

2006 Pearson Education, Inc. All rights reserved.

22.2.3 Determining a Web Service’s Functionality (Cont.)

• ASMX File- Generated by the Visual Web Developer when a Web service is constructed- Presents Web method descriptions and links to test pages

• Allow users to execute sample calls to these methods- Specifies the Web service’s :

• Implementation class• Optional code-behind file

- Where the Web service is defined • The assemblies

- Referenced by the Web service- Accessed when the Web server receives a request for the Web service

• Invokes the Web service implementation- For more technical information about the Web service, access the WSDL

file • ASP.NET generates WSDL information dynamically

- Ensures that clients receive the most current information about the Web service

Page 14: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

14

2006 Pearson Education, Inc. All rights reserved.

Fig. 22.2 | ASMX file rendered in a Web browser.

Link to the service description

Links to the Web service’s methods

Page 15: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

15

2006 Pearson Education, Inc. All rights reserved.

22.2.4 Testing a Web Service’s Methods

• SOAP and HTTP POST- Two options for sending and receiving messages in Web

services- Web service’s wire format or wire protocol

• The protocol that transmits request-and-response messages• SOAP is the more commonly used wire format

- SOAP messages can be sent using several transport protocols

- HTTP POST must use HTTP

- When you test a Web service via an ASMX page, the ASMX page uses HTTP POST to test the Web service methods

Page 16: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

16

2006 Pearson Education, Inc. All rights reserved.

Fig. 22.3 | Service description for our HugeInteger Web service.

Page 17: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

17

2006 Pearson Education, Inc. All rights reserved.

Fig. 22.4 | Invoking a Web method from a Web browser.

Page 18: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

18

2006 Pearson Education, Inc. All rights reserved.

Fig. 22.5 | Results of invoking a Web method from a Web browser.

Page 19: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

19

2006 Pearson Education, Inc. All rights reserved.

Error-Prevention Tip 22.1

Using the ASMX page of a Web service to test and debug methods can help you make the Web service more reliable and robust.

Page 20: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

20

2006 Pearson Education, Inc. All rights reserved.

22.2.5 Building a Client to Use a Web Service• Client Using a Web Service

- To consume a Web service, add a Web reference to the client• Adds files that allow the client to access the Web service

- Visual C# 2005 accesses the Web service’s WSDL information and copies it into a WSDL file that is stored in the client project’s Web References folder

• Visual C# 2005 provides an Update Web Reference option • The WSDL information is used to create a proxy class

- Handles all the “plumbing” required for Web method calls • When the client application calls a Web method, it actually calls a method in the

proxy class- This method has the same name and parameters as the Web method that

is being called• Formats the call to be sent as a request in a SOAP message

- The Web service receives this request as a SOAP message• Executes the method call and sends back the result as another SOAP

message- The proxy class deserializes the SOAP message containing the response

and returns the results of the Web method that was called

Page 21: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

21

2006 Pearson Education, Inc. All rights reserved.

Fig. 22.6 | .NET Web service client after a Web reference has been added.

Page 22: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

22

2006 Pearson Education, Inc. All rights reserved.

22.3 Simple Object Access Protocol (SOAP)• SOAP

- Each request and response is packaged in a SOAP message• XML message contains information that is required to process the message

- The wire format used to transmit requests and responses must support all types passed between the applications

- The request and all relevant information are packaged in a SOAP message and sent to the server on which the Web service resides

- The Web service processes the contents which specify the method that the client wishes to execute and any arguments the client is passing to that method

• Known as parsing a SOAP message

- The proper method is then called with the specified arguments and the response is sent back to the client in another SOAP message

- The client parses the response to retrieve the result of the method call

Page 23: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

23

2006 Pearson Education, Inc. All rights reserved.

Fig. 22.7 | Interaction between a Web service client and a Web service.

Page 24: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

24

2006 Pearson Education, Inc. All rights reserved.

1 POST /HugeInteger/HugeInteger.asmx HTTP/1.1

2 Host: localhost

3 Content-Type: text/xml; charset=utf-8

4 Content-Length: length

5 SOAPAction: "http://www.deitel.com/Bigger"

6

7 <?xml version="1.0" encoding="utf-8"?>

8

9 <soap:Envelope

10 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">

16 <first>string</first>

17 <second>string</second>

18 </Bigger>

19 </soap:Body>

20 </soap:Envelope>

Outline

HugeInteger.asmx

Placeholders

Page 25: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

25

2006 Pearson Education, Inc. All rights reserved.

22.4 Publishing and Consuming Web Services

• Terms- Publishing

• Creating a Web services

- Consuming• Using a Web services

• Visual C# 2005 and Visual Web Developer create proxy classes for you

Page 26: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

26

2006 Pearson Education, Inc. All rights reserved.

22.4.1 Defining the HugeInteger Web Service

•WebService attribute - Allows you to specify the Web service’s namespace and

description• Namespace property

- The namespace that the Web service uses• Description property

- Describe the Web service’s purpose- ConformsTo property

• Instructs Visual Web Developer to perform its “behind-the-scenes” work in conformance with to a certain guideline

- By default, each new Web service class created in Visual Web Developer inherits from class System.Web.Services.WebService

Page 27: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

27

2006 Pearson Education, Inc. All rights reserved.

22.4.1 Defining the HugeInteger Web Service (Cont.)

•WebMethod attribute - Exposes a method so it can be called remotely

- When this attribute is absent, the method is not accessible to the clients

Page 28: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

28

2006 Pearson Education, Inc. All rights reserved.

1 // Fig. 22.9: HugeInteger.cs

2 // HugeInteger Web service performs operations on large integers.

3 using System;

4 using System.Web;

5 using System.Web.Services;

6 using System.Web.Services.Protocols;

7

8 [ WebService( Namespace = "http://www.deitel.com/",

9 Description = "A Web service that provides methods for" +

10 " manipulating large integer values" ) ]

11 [ WebServiceBinding( ConformsTo = WsiProfiles.BasicProfile1_1 ) ]

12 public class HugeInteger : System.Web.Services.WebService

13 {

14 private const int MAXIMUM = 100; // maximum number of digits

15 public int[] number; // array representing the huge integer

16

17 // default constructor

18 public HugeInteger()

19 {

20 number = new int[ MAXIMUM ];

21 } // end default constructor

22

23 // indexer that accepts an integer parameter

24 public int this[ int index ]

25 {

26 get

27 {

28 return number[ index ];

29 } // end get

Outline

HugeInteger.cs

(1 of 7)

Namespaces for Web services

Assign the Web service’s namespace and description

Indicates that the Web service conforms to

Basic Profile 1.1

Web service class inherits from System.Web.Services.W

ebService

Enable access to any digit in a

HugeInteger

Page 29: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

29

2006 Pearson Education, Inc. All rights reserved.

30

31 set

32 {

33 number[ index ] = value;

34 } // end set

35 } // end indexer

36

37 // returns string representation of HugeInteger

38 public override string ToString()

39 {

40 string returnString = "";

41

42 foreach ( int i in number )

43 returnString = i + returnString;

44

45 return returnString;

46 } // end method ToString

47

48 // creates HugeInteger based on argument

49 public static HugeInteger FromString( string value )

50 {

51 // create temporary HugeInteger to be returned by the method

52 HugeInteger parsedInteger = new HugeInteger();

53

54 for ( int i = 0 ; i < value.Length; i++ )

55 parsedInteger[ i ] = Int32.Parse(

56 value[ value.Length - i - 1 ].ToString() );

57

58 return parsedInteger;

59 } // end method FromString

Outline

HugeInteger.cs

(2 of 7)

Page 30: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

30

2006 Pearson Education, Inc. All rights reserved.

60

61 // WebMethod that adds integers represented by the string arguments

62 [ WebMethod( Description = "Adds two huge integers." ) ]

63 public string Add( string first, string second )

64 {

65 int carry = 0;

66 HugeInteger operand1 = HugeInteger.FromString( first );

67 HugeInteger operand2 = HugeInteger.FromString( second );

68 HugeInteger result = new HugeInteger(); // stores result of addition

69

70 // perform addition algorithm for each digit

71 for ( int i = 0; i < MAXIMUM; i++ )

72 {

73 // add two digits in same column,

74 // result is their sum plus carry from

75 // previous operation modulo 10

76 result[ i ] =

77 ( operand1[ i ] + operand2[ i ] + carry ) % 10;

78

79 // set carry to remainder of dividing sums of two digits by 10

80 carry = ( operand1[ i ] + operand2[ i ] + carry ) / 10;

81 } // end for

82

83 return result.ToString();

84 } // end method Add

Outline

HugeInteger.cs

(3 of 7)

Allows the method to be called by the client

Page 31: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

31

2006 Pearson Education, Inc. All rights reserved.

85

86 // WebMethod that subtracts integers

87 // represented by the string arguments

88 [ WebMethod( Description = "Subtracts two huge integers." ) ]

89 public string Subtract( string first, string second )

90 {

91 HugeInteger operand1 = HugeInteger.FromString( first );

92 HugeInteger operand2 = HugeInteger.FromString( second );

93 HugeInteger result = new HugeInteger();

94

95 // subtract bottom digit from top digit

96 for ( int i = 0; i < MAXIMUM; i++ )

97 {

98 // if top digit is smaller than bottom digit we need to borrow

99 if ( operand1[ i ] < operand2[ i ] )

100 Borrow( operand1, i );

101

102 // subtract bottom from top

103 result[ i ] = operand1[ i ] - operand2[ i ];

104 } // end for

105

106 return result.ToString();

107 } // end method Subtract

108

109 // borrow 1 from next digit

110 private void Borrow( HugeInteger hugeInteger, int place )

111 {

112 // if no place to borrow from, signal problem

113 if ( place >= MAXIMUM - 1 )

114 throw new ArgumentException();

Outline

HugeInteger.cs

(4 of 7)

Allows the method to be called by the client

Page 32: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

32

2006 Pearson Education, Inc. All rights reserved.

115

116 // otherwise if next digit is zero, borrow from column to left

117 else if ( hugeInteger[ place + 1 ] == 0 )

118 Borrow( hugeInteger, place + 1 );

119

120 // add ten to current place because we borrowed and subtract

121 // one from previous digit--this is the digit we borrowed from

122 hugeInteger[ place ] += 10;

123 hugeInteger[ place + 1 ]--;

124 } // end method Borrow

125

126 // WebMethod that returns true if first integer is bigger than second

127 [ WebMethod( Description = "Determines whether the first integer is " +

128 "larger than the second integer." ) ]

129 public bool Bigger( string first, string second )

130 {

131 char[] zeros = { '0' };

Outline

HugeInteger.cs

(5 of 7)

Allows the method to be called by the client

Page 33: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

33

2006 Pearson Education, Inc. All rights reserved.

132

133 try

134 {

135 // if elimination of all zeros from result

136 // of subtraction is an empty string,

137 // numbers are equal, so return false, otherwise return true

138 if ( Subtract( first, second ).Trim( zeros ) == "" )

139 return false;

140 else

141 return true;

142 } // end try

143 // if ArgumentException occurs,

144 // first number was smaller, so return false

145 catch ( ArgumentException exception )

146 {

147 return false;

148 } // end catch

149 } // end method Bigger

150

151 // WebMethod returns true if first integer is smaller than second

152 [ WebMethod( Description = "Determines whether the first integer " +

153 "is smaller than the second integer." ) ]

154 public bool Smaller( string first, string second )

155 {

156 // if second is bigger than first, then first is smaller than second

157 return Bigger( second, first );

158 } // end method Smaller

Outline

HugeInteger.cs

(6 of 7)

Allows the method to be called by the client

Page 34: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

34

2006 Pearson Education, Inc. All rights reserved.

159

160 // WebMethod that returns true if two integers are equal

161 [ WebMethod( Description = "Determines whether the first integer " +

162 "is equal to the second integer." ) ]

163 public bool EqualTo( string first, string second )

164 {

165 // if either first is bigger than second,

166 // or first is smaller than second, they are not equal

167 if ( Bigger( first, second ) || Smaller( first, second ) )

168 return false;

169 else

170 return true;

171 } // end method EqualTo

172 } // end class HugeInteger

Outline

HugeInteger.cs

(7 of 7)

Allows the method to be called by the client

Page 35: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

35

2006 Pearson Education, Inc. All rights reserved.

Common Programming Error 22.1

Failing to expose a method as a Web method by declaring it with the WebMethod attribute prevents clients of the Web service from accessing the method.

Page 36: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

36

2006 Pearson Education, Inc. All rights reserved.

Portability Tip 22.1

Specify a namespace for each Web service so that it can be uniquely identified by clients. In general, you should use your company’s domain name as the Web service’s namespace, since company domain names are guaranteed to be unique.

Page 37: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

37

2006 Pearson Education, Inc. All rights reserved.

Portability Tip 22.2

Specify descriptions for a Web service and its Web methods so that the Web service’s clients can view information about the service in the service’s ASMX page.

Page 38: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

38

2006 Pearson Education, Inc. All rights reserved.

Common Programming Error 22.2

No method with the WebMethod attribute can be declared static—for a client to access a Web method, an instance of that Web service must exist.

Page 39: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

39

2006 Pearson Education, Inc. All rights reserved.

22.4.2 Building a Web Service in Visual Web Developer• To create an ASP.NET Web Service project that executes on your

computer’s local IIS Web server:

- Step 1: Create the Project

• Must be project of type ASP.NET Web Service

- Step 2: Examine the Newly Created Project

• The code-behind file Service.cs contains code for a simple Web service

- Step 3: Modify and Rename the Code-Behind File

- Step 4: Examine the ASMX File

- Step 5: Modify the ASMX File

- Step 6: Rename the ASMX File

Page 40: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

40

2006 Pearson Education, Inc. All rights reserved.

Fig. 22.10 | Creating an ASP.NET Web Service in Visual Web Developer.

Page 41: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

41

2006 Pearson Education, Inc. All rights reserved.

Fig. 22.11 | Code view of a Web service.

Page 42: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

42

2006 Pearson Education, Inc. All rights reserved.

22.4.3 Deploying the HugeInteger Web Service

• Accessing the HugeInteger Web Service’s ASMX Page from Another Computer

- Access the Web service’s ASMX page from your computer by typing the following URL in a Web browser in the form:

• http://localhost/HugeInteger/HugeInteger.asmx

- By deploying the Web service on an IIS Web server, a client can connect to that server to access the Web service with a URL of the form:

• http://host/HugeInteger/HugeInteger.asmx

Page 43: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

43

2006 Pearson Education, Inc. All rights reserved.

22.4.3 Deploying the HugeInteger Web Service (Cont.)

• Accessing the HugeInteger Web Service’s ASMX Page When the Web Service Executes in Visual Web Developer’s Built-in Web Server

- Web servers typically receive requests on port 80

- Visual Web Developer’s Web server receives requests on a randomly selected port number

• Ensure that Visual Web Developer’s built-in Web server does not conflict with another Web server running

- Requests must be specify the port number as part of the request• Except when on port 80

- The URL to access the HugeInteger Web service’s ASMX page would be of the form:

• http://host:portNumber/HugeInteger/HugeInteger.asmx

Page 44: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

44

2006 Pearson Education, Inc. All rights reserved.

Error-Prevention Tip 22.2

Update the Web service’s ASMX file appropriately whenever the name of a Web service’s code-behind file or the class name changes. Visual Web Developer creates the ASMX file, but does not automatically update it when you make changes to other files in the project.

Page 45: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

45

2006 Pearson Education, Inc. All rights reserved.

22.4.4 Creating a Client to Consume the HugeInteger Web Service

• Create a Windows application as the client using Visual C# 2005:

- Step 1: Open the Add Web Reference Dialog (Fig. 22.12)

- Step 2: Locate Web Services on Your Computer (Fig. 22.13)

- Step 3: Choose the Web Service to Reference (Fig. 22.14)

- Step 4: Add the Web Reference (Fig. 22.15)

- Step 5: View the Web Reference in the Solution Explorer (Fig. 22.16)

Page 46: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

46

2006 Pearson Education, Inc. All rights reserved.

Fig. 22.12 | Adding a Web service reference to a project.

Page 47: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

47

2006 Pearson Education, Inc. All rights reserved.

Fig. 22.13 | Add Web Reference dialog.

Page 48: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

48

2006 Pearson Education, Inc. All rights reserved.

Fig. 22.14 | Web services located on localhost.

Page 49: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

49

2006 Pearson Education, Inc. All rights reserved.

Fig. 22.15 | Web reference selection and description.

Page 50: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

50

2006 Pearson Education, Inc. All rights reserved.

Fig. 22.16 | Solution Explorer after adding a Web reference to a project.

Page 51: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

51

2006 Pearson Education, Inc. All rights reserved.

22.4.4 Creating a Client to Consume the HugeInteger Web Service (Cont.)• Notes on Creating a Client to Consume a Web Service

- Add the Web reference first • So Visual C# 2005 can recognize an object of the Web service proxy class

- Can access the Web service through an object of the proxy class

- The proxy class is located in namespace localhost, so you must use localhost.class_name to reference this class

- Must create an object of the proxy class to access the Web service

- Do not need access to the proxy class’s code

- Can invoke the proxy object’s methods as if it were an object of the Web service class

- Two common technologies facilitate to locating a new Web service • Universal Description, Discovery and Integration (UDDI)

• Discovery of Web services (DISCO)

Page 52: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

52

2006 Pearson Education, Inc. All rights reserved.

1 // Fig. 22.17: UsingHugeIntegerService.cs

2 // Using the HugeInteger Web Service.

3 using System;

4 using System.Collections.Generic;

5 using System.ComponentModel;

6 using System.Data;

7 using System.Drawing;

8 using System.Text;

9 using System.Windows.Forms;

10 using System.Web.Services.Protocols;

11

12 namespace UsingHugeIntegerWebService

13 {

14 public partial class UsingHugeIntegerServiceForm : Form

15 {

16 public UsingHugeIntegerServiceForm()

17 {

18 InitializeComponent();

19 } // end constructor

20

21 // declare a reference to Web service

22 private localhost.HugeInteger remoteInteger;

23

24 private char[] zeros = { '0' }; // character to trim from strings

Outline

UsingHugeIntegerService.cs

(1 of 8)

Declare variable of localhost.HugeInteger

Page 53: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

53

2006 Pearson Education, Inc. All rights reserved.

25

26 // instantiates object to interact with Web service

27 private void UsingHugeIntegerServiceForm_Load( object sender,

28 EventArgs e )

29 {

30 // instantiate remoteInteger

31 remoteInteger = new localhost.HugeInteger();

32 } // end method UsingHugeIntegerServiceForm_Load

33

34 // adds two numbers input by user

35 private void addButton_Click( object sender, EventArgs e )

36 {

37 // make sure numbers do not exceed 100 digits and that both

38 // are not 100 digits long, which would result in overflow

39 if ( firstTextBox.Text.Length > 100 ||

40 secondTextBox.Text.Length > 100 ||

41 ( firstTextBox.Text.Length == 100 &&

42 secondTextBox.Text.Length == 100) )

43 {

44 MessageBox.Show( "HugeIntegers must not be more " +

45 "than 100 digits\r\nBoth integers cannot be " +

46 "of length 100: this causes an overflow", "Error",

47 MessageBoxButtons.OK, MessageBoxIcon.Information );

48 return;

49 } // end if

50

51 // perform addition

52 resultLabel.Text = remoteInteger.Add(

53 firstTextBox.Text, secondTextBox.Text ).TrimStart( zeros );

54 } // end method addButton_Click

Outline

UsingHugeIntegerService.cs

(2 of 8)

The proxy object is created and assigned to remoteInteger

Invoke method of the Web service

Page 54: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

54

2006 Pearson Education, Inc. All rights reserved.

55

56 // subtracts two numbers input by user

57 private void subtractButton_Click( object sender, EventArgs e )

58 {

59 // make sure HugeIntegers do not exceed 100 digits

60 if ( SizeCheck( firstTextBox, secondTextBox ) )

61 return;

62

63 // perform subtraction

64 try

65 {

66 string result = remoteInteger.Subtract(

67 firstTextBox.Text, secondTextBox.Text ).TrimStart( zeros );

68

69 if ( result == "" )

70 resultLabel.Text = "0";

71 else

72 resultLabel.Text = result;

73

74 } // end try

75

76 // if WebMethod throws an exception,

77 // then first argument was smaller than second

78 catch ( SoapException exception )

79 {

80 MessageBox.Show(

81 "First argument was smaller than the second" );

82 } // end catch

83 } // end method subtractButton_Click

Outline

UsingHugeIntegerService.cs

(3 of 8)Invoke method of the Web service

Page 55: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

55

2006 Pearson Education, Inc. All rights reserved.

84

85 // determines whether first number

86 // input by user is larger than second

87 private void largerButton_Click( object sender, EventArgs e )

88 {

89 // make sure HugeIntegers do not exceed 100 digits

90 if ( SizeCheck( firstTextBox, secondTextBox ) )

91 return;

92

93 // call Web-service method to determine if

94 // first integer is larger than the second

95 if ( remoteInteger.Bigger( firstTextBox.Text,

96 secondTextBox.Text ) )

97 resultLabel.Text = firstTextBox.Text.TrimStart( zeros ) +

98 " is larger than " +

99 secondTextBox.Text.TrimStart( zeros );

100 else

101 resultLabel.Text = firstTextBox.Text.TrimStart( zeros ) +

102 " is not larger than " +

103 secondTextBox.Text.TrimStart( zeros );

104 } // end method largerButton_Click

105

106 // determines whether first number

107 // input by user is smaller than second

108 private void smallerButton_Click( object sender, EventArgs e )

109 {

110 // make sure HugeIntegers do not exceed 100 digits

111 if ( SizeCheck( firstTextBox, secondTextBox ) )

112 return;

Outline

UsingHugeIntegerService.cs

(4 of 8)Invoke method of the Web service

Page 56: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

56

2006 Pearson Education, Inc. All rights reserved.

113

114 // call Web-service method to determine if

115 // first integer is smaller than second

116 if ( remoteInteger.Smaller( firstTextBox.Text,

117 secondTextBox.Text ) )

118 resultLabel.Text = firstTextBox.Text.TrimStart( zeros ) +

119 " is smaller than " +

120 secondTextBox.Text.TrimStart( zeros );

121 else

122 resultLabel.Text = firstTextBox.Text.TrimStart( zeros ) +

123 " is not smaller than " +

124 secondTextBox.Text.TrimStart( zeros );

125 } // end method smallerButton_Click

126

127 // determines whether two numbers input by user are equal

128 private void equalButton_Click( object sender, EventArgs e )

129 {

130 // make sure HugeIntegers do not exceed 100 digits

131 if ( SizeCheck( firstTextBox, secondTextBox ) )

132 return;

Outline

UsingHugeIntegerService.cs

(5 of 8)

Invoke method of the Web service

Page 57: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

57

2006 Pearson Education, Inc. All rights reserved.

133

134 // call Web-service method to determine if integers are equal

135 if ( remoteInteger.EqualTo( firstTextBox.Text,

136 secondTextBox.Text ) )

137 resultLabel.Text = firstTextBox.Text.TrimStart( zeros ) +

138 " is equal to " + secondTextBox.Text.TrimStart( zeros );

139 else

140 resultLabel.Text = firstTextBox.Text.TrimStart( zeros ) +

141 " is not equal to " +

142 secondTextBox.Text.TrimStart( zeros );

143 } // end method equalButton_Click

144

145 // determines whether numbers input by user are too big

146 private bool SizeCheck( TextBox first, TextBox second )

147 {

148 // display an error message if either number has too many digits

149 if ( ( first.Text.Length > 100 ) ||

150 ( second.Text.Length > 100 ) )

151 {

152 MessageBox.Show( "HugeIntegers must be less than 100 digits" ,

153 "Error", MessageBoxButtons.OK, MessageBoxIcon.Information);

154 return true;

155 } // end if

156

157 return false;

158 } // end method SizeCheck

159 } // end class UsingHugeIntegerServiceForm

160 } // end namespace UsingHugeIntegerWebService

Outline

UsingHugeIntegerService.cs

(6 of 8)

Invoke method of the Web service

Page 58: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

58

2006 Pearson Education, Inc. All rights reserved.

Outline

UsingHugeIntegerService.cs

(7 of 8)

Page 59: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

59

2006 Pearson Education, Inc. All rights reserved.

Outline

UsingHugeIntegerService.cs

(8 of 8)

Page 60: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

60

2006 Pearson Education, Inc. All rights reserved.

22.5 Session Tracking in Web Services

• Session Tracking- Eliminates the need for information to be passed between

the client and the Web service multiple times• Improves performance

- Web methods can return personalized, localized results without requiring that the address be passed in each method call

• After the user’s address is stored in a session variable

- Requires less effort on the part of the programmer• Less information is passed in each method call

Page 61: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

61

2006 Pearson Education, Inc. All rights reserved.

22.5.1 Creating a Blackjack Web Service

• Web method’s EnableSession - Indicates that session information should be maintained

and should be accessible to the method

- Required only for methods that must access the session information

Page 62: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

62

2006 Pearson Education, Inc. All rights reserved.

1 // Fig. 22.18: BlackjackService.cs

2 // Blackjack Web Service deals and counts cards.

3 using System;

4 using System.Web;

5 using System.Web.Services;

6 using System.Web.Services.Protocols;

7 using System.Collections;

8

9 [ WebService( Namespace = "http://www.deitel.com/", Description =

10 "A Web service that deals and counts cards for the game Blackjack" ) ]

11 [ WebServiceBinding( ConformsTo = WsiProfiles.BasicProfile1_1 ) ]

12 public class BlackjackService : System.Web.Services.WebService

13 {

14 // deals card that has not yet been dealt

15 [ WebMethod( EnableSession = true,

16 Description="Deal a new card from the deck." ) ]

17 public string DealCard()

18 {

19 string card = "2 2";

20

21 // get client's deck

22 ArrayList deck = ( ArrayList )( Session[ "deck" ] );

23 card = Convert.ToString( deck[ 0 ] );

24 deck.RemoveAt( 0 );

25 return card;

26 } // end method DealCard

Outline

BlackjackService.cs

(1 of 5)

Assign the Web service’s namespace and description

Indicates that the Web service conforms to

Basic Profile 1.1

Indicates that session information should be maintained and accessible to this method

Obtains the current user’s deck as an ArrayList from the Web

service’s Session object

Page 63: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

63

2006 Pearson Education, Inc. All rights reserved.

27

28 // creates and shuffles a deck of cards

29 [ WebMethod( EnableSession = true,

30 Description="Create and shuffle a deck of cards." ) ]

31 public void Shuffle()

32 {

33 object temporary; // holds card temporarily during swapping

34 Random randomObject = new Random(); // generates random numbers

35 int newIndex; // index of randomly selected card

36 ArrayList deck = new ArrayList(); // stores deck of cards (strings)

37

38 // generate all possible cards

39 for ( int i = 1; i <= 13; i++ ) // loop through face values

40 for ( int j = 0; j <= 3; j++ ) // loop through suits

41 deck.Add( i + " " + j ); // add card (string) to deck

42

43 // shuffles deck by swapping each card with another card randomly

44 for ( int i = 0; i < deck.Count; i++ )

45 {

46 // get random index

47 newIndex = randomObject.Next( deck.Count - 1 );

48 temporary = deck[ i ]; // save current card in temporary variable

49 deck[ i ] = deck[ newIndex ]; // copy randomly selected card

50 deck[ newIndex ] = temporary; // copy current card back into deck

51 } // end for

52

53 // add this deck to user's session state

54 Session.Add( "deck", deck );

55 } // end method Shuffle

Outline

BlackjackService.cs

(2 of 5)

Indicates that session information should be maintained and accessible to this method

Adds the ArrayList to the Session object to maintain the deck between method calls from

a particular client

Page 64: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

64

2006 Pearson Education, Inc. All rights reserved.

56

57 // computes value of hand

58 [ WebMethod( Description =

59 "Compute a numerical value for the current hand." ) ]

60 public int GetHandValue( string dealt )

61 {

62 // split string containing all cards

63 char[] tab = { '\t' };

64 string[] cards = dealt.Split( tab ); // get array of cards

65 int total = 0; // total value of cards in hand

66 int face; // face of the current card

67 int aceCount = 0; // number of aces in hand

68

69 // loop through the cards in the hand

70 foreach ( string drawn in cards )

71 {

72 // get face of card

73 face = Int32.Parse( drawn.Substring( 0, drawn.IndexOf( " " ) ) );

Outline

BlackjackService.cs

(3 of 5)

Allows the method to be called by the client

Page 65: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

65

2006 Pearson Education, Inc. All rights reserved.

74

75 switch ( face )

76 {

77 case 1: // if ace, increment aceCount

78 aceCount++;

79 break;

80 case 11: // if jack add 10

81 case 12: // if queen add 10

82 case 13: // if king add 10

83 total += 10;

84 break;

85 default: // otherwise, add value of face

86 total += face;

87 break;

88 } // end switch

89 } // end foreach

Outline

BlackjackService.cs

(4 of 5)

Page 66: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

66

2006 Pearson Education, Inc. All rights reserved.

90

91 // if there are any aces, calculate optimum total

92 if ( aceCount > 0 )

93 {

94 // if it is possible to count one ace as 11, and the rest

95 // as 1 each, do so; otherwise, count all aces as 1 each

96 if ( total + 11 + aceCount - 1 <= 21 )

97 total += 11 + aceCount - 1;

98 else

99 total += aceCount;

100 } // end if

101

102 return total;

103 } // end method GetHandValue

104 } // end class BlackjackService

Outline

BlackjackService.cs

(5 of 5)

Page 67: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

67

2006 Pearson Education, Inc. All rights reserved.

22.5.2 Consuming the Blackjack Web Service

•CookieContainer - Namespace System.Net- Stores the information from a cookie in a Cookie object

- Without creating a CookieContainer object, the Web service would create a new Session object for each request

• The user’s state information would not persist across requests

•Cookie - Contains a unique identifier that the Web service can use to

recognize the client when the client makes future requests

- The cookie is automatically sent back to the server as part of each request

Page 68: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

68

2006 Pearson Education, Inc. All rights reserved.

1 // Fig. 22.19: Blackjack.cs

2 // Blackjack game that uses the Blackjack Web service.

3 using System;

4 using System.Collections.Generic;

5 using System.ComponentModel;

6 using System.Data;

7 using System.Drawing;

8 using System.Text;

9 using System.Windows.Forms;

10 using System.Net;

11 using System.Collections;

12

13 namespace Blackjack

14 {

15 public partial class BlackjackForm : Form

16 {

17 // reference to Web service

18 private localhost.BlackjackService dealer;

19

20 // string representing the dealer's cards

21 private string dealersCards;

22

23 // string representing the player's cards

24 private string playersCards;

25 private ArrayList cardBoxes; // list of PictureBoxes for card images

26 private int currentPlayerCard; // player's current card number

27 private int currentDealerCard; // dealer's current card number

Outline

Blackjack.cs

(1 of 16)

Create an instance of BlackjackService

to represent dealer

Page 69: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

69

2006 Pearson Education, Inc. All rights reserved.

28

29 // enum representing the possible game outcomes

30 public enum GameStatus

31 {

32 PUSH, // game ends in a tie

33 LOSE, // player loses

34 WIN, // player wins

35 BLACKJACK // player has blackjack

36 } // end enum GameStatus

37

38 public BlackjackForm()

39 {

40 InitializeComponent();

41 } // end constructor

42

43 // sets up the game

44 private void BlackjackForm_Load( object sender, EventArgs e )

45 {

46 // instantiate object allowing communication with Web service

47 dealer = new localhost.BlackjackService();

48

49 // allow session state

50 dealer.CookieContainer = new CookieContainer();

51 cardBoxes = new ArrayList();

Outline

Blackjack.cs

(2 of 16)

Instantiate the “dealer”

Create a new CookieContainer object for the dealer’s

CookieContainer property

Page 70: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

70

2006 Pearson Education, Inc. All rights reserved.

52

53 // put PictureBoxes into cardBoxes

54 cardBoxes.Add( pictureBox1 );

55 cardBoxes.Add( pictureBox2 );

56 cardBoxes.Add( pictureBox3 );

57 cardBoxes.Add( pictureBox4 );

58 cardBoxes.Add( pictureBox5 );

59 cardBoxes.Add( pictureBox6 );

60 cardBoxes.Add( pictureBox7 );

61 cardBoxes.Add( pictureBox8 );

62 cardBoxes.Add( pictureBox9 );

63 cardBoxes.Add( pictureBox10 );

64 cardBoxes.Add( pictureBox11 );

65 cardBoxes.Add( pictureBox12 );

66 cardBoxes.Add( pictureBox13 );

67 cardBoxes.Add( pictureBox14 );

68 cardBoxes.Add( pictureBox15 );

69 cardBoxes.Add( pictureBox16 );

70 cardBoxes.Add( pictureBox17 );

71 cardBoxes.Add( pictureBox18 );

72 cardBoxes.Add( pictureBox19 );

73 cardBoxes.Add( pictureBox20 );

74 cardBoxes.Add( pictureBox21 );

75 cardBoxes.Add( pictureBox22 );

76 } // end method BlackjackForm_Load

Outline

Blackjack.cs

(3 of 16)

Page 71: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

71

2006 Pearson Education, Inc. All rights reserved.

77

78 // deals cards to dealer while dealer's total is less than 17,

79 // then computes value of each hand and determines winner

80 private void DealerPlay()

81 {

82 // while value of dealer's hand is below 17,

83 // dealer must take cards

84 while ( dealer.GetHandValue( dealersCards ) < 17 )

85 {

86 dealersCards += '\t' + dealer.DealCard(); // deal new card

87

88 // update GUI to show new card

89 DisplayCard( currentDealerCard, "" );

90 currentDealerCard++;

91 MessageBox.Show( "Dealer takes a card" );

92 } // end while

93

94 int dealersTotal = dealer.GetHandValue( dealersCards );

95 int playersTotal = dealer.GetHandValue( playersCards );

96

97 // if dealer busted, player wins

98 if ( dealersTotal > 21 )

99 {

100 GameOver( GameStatus.WIN );

101 return;

102 } // end if

Outline

Blackjack.cs

(4 of 16)

Invoke method of the Web service

Page 72: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

72

2006 Pearson Education, Inc. All rights reserved.

103

104 // if dealer and player have not exceeded 21,

105 // higher score wins; equal scores is a push.

106 if ( dealersTotal > playersTotal )

107 GameOver( GameStatus.LOSE );

108 else if ( playersTotal > dealersTotal )

109 GameOver( GameStatus.WIN );

110 else

111 GameOver( GameStatus.PUSH );

112 } // end method DealerPlay

113

114 // displays card represented by cardValue in specified PictureBox

115 public void DisplayCard( int card, string cardValue )

116 {

117 // retrieve appropriate PictureBox from ArrayList

118 PictureBox displayBox = ( PictureBox )( cardBoxes[ card ] );

119

120 // if string representing card is empty,

121 // set displayBox to display back of card

122 if ( cardValue == "" )

123 {

124 displayBox.Image =

125 Image.FromFile( "blackjack_images/cardback.png" );

126 return;

127 } // end if

128

129 // retrieve face value of card from cardValue

130 string face = cardValue.Substring( 0, cardValue.IndexOf( " " ) );

Outline

Blackjack.cs

(5 of 16)

Page 73: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

73

2006 Pearson Education, Inc. All rights reserved.

131

132 // retrieve the suit of the card from cardValue

133 string suit =

134 cardValue.Substring( cardValue.IndexOf( " " ) + 1 );

135

136 char suitLetter; // suit letter used to form image file name

137

138 // determine the suit letter of the card

139 switch ( Convert.ToInt32( suit ) )

140 {

141 case 0: // clubs

142 suitLetter = 'c';

143 break;

144 case 1: // diamonds

145 suitLetter = 'd';

146 break;

147 case 2: // hearts

148 suitLetter = 'h';

149 break;

150 default: // spades

151 suitLetter = 's';

152 break;

153 } // end switch

154

155 // set displayBox to display appropriate image

156 displayBox.Image = Image.FromFile(

157 "blackjack_images/" + face + suitLetter + ".png" );

158 } // end method DisplayCard

Outline

Blackjack.cs

(6 of 16)

Page 74: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

74

2006 Pearson Education, Inc. All rights reserved.

159

160 // displays all player cards and shows

161 // appropriate game status message

162 public void GameOver( GameStatus winner )

163 {

164 char[] tab = { '\t' };

165 string[] cards = dealersCards.Split( tab );

166

167 // display all the dealer's cards

168 for ( int i = 0; i < cards.Length; i++ )

169 DisplayCard( i, cards[ i ] );

170

171 // display appropriate status image

172 if ( winner == GameStatus.PUSH ) // push

173 statusPictureBox.Image =

174 Image.FromFile( "blackjack_images/tie.png" );

175 else if ( winner == GameStatus.LOSE ) // player loses

176 statusPictureBox.Image =

177 Image.FromFile( "blackjack_images/lose.png" );

178 else if ( winner == GameStatus.BLACKJACK )

179 // player has blackjack

180 statusPictureBox.Image =

181 Image.FromFile( "blackjack_images/blackjack.png" );

182 else // player wins

183 statusPictureBox.Image =

184 Image.FromFile( "blackjack_images/win.png" );

Outline

Blackjack.cs

(7 of 16)

Page 75: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

75

2006 Pearson Education, Inc. All rights reserved.

185

186 // display final totals for dealer and player

187 dealerTotalLabel.Text =

188 "Dealer: " + dealer.GetHandValue( dealersCards );

189 playerTotalLabel.Text =

190 "Player: " + dealer.GetHandValue( playersCards );

191

192 // reset controls for new game

193 stayButton.Enabled = false;

194 hitButton.Enabled = false;

195 dealButton.Enabled = true;

196 } // end method GameOver

197

198 // deal two cards each to dealer and player

199 private void dealButton_Click( object sender, EventArgs e )

200 {

201 string card; // stores a card temporarily until added to a hand

202

203 // clear card images

204 foreach ( PictureBox cardImage in cardBoxes )

205 cardImage.Image = null;

206

207 statusPictureBox.Image = null; // clear status image

208 dealerTotalLabel.Text = ""; // clear final total for dealer

209 playerTotalLabel.Text = ""; // clear final total for player

210

211 // create a new, shuffled deck on the remote machine

212 dealer.Shuffle();

Outline

Blackjack.cs

(8 of 16)

Invoke method of the Web service

Page 76: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

76

2006 Pearson Education, Inc. All rights reserved.

213

214 // deal two cards to player

215 playersCards = dealer.DealCard(); // deal a card to player's hand

216

217 // update GUI to display new card

218 DisplayCard( 11, playersCards );

219 card = dealer.DealCard(); // deal a second card

220 DisplayCard( 12, card ); // update GUI to display new card

221 playersCards += '\t' + card; // add second card to player's hand

222

223 // deal two cards to dealer, only display face of first card

224 dealersCards = dealer.DealCard(); // deal a card to dealer's hand

225 DisplayCard( 0, dealersCards ); // update GUI to display new card

226 card = dealer.DealCard(); // deal a second card

227 DisplayCard( 1, "" ); // update GUI to show face-down card

228 dealersCards += '\t' + card; // add second card to dealer's hand

229

230 stayButton.Enabled = true; // allow player to stay

231 hitButton.Enabled = true; // allow player to hit

232 dealButton.Enabled = false; // disable Deal Button

233

234 // determine the value of the two hands

235 int dealersTotal = dealer.GetHandValue( dealersCards );

236 int playersTotal = dealer.GetHandValue( playersCards );

Outline

Blackjack.cs

(9 of 16)

Invoke method of the Web service

Page 77: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

77

2006 Pearson Education, Inc. All rights reserved.

237

238 // if hands equal 21, it is a push

239 if ( dealersTotal == playersTotal && dealersTotal == 21 )

240 GameOver( GameStatus.PUSH );

241 else if ( dealersTotal == 21 ) // if dealer has 21, dealer wins

242 GameOver( GameStatus.LOSE );

243 else if ( playersTotal == 21 ) // player has blackjack

244 GameOver( GameStatus.BLACKJACK );

245

246 // next dealer card has index 2 in cardBoxes

247 currentDealerCard = 2;

248

249 // next player card has index 13 in cardBoxes

250 currentPlayerCard = 13;

251 } // end method dealButton_Click

252

253 // deal another card to player

254 private void hitButton_Click( object sender, EventArgs e )

255 {

256 // get player another card

257 string card = dealer.DealCard(); // deal new card

258 playersCards += '\t' + card; // add new card to player's hand

259

260 // update GUI to show new card

261 DisplayCard( currentPlayerCard, card );

262 currentPlayerCard++;

263

264 // determine the value of the player s hand

265 int total = dealer.GetHandValue( playersCards );

Outline

Blackjack.cs

(10 of 16)

Invoke method of the Web service

Page 78: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

78

2006 Pearson Education, Inc. All rights reserved.

266

267 // if player exceeds 21, house wins

268 if ( total > 21 )

269 GameOver( GameStatus.LOSE );

270

271 // if player has 21,

272 // they cannot take more cards, and dealer plays

273 if ( total == 21 )

274 {

275 hitButton.Enabled = false;

276 DealerPlay();

277 } // end if

278 } // end method hitButton_Click

279

280 // play the dealer’s hand after the play chooses to stay

281 private void stayButton_Click( object sender, EventArgs e )

282 {

283 stayButton.Enabled = false; // disable Stay Button

284 hitButton.Enabled = false; // display Hit Button

285 dealButton.Enabled = true; // re-enable Deal Button

286 DealerPlay(); // player chose to stay, so play the dealer's hand

287 } // end method stayButton_Click

288 } // end class BlackjackForm

289 } // end namespace Blackjack

Outline

Blackjack.cs

(11 of 16)

Page 79: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

79

2006 Pearson Education, Inc. All rights reserved.

Outline

Blackjack.cs

(12 of 16)

a) Initial cards dealt to the player and the dealer when the user pressed the Deal button

Page 80: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

80

2006 Pearson Education, Inc. All rights reserved.

Outline

Blackjack.cs

(13 of 16)

b) Cards after the player pressed the Hit button twice, then the Stay button. In this case, the player won the game with a higher total than the dealer.

Page 81: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

81

2006 Pearson Education, Inc. All rights reserved.

Outline

Blackjack.cs

(14 of 16)

c) Cards after the player pressed the Hit button once, then the Stay button. In this case, the player busted (exceeded 21) and the dealer won the game.

Page 82: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

82

2006 Pearson Education, Inc. All rights reserved.

Outline

Blackjack.cs

(15 of 16)

d) Cards after the player pressed the Deal button. In this case, the player won with Blackjack because the first two cards were an ace and a card with a value of 10 (a jack in this case.)

Page 83: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

83

2006 Pearson Education, Inc. All rights reserved.

Outline

Blackjack.cs

(16 of 16)

e) Cards after the player pressed the Stay button. In this case, the player and dealer push—they have the same card total.

Page 84: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

84

2006 Pearson Education, Inc. All rights reserved.

22.6 Using Web Forms and Web Services

• Using DataSet Designer to add a DataSet to a project

- Automatically create DataSet and TableAdapter objects for you

Page 85: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

85

2006 Pearson Education, Inc. All rights reserved.

1 // Fig. 22.20: ReservationService.cs

2 // Airline reservation Web Service.

3 using System;

4 using System.Web;

5 using System.Web.Services;

6 using System.Web.Services.Protocols;

7

8 [ WebService( Namespace = "http://www.deitel.com/", Description =

9 "Service that enables a user to reserve a seat on a plane." ) ]

10 [ WebServiceBinding( ConformsTo = WsiProfiles.BasicProfile1_1 ) ]

11 public class ReservationService : System.Web.Services.WebService

12 {

13 // create TicketsDataSet object for

14 // caching data from the Tickets database

15 private TicketsDataSet ticketsDataSet = new TicketsDataSet();

16

17 // create SeatsTableAdapter for interacting with the database

18 private TicketsDataSetTableAdapters.SeatsTableAdapter

19 SeatsTableAdapter =

20 new TicketsDataSetTableAdapters.SeatsTableAdapter();

21

22 // checks database to determine whether matching seat is available

23 [ WebMethod( Description = "Method to reserve a seat." ) ]

24 public bool Reserve( string seatType, string classType )

25 {

26 // fill TicketsDataSet.Seats with rows that represent untaken

27 // seats that match the specified seatType and classType

28 SeatsTableAdapter.FillByTypeAndClass(

29 ticketsDataSet.Seats, seatType, classType );

Outline

ReservationService.cs

(1 of 2)

Assign the Web service’s namespace and description

Allows the method to be called by the client

Query the database

Page 86: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

86

2006 Pearson Education, Inc. All rights reserved.

30

31 // if the number of seats returned is nonzero,

32 // obtain the first matching seat number and mark it as taken

33 if ( ticketsDataSet.Seats.Count != 0 )

34 {

35 string seatNumber = ticketsDataSet.Seats[ 0 ].Number;

36

37 SeatsTableAdapter.UpdateSeatAsTaken( seatNumber );

38 return true; // seat was reserved

39 } // end if

40

41 return false; // no seat was reserved

42 } // end method Reserve

43 } // end class ReservationService

Outline

ReservationService.cs

(2 of 2)Update the database

Page 87: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

87

2006 Pearson Education, Inc. All rights reserved.

22.6.1 Adding Data Components to a Web Services

• The following steps for configuring the DataSet and its corresponding TableAdapter using the airline reservation example:

- Step 1: Create ReservationService and Add a DataSet to the Project

- Step 2: Select the Data Source and Create a Connection

- Step 3: Open the Query Builder and Add the Seats Table from Tickets.mdf

- Step 4: Configure a SELECT Query to Obtain Available Seats

- Step 5: Add Another Query to the SeatsTableAdapter for the TicketsDataSet

- Step 6: Configure an UPDATE Statement to Reserve a Seat

Page 88: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

88

2006 Pearson Education, Inc. All rights reserved.

Fig. 22.21 | QueryBuilder dialog specifying a SELECT query that selects seats that are not already reserved and that match a particular type and class.

Page 89: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

89

2006 Pearson Education, Inc. All rights reserved.

Fig. 22.22 | QueryBuilder dialog specifying an UPDATE statement that reserves a seat.

Page 90: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

90

2006 Pearson Education, Inc. All rights reserved.

1 <%-- Fig. 22.23: ReservationClient.aspx --%>

2 <%-- Web Form that allows users to reserve seats on a plane. --%>

3 <%@ Page Language="C#" AutoEventWireup="true"

4 CodeFile="ReservationClient.aspx.cs"

5 Inherits="ReservationClient" %>

6

7 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"

8 "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

9

10 <html xmlns="http://www.w3.org/1999/xhtml" >

11 <head runat="server">

12 <title>Ticket Reservation</title>

13 </head>

14

15 <body>

16 <form id="form1" runat="server">

17 <div>

18 <asp:Label ID="instructionsLabel" runat="server"

19 Text="Please select the seat type and class to reserve:">

Outline

ReservationClient .aspx

(1 of 2)

Page 91: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

91

2006 Pearson Education, Inc. All rights reserved.

20 </asp:Label><br /><br />

21

22 <asp:DropDownList ID="seatList" runat="server"

23 Height="22px" Width="100px">

24 <asp:ListItem>Aisle</asp:ListItem>

25 <asp:ListItem>Middle</asp:ListItem>

26 <asp:ListItem>Window</asp:ListItem>

27 </asp:DropDownList>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

28

29 <asp:DropDownList ID="classList" runat="server" Width="100px">

30 <asp:ListItem>Economy</asp:ListItem>

31 <asp:ListItem>First</asp:ListItem>

32 </asp:DropDownList>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

33

34 <asp:Button ID="reserveButton" runat="server" Height="24px"

35 OnClick="reserveButton_Click"

36 Text="Reserve" Width="102px" /><br /><br />

37

38 <asp:Label ID="errorLabel" runat="server" ForeColor="#C00000"

39 Height="19px" Width="343px"></asp:Label>

40 </div>

41 </form>

42 </body>

43 </html>

Outline

ReservationClient .aspx

(2 of 2)

Button to submit requests after making selections

Defines an initially blank Label which displays an appropriate message if no seat matching the user’s

selection is available

Page 92: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

92

2006 Pearson Education, Inc. All rights reserved.

1 // Fig. 22.24: ReservationClient.aspx.cs

2 // ReservationClient code behind file.

3 using System;

4 using System.Data;

5 using System.Configuration;

6 using System.Web;

7 using System.Web.Security;

8 using System.Web.UI;

9 using System.Web.UI.WebControls;

10 using System.Web.UI.WebControls.WebParts;

11 using System.Web.UI.HtmlControls;

12

13 public partial class ReservationClient : System.Web.UI.Page

14 {

15 // object of proxy type used to connect to Reservation Web service

16 private localhost.ReservationService ticketAgent =

17 new localhost.ReservationService();

Outline

ReservationClient .aspx.cs

(1 of 2)

Create a ReservationService

proxy object

Page 93: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

93

2006 Pearson Education, Inc. All rights reserved.

18

19 // attempt to reserve the selected type of seat

20 protected void reserveButton_Click( object sender, EventArgs e )

21 {

22 // if WebMethod returned true, signal success

23 if ( ticketAgent.Reserve( seatList.SelectedItem.Text,

24 classList.SelectedItem.Text ) )

25 {

26 // hide other controls

27 instructionsLabel.Visible = false;

28 seatList.Visible = false;

29 classList.Visible = false;

30 reserveButton.Visible = false;

31 errorLabel.Visible = false;

32

33 // display message indicating success

34 Response.Write( "Your reservation has been made. Thank you." );

35 } // end if

36 else // WebMethod returned false, so signal failure

37 {

38 // display message in the initially blank errorLabel

39 errorLabel.Text = "This type of seat is not available. " +

40 "Please modify your request and try again.";

41 } // end else

42 } // end method reserveButton_Click

43 } // end class ReservationClient

Outline

ReservationClient .aspx.cs

(2 of 2)Invoke Web method to determine if seat is available

Display the appropriate output based on the

Web method’s result

Page 94: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

94

2006 Pearson Education, Inc. All rights reserved.

Fig. 22.25 | Ticket reservation Web Form sample execution. (Part 1 of 2.)

a) Selecting a seat.

b) Seat reserved successfully

Page 95: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

95

2006 Pearson Education, Inc. All rights reserved.

Fig. 22.25 | Ticket reservation Web Form sample execution. (Part 2 of 2.)

c) Attempting to reserve another seat.

d) No seats match the requested type and class.

Page 96: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

96

2006 Pearson Education, Inc. All rights reserved.

22.7 User-Defined Types in Web Services

• Custom Types- Web methods can also return process user-defined types in

a Web service

- Web service clients can use these user-defined types• The proxy class created for the client contains the type

definitions

• Serialization of User-Defined Types- Custom types that are sent to or from a Web service are

serialized• Enable them to be passed in XML format

- Referred to as XML serialization

Page 97: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

97

2006 Pearson Education, Inc. All rights reserved.

22.7 User-Defined Types in Web Services (Cont.)

• Requirements for User-Defined Types Used with Web Methods

- Must provide a public default constructor• Must be able to call this constructor as part of the process of

deserializing the object when a Web service receives an XML serialized object

- Properties and instance variables that should be serialized in XML format must be declared public

- Properties that should be serialized must provide both get and set accessors

• Read-only properties are not serialized

• Any data that is not serialized simply receives its default value when an object of the class is deserialized

Page 98: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

98

2006 Pearson Education, Inc. All rights reserved.

Common Programming Error 22.3

Failure to define a default or parameterless public constructor for a type being passed to or returned from a Web method is a runtime error.

Page 99: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

99

2006 Pearson Education, Inc. All rights reserved.

Common Programming Error 22.4

Defining only the get or set accessor of a property for a user-defined type being passed to or returned from a Web method results in a property that is inaccessible to the client.

Page 100: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

100

2006 Pearson Education, Inc. All rights reserved.

Software Engineering Observation 22.1

Clients of a Web service can access only the service’s public members. The programmer can provide public properties to allow access to private data.

Page 101: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

101

2006 Pearson Education, Inc. All rights reserved.

1 // Fig. 22.26: Equation.cs

2 // Class Equation that contains information about an equation.

3 using System;

4 using System.Data;

5 using System.Configuration;

6 using System.Web;

7 using System.Web.Security;

8 using System.Web.UI;

9 using System.Web.UI.WebControls;

10 using System.Web.UI.WebControls.WebParts;

11 using System.Web.UI.HtmlControls;

12

13 public class Equation

14 {

15 private int leftOperand; // number to the left of the operator

16 private int rightOperand; // number to the right of the operator

17 private int resultValue; // result of the operation

18 private string operationType; // type of the operation

19

20 // required default constructor

21 public Equation()

22 : this( 0, 0, "+" )

23 {

24 // empty body

25 } // end default constructor

Outline

Equation.cs

(1 of 5)

Declare the required parameterless constructor

Calls the three argument constructor

Page 102: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

102

2006 Pearson Education, Inc. All rights reserved.

26

27 // three-argument constructor for class Equation

28 public Equation( int leftValue, int rightValue, string type )

29 {

30 leftOperand = leftValue;

31 rightOperand = rightValue;

32 operationType = type;

33

34 switch ( operationType ) // perform appropriate operation

35 {

36 case "+": // addition

37 resultValue = leftOperand + rightOperand;

38 break;

39 case "-": // subtraction

40 resultValue = leftOperand - rightOperand;

41 break;

42 case "*": // multiplication

43 resultValue = leftOperand * rightOperand;

44 break;

45 } // end switch

46 } // end three-argument constructor

47

48 // return string representation of the Equation object

49 public override string ToString()

50 {

51 return leftOperand.ToString() + " " + operationType + " " +

52 rightOperand.ToString() + " = " + resultValue.ToString();

53 } // end method ToString

Outline

Equation.cs

(2 of 5)

Page 103: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

103

2006 Pearson Education, Inc. All rights reserved.

54

55 // property that returns a string representing left-hand side

56 public string LeftHandSide

57 {

58 get

59 {

60 return leftOperand.ToString() + " " + operationType + " " +

61 rightOperand.ToString();

62 } // end get

63

64 set // required set accessor

65 {

66 // empty body

67 } // end set

68 } // end property LeftHandSide

69

70 // property that returns a string representing right-hand side

71 public string RightHandSide

72 {

73 get

74 {

75 return resultValue.ToString();

76 } // end get

77

78 set // required set accessor

79 {

80 // empty body

81 } // end set

82 } // end property RightHandSide

Outline

Equation.cs

(3 of 5)

set accessors are required even if it means having empty bodies

Page 104: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

104

2006 Pearson Education, Inc. All rights reserved.

83

84 // property to access the left operand

85 public int Left

86 {

87 get

88 {

89 return leftOperand;

90 } // end get

91

92 set

93 {

94 leftOperand = value;

95 } // end set

96 } // end property Left

97

98 // property to access the right operand

99 public int Right

100 {

101 get

102 {

103 return rightOperand;

104 } // end get

105

106 set

107 {

108 rightOperand = value;

109 } // end set

110 } // end property Right

Outline

Equation.cs

(4 of 5)

Page 105: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

105

2006 Pearson Education, Inc. All rights reserved.

111

112 // property to access the result of applying

113 // an operation to the left and right operands

114 public int Result

115 {

116 get

117 {

118 return resultValue;

119 } // end get

120

121 set

122 {

123 resultValue = value;

124 } // end set

125 } // end property Result

126

127 // property to access the operation

128 public string Operation

129 {

130 get

131 {

132 return operationType;

133 } // end get

134

135 set

136 {

137 operationType = value;

138 } // end set

139 } // end property Operation

140 } // end class Equation

Outline

Equation.cs

(5 of 5)

Page 106: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

106

2006 Pearson Education, Inc. All rights reserved.

1 // Fig. 22.27: Generator.cs

2 // Web Service to generate random equations based on a specified

3 // operation and difficulty level.

4 using System;

5 using System.Web;

6 using System.Web.Services;

7 using System.Web.Services.Protocols;

8

9 [ WebService( Namespace = "http://www.deitel.com/", Description =

10 "Web service that generates a math equation." ) ]

11 [ WebServiceBinding( ConformsTo = WsiProfiles.BasicProfile1_1 ) ]

12 public class Generator : System.Web.Services.WebService

13 {

14 // Method to generate a math equation

15 [ WebMethod( Description = "Method to generate a math equation." ) ]

16 public Equation GenerateEquation( string operation, int level )

17 {

18 // find maximum and minimum number to be used

19 int maximum = Convert.ToInt32( Math.Pow( 10, level ) );

20 int minimum = Convert.ToInt32( Math.Pow( 10, level - 1 ) );

Outline

Generator.cs

(1 of 2)

Allows the method to be called by the client

Page 107: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

107

2006 Pearson Education, Inc. All rights reserved.

21

22 // object to generate random numbers

23 Random randomObject = new Random();

24

25 // create equation consisting of two random

26 // numbers between minimum and maximum parameters

27 Equation equation = new Equation(

28 randomObject.Next( minimum, maximum ),

29 randomObject.Next( minimum, maximum ), operation );

30

31 return equation;

32 } // end method GenerateEquation

33 } // end class Generator

Outline

Generator.cs

(2 of 2)

Passes the string operation received by GenerateEquation to the

Equation constructor

Return the created Equation object

Page 108: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

108

2006 Pearson Education, Inc. All rights reserved.

Fig. 22.28 | Returning an XML serialized object from a Web method. (Part 1 of 2.)

a) Invoking the GenerateEquation method to create a subtraction equation with two-digit numbers.

Page 109: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

109

2006 Pearson Education, Inc. All rights reserved.

Fig. 22.28 | Returning an XML serialized object from a Web method. (Part 2 of 2.)

b) XML encoded results of invoking the GenerateEquation method to create a subtraction equation with two-digit numbers.

Page 110: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

110

2006 Pearson Education, Inc. All rights reserved.

1 // Fig. 22.29: MathTutor.cs

2 // Math tutoring program using Web service to generate random equations.

3 using System;

4 using System.Collections.Generic;

5 using System.ComponentModel;

6 using System.Data;

7 using System.Drawing;

8 using System.Text;

9 using System.Windows.Forms;

10

11 namespace MathTutor

12 {

13 public partial class MathTutorForm : Form

14 {

15 public MathTutorForm()

16 {

17 InitializeComponent();

18 } // end constructor

19

20 private string operation = "+";

21 private int level = 1;

22 private localhost.Equation equation;

23 private localhost.Generator generator = new localhost.Generator();

24

25 // generates new equation when user clicks button

26 private void generateButton_Click( object sender, EventArgs e )

27 {

28 // generate equation using current operation and level

29 equation = generator.GenerateEquation( operation, level );

Outline

MathTutor.cs

(1 of 6)

Create objects of Equation and Generator from the localhost

Invoke GenerateEquation and assign the return object to

equation

Page 111: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

111

2006 Pearson Education, Inc. All rights reserved.

30

31 // display left-hand side of equation

32 questionLabel.Text = equation.LeftHandSide;

33

34 okButton.Enabled = true;

35 answerTextBox.Enabled = true;

36 } // end method generateButton_Click

37

38 // check user's answer

39 private void okButton_Click( object sender, EventArgs e )

40 {

41 // determine correct result from Equation object

42 int answer = equation.Result;

43

44 if ( answerTextBox.Text == "" )

45 return;

46

47 // get user's answer

48 int userAnswer = Int32.Parse( answerTextBox.Text );

Outline

MathTutor.cs

(2 of 6)

Call equation’s properties

Page 112: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

112

2006 Pearson Education, Inc. All rights reserved.

49

50 // determine whether user's answer is correct

51 if ( answer == userAnswer )

52 {

53 questionLabel.Text = ""; // clear question

54 answerTextBox.Text = ""; // clear answer

55 okButton.Enabled = false; // disable OK button

56 MessageBox.Show( "Correct! Good job!" );

57 } // end if

58 else

59 MessageBox.Show( "Incorrect. Try again." );

60 } // end method okButton_Click

61

62 // set difficulty level to 1

63 private void levelOneRadioButton_CheckedChanged( object sender,

64 EventArgs e )

65 {

66 level = 1;

67 } // end method levelOneRadioButton_CheckedChanged

68

69 // set difficulty level to 2

70 private void levelTwoRadioButton_CheckedChanged( object sender,

71 EventArgs e )

72 {

73 level = 2;

74 } // end method levelTwoRadioButton_CheckedChanged

Outline

MathTutor.cs

(3 of 6)

Page 113: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

113

2006 Pearson Education, Inc. All rights reserved.

75

76 // set difficulty level to 3

77 private void levelThreeRadioButton_CheckedChanged( object sender,

78 EventArgs e )

79 {

80 level = 3;

81 } // end method levelThreeRadioButton_CheckedChanged

82

83 // set the operation to addition

84 private void additionRadioButton_CheckedChanged( object sender,

85 EventArgs e )

86 {

87 operation = "+";

88 generateButton.Text =

89 "Generate " + additionRadioButton.Text + " Example";

90 } // end method additionRadioButton_CheckedChanged

91

92 // set the operation to subtraction

93 private void subtractionRadioButton_CheckedChanged( object sender,

94 EventArgs e )

95 {

96 operation = "-";

97 generateButton.Text = "Generate " +

98 subtractionRadioButton.Text + " Example";

99 } // end method subtractionRadioButton_CheckedChanged

Outline

MathTutor.cs

(4 of 6)

Page 114: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

114

2006 Pearson Education, Inc. All rights reserved.

100

101 // set the operation to multiplication

102 private void multiplicationRadioButton_CheckedChanged(

103 object sender, EventArgs e )

104 {

105 operation = "*";

106 generateButton.Text = "Generate " +

107 multiplicationRadioButton.Text + " Example";

108 } // end method multiplicationRadioButton_CheckedChanged

109 } // end class MathTutorForm

110 } // end namespace MathTutor

Outline

MathTutor.cs

(5 of 6)

a) Generating a level 1 addition equation.

Page 115: 2006 Pearson Education, Inc. All rights reserved. 1 22 Web Services.

115

2006 Pearson Education, Inc. All rights reserved.

Outline

MathTutor.cs

(6 of 6)

d) Generating a level 2 multiplication equation.

c) Answering the equation correctly.

b) Answering the equation incorrectly.