Section 22.7. User-Defined Types in Web Services


22.7. User-Defined Types in Web Services

The Web methods we have demonstrated so far all received and returned primitive-type values. It is also possible to process user-defined typesknown as custom typesin a Web service. These types can be passed to or returned from Web methods. Web service clients also can use these user-defined types, because the proxy class created for the client contains the type definitions.

This section presents an EquationGenerator Web service that generates random arithmetic equations of type Equation. The client is a math-tutoring application that inputs information about the mathematical question that the user wishes to attempt (addition, subtraction or multiplication) and the skill level of the user (1 specifies equations using numbers from 1 to 10, 2 specifies equations involving numbers from 10 to 100, and 3 specifies equations containing numbers from 100 to 1000). The Web service then generates an equation consisting of random numbers in the proper range. The client application receives the Equation and displays the sample question to the user in a Windows Form.

Serialization of User-Defined Types

We mentioned earlier that all types passed to and from Web services must be supported by SOAP. How, then, can SOAP support a type that is not even created yet? Custom types that are sent to or from a Web service are serialized, enabling them to be passed in XML format. This process is referred to as XML serialization.

Requirements for User-Defined Types Used with Web Methods

Classes that are used to specify return types and parameter types for Web methods must meet several requirements:

  1. They must provide a Public default or parameterless constructor. When a Web service or Web service consumer receives an XML serialized object, the .NET Framework must be able to call this constructor as part of the process of deserializing the object (i.e., converting it back to a Visual Basic object).

  2. Properties and instance variables that should be serialized in XML format must be declared Public. (Note that the Public properties can be used to provide access to Private instance variables.)

  3. Properties that should be serialized must provide both Get and Set accessors (even if they have empty bodies). Read-only properties are not serialized.

Any data that is not serialized simply receives its default value (or the value provided by the default or parameterless constructor) when an object of the class is deserialized.

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.


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.


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.


Defining Class Equation

We define class Equation in Fig. 22.26. Lines 1529 define a constructor that takes three argumentstwo Integers representing the left and right operands and a String that represents the arithmetic operation to perform. The constructor sets the leftOperand, rightOperand and operationType instance variables, then calculates the appropriate result. The parameterless constructor (lines 1012) calls the three-argument constructor (lines 1529) and passes some default values. We do not use the parameterless constructor explicitly, but the XML serialization mechanism uses it when objects of this class are deserialized. Because we provide a constructor with parameters, we must explicitly define the parameterless constructor in this class so that objects of the class can be passed to or returned from Web methods.

Figure 22.26. Class that stores equation information.

  1  ' Fig. 22.26: Equation.vb  2  ' Class Equation that contains information about an equation.  3  Public Class Equation  4     Private leftOperand As Integer ' number to the left of the operator  5     Private rightOperand  As Integer ' number to the right of the operator  6     Private resultValue As Integer ' result of the operation  7     Private operationType As String ' type of the operation  8  9     ' required default constructor 10     Public Sub New()               11        MyClass.New(0, 0, "+")      12     End Sub ' parameterless New    13 14     ' three-argument constructor for class Equation 15     Public Sub New(ByVal  leftValue As Integer,  _ 16        ByVal rightValue As Integer, ByVal type As String) 17        leftOperand = leftValue 18        rightOperand = rightValue 19        operationType = type 20 21        Select Case operationType ' perform appropriate operation 22           Case "+" ' addition 23              resultValue = leftOperand  + rightOperand 24           Case "-" ' subtraction 25              resultValue = leftOperand  - rightOperand 26           Case "*" ' multiplication 27              resultValue = leftOperand  * rightOperand 28        End Select 29     End Sub ' three-parameter New 30 31    ' return string representation of the Equation object 32    Public Overrides Function ToString() As String 33      Return leftOperand.ToString() &  " " & operationType & " " & _ 34         rightOperand.ToString() & " = " & resultValue.ToString() 35    End Function ' ToString 36 37    ' property that returns a string representing left-hand side 38     Public Property LeftHandSide() As String 39        Get 40           Return leftOperand.ToString() & " " & operationType & " " & _ 41              rightOperand.ToString() 42        End Get 43 44        Set(ByVal value As String) ' required set accessor 45           ' empty body                                    46        End Set                                            47     End Property ' LeftHandSide 48 49       ' property that returns a string representing right-hand side 50       Public Property RightHandSide() As String 51          Get 52             Return resultValue.ToString() 53          End Get 54 55          Set(ByVal value  As String) ' required set accessor 56               ' empty body                                   57          End Set                                             58       End Property ' RightHandSide 59 60       ' property to  access the left operand 61       Public Property Left() As Integer 62          Get 63             Return leftOperand 64          End Get 65 66          Set(ByVal value  As Integer) 67              leftOperand = value 68          End Set 69       End Property ' Left 70 71       ' property to  access the right operand 72       Public Property Right() As Integer 73          Get 74            Return rightOperand 75          End Get 76 77          Set(ByVal value As Integer) 78             rightOperand  = value 79          End Set 80       End Property ' Right 81 82       ' property to  access the result of applying 83       ' an operation to the left and right operands 84       Public Property Result() As Integer 85          Get 86             Return resultValue 87          End Get 88 89          Set(ByVal value As Integer) 90             resultValue = value 91          End Set 92       End Property ' Result 93 94      ' property to  access the operation 95      Public Property Operation() As String 96         Get 97            Return operationType 98         End Get 99 100       Set(ByVal value As String) 101          operationType = value 102       End Set 103    End Property ' Operation 104 End Class ' Equation 

Class Equation defines properties LeftHandSide (lines 3847), RightHandSide (lines 5058), Left (lines 6169), Right (lines 7280), Result (lines 8492) and Operation (lines 95103). The client of the Web service does not need to modify the values of properties LeftHandSide and RightHandSide. However, recall that a property can be serialized only if it has both a Get and a Set accessorthis is true even if the Set accessor has an empty body. LeftHandSide (lines 3847) returns a String representing everything to the left of the equals (=) sign in the equation, and RightHandSide (lines 5058) returns a String representing everything to the right of the equals (=) sign. Left (lines 6169) returns the Integer to the left of the operator (known as the left operand), and Right (lines 7280) returns the Integer to the right of the operator (known as the right operand). Result (lines 8492) returns the solution to the equation, and Operation (lines 95103) returns the operator in the equation. The client in this case study does not use the RightHandSide property, but we included it in case future clients choose to use it. Method ToString (lines 3235) returns a String representation of the equation.

Creating the EquationGenerator Web Service

Figure 22.27 presents the EquationGenerator Web service, which creates random, customized Equations. This Web service contains only method GenerateEquation (lines 1632), which takes two parametersa String representing the mathematical operation (addition, subtraction or multiplication) and an Integer representing the difficulty level.

Figure 22.27. Web service that generates random equations.

  1  ' Fig. 22.27: EquationGeneratorWebService.vb  2  ' Web Service to generate random equations based on a specified  3  ' operation and difficulty level.  4  Imports System.Web  5  Imports System.Web.Services  6  Imports System.Web.Services.Protocols  7  8  <WebService(Namespace:="http://www.deitel.com/")> _  9  <WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _ 10  <Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _ 11  Public Class EquationGeneratorWebService 12     Inherits System.Web.Services.WebService 13     ' Method to generate a math equation 14     <WebMethod(Description:="Method to generate a math equation.")> _ 15     Public Function GenerateEquation(ByVal operation As String, _     16        ByVal level As Integer) As Equation                            17        ' calculate maximum and minimum number to be used 18        Dim maximum As Integer = Convert.ToInt32(Math.Pow(10, level)) 19        Dim minimum As Integer = Convert.ToInt32(Math.Pow(10, level - 1)) 20 21        Dim randomObject As New Random() ' used to  generate random numbers 22 23        ' create Equation consisting of two random          24        ' numbers in the range minimum to maximum           25        Dim newEquation As New Equation( _                  26           randomObject.Next(minimum,  maximum), _          27           randomObject.Next(minimum,  maximum), operation) 28 29        Return newEquation 30     End Function ' GenerateEquation 31  End Class ' EquationGeneratorWebService 

Testing the EquationGenerator Web Service

Figure 22.28 shows the result of testing the EquationGenerator Web service. Note that the return value from our Web method is XML-encoded. However, this example differs from previous ones in that the XML specifies the values for all Public properties and data of the object that is being returned. The return object has been serialized in XML. The client's object class takes this XML and deserializes it into an object of class Equation, that can be used by the client.

Figure 22.28. Returning an XML serialized object from a Web method.

a) Invoking the GenerateEquation method to create a subtraction equation with numbers in the range 10100.

b) XML encoded results of invoking the GenerateEquation method to create a subtraction equation with numbers in the range 10100.


Note that an Equation object is not being passed between the Web service and the client. Rather, the information in the object is being sent as XML-encoded data. Clients created using .NET will take the information and create a new Equation object. Clients created on other platforms, however, may use the information differently. Readers creating clients on other platforms should check the Web services documentation for the specific platform they are using, to see how their clients may process custom types.

Let's examine Web method GenerateEquation more closely. Lines 1819 of Fig. 22.27 define the upper and lower bounds for the random numbers that the method uses to generate an Equation. To set these limits, the program first calls Shared method Pow of class Maththis method raises its first argument to the power of its second argument. To calculate the value of maximum (the upper bound for any randomly generated numbers used to form an Equation), the program raises 10 to the power of the specified level argument (line 18). If level is 1, maximum is 10; if level is 2, maximum is 100; and if level is 3, maximum is 1000. Variable minimum's value is determined by raising 10 to a power one less than level (line 19). This calculates the smallest number with level digits. If level is 1, minimum is 1; if level is 2, minimum is 10; and if level is 3, minimum is 100.

Lines 2527 create a new Equation object. The program calls Random method Next, which returns an Integer that is greater than or equal to the specified lower bound, but less than the specified upper bound. This method generates a left operand value that is greater than or equal to minimum but less than maximum (i.e., a number with level digits). The right operand is another random number with the same characteristics. Line 27 passes the String operation received by GenerateEquation to the Equation constructor. Line 29 returns the new Equation object to the client.

Consuming the EquationGenerator Web Service

The MathTutor application (Fig. 22.29) calls the EquationGenerator Web service's GenerateEquation method to create an Equation object. The tutor then displays the left-hand side of the Equation and waits for user input. This example accesses classes Generator and Equation from the localhost namespaceboth are placed in this namespace by default when the proxy is generated. We declare variables of these types at lines 67. Line 7 also creates the Generator proxy. (Remember to add a Web reference to the EquationGeneratorWebService when you create this application.

Figure 22.29. Math-tutoring application.

 1  ' Fig. 22.29: FrmMathTutor.vb 2  ' Math tutoring program using Web service to generate random equations. 3  Public Class FrmMathTutor 4     Private operation As String =  "+" 5     Private level As Integer = 1 6     Private currentEquation As localhost.Equation                     7     Private generator As New localhost.EquationGeneratorWebService()  8 9     ' generates a new equation when user clicks button 10     Private Sub btnGenerate_Click(ByVal sender As System.Object, _ 11        ByVal e As System.EventArgs) Handles btnGenerate.Click 12        ' generate equation using current operation and level             13        currentEquation = generator.GenerateEquation(operation, level)    14 15        ' display left-hand side of equation 16        lblQuestion.Text = currentEquation.LeftHandSide 17 18        btnOK.Enabled = True 19        txtAnswer.Enabled = True 20     End Sub ' btnGenerate_Click 21 22     ' check user's answer 23     Private Sub btnOK_Click(ByVal sender As System.Object, _ 24        ByVal e As System.EventArgs) Handles btnOK.Click 25        ' determine correct result from Equation  object 26        Dim answer As Integer = currentEquation.Result 27 28        If txtAnswer.Text <> "" Then 29           ' get user's answer 30           Dim userAnswer As Integer = Int32.Parse(txtAnswer.Text) 31 32           ' determine whether user's answer is correct 33           If answer = userAnswer Then 34              lblQuestion.Text = "" ' clear question 35              txtAnswer.Text = "" ' clear answer 36              btnOK.Enabled = False ' disable  OK button 37              MessageBox.Show("Correct! Good  job!") 38           Else 39              MessageBox.Show("Incorrect. Try again.") 40          End If 41       End If 42    End Sub ' btnOK_Click 43 44    ' set the operation to addition 45    Private Sub radAddition_CheckedChanged( _ 46       ByVal sender As  System.Object, ByVal  e As System.EventArgs) _ 47       Handles radAddition.CheckedChanged 48       operation = "+" 49       btnGenerate.Text = "Generate " & radAddition.Text & " Example" 50    End Sub ' radAddition_CheckedChanged 51 52    ' set the operation to subtraction 53    Private Sub radSubtraction_CheckedChanged( _ 54       ByVal sender As System.Object, ByVal e As System.EventArgs) _ 55       Handles radSubtraction.CheckedChanged 56       operation = "-" 57       btnGenerate.Text = "Generate " & radSubtraction.Text & " Example" 58    End Sub ' radSubtraction_CheckedChanged 59 60    ' set the operation to multiplication 61    Private Sub radMultiplication_CheckedChanged( _ 62       ByVal sender As System.Object, ByVal e As System.EventArgs) _ 63       Handles radMultiplication.CheckedChanged 64       operation = "*" 65       btnGenerate.Text = "Generate " & radMultiplication.Text & " Example" 66    End Sub ' radMultiplication_CheckedChanged 67 68    ' set difficulty level to 1 69    Private Sub radLevelOne_CheckedChanged( _ 70       ByVal sender As System.Object, ByVal  e As System.EventArgs) _ 71       Handles radLevelOne.CheckedChanged 72       level = 1 73    End Sub ' radLevelOne_CheckedChanged 74 75    ' set difficulty level to 2 76    Private Sub radLevelTwo_CheckedChanged( _ 77       ByVal sender As System.Object, ByVal  e As System.EventArgs) _ 78       Handles radLevelTwo.CheckedChanged 79       level = 2 80    End Sub ' radLevelTwo_CheckedChanged 81 82    ' set difficulty level to 3 83    Private Sub radLevelThree_CheckedChanged( _ 84       ByVal sender As System.Object, ByVal e As System.EventArgs) _ 85       Handles radLevelThree.CheckedChanged 86       level = 3 87     End Sub ' radLevelThree_CheckedChanged 88  End Class ' FrmMathTutor 

a) Generating a level 1 addition equation.

b) Answering the equation incorrectly.

c) Answering the equation correctly.

d) Generating a level 2 multiplication equation.

The math-tutoring application displays an equation and waits for the user to enter an answer. The default setting for the difficulty level is 1, but the user can change this by choosing a level from the RadioButtons in the GroupBox labeled Difficulty. Clicking any of the levels invokes the corresponding RadioButton's CheckedChanged event handler (lines 6987), which sets integer level to the level selected by the user. Although the default setting for the question type is Addition, the user also can change this by selecting one of the RadioButtons in the GroupBox labeled Operation. Doing so invokes the corresponding operation's event handlers in lines 4566, which assigns to String operation the symbol corresponding to the user's selection. Each event handler also updates the Text property of the Generate button to match the newly selected operation.

Event handler btnGenerate_Click (lines 1020) invokes EquationGenerator method GenerateEquation (line 13). After receiving an Equation object from the Web service, the handler displays the left-hand side of the equation in lblQuestion (line 16) and enables btnOK so that the user can enter an answer. When the user clicks OK, btnOK_Click (lines 2342) checks whether the user provided the correct answer.



Visual BasicR 2005 for Programmers. DeitelR Developer Series
Visual Basic 2005 for Programmers (2nd Edition)
ISBN: 013225140X
EAN: 2147483647
Year: 2004
Pages: 435

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net