Implementing Web Services

Team-Fly    

 
Visual Basic .NET Unleashed
By Paul Kimmel
Table of Contents
Chapter 18.  Using and Implementing Web Services

Implementing Web Services

Web Services are Web application DLLs that contain classes generalized from the System.Web.Services.WebService class. Web methods are methods in a WebService that are tagged with the WebMethodAttribute. The easiest way to create a WebService is to select an ASP.NET Web Service template from the New Project dialog box. The ASP.NET Web Service template will prepare the project for you, including creating the global.asax file, adding an .asmx file that contains the ASP code that will be your Web Service, creating the web.config file and the . vsdisco file.

We will cover the role of each of these files and wrap up this section with the .asmx file and implementing the Web Service.

global.asax File

The global.asax file is the entry point for your HttpApplication, the Web Service application. global.asax contains a class named Global that provides an empty module containing empty application-level event handlers that you can write code to respond to.

The ASP.NET Web Service template creates a global.asax module automatically. However, if you were to start your Web Service with the empty Web application template, no global.asax file would be generated. If no global.asax file exists, .NET assumes that you are not handling application-level events. Table 18.1 contains the list of application-level events.

Table 18.1. Application Events Defined in the global.asax Module
Event Name Description
Application_Start Raised when the application starts
Session_Start Raised when a session starts
Application_BeginRequest Raised when a request begins
Application_AuthenticationRequest Raised when authentication is attempted
Application_Error Raised when an application error occurs
Session_End Raised when a session ends
Application_End Raised when the application ends

Write handling code for these methods if you determine that some custom response is needed. The global.asax file is a module, containing a class derived from System.Web.HttApplication. There are several methods, properties, and additional events that you can use to manage the way that the application containing your Web Service behaves.

web.config File

The web.config file resides in the application root directory containing your Web Service. Listing 18.3 contains a sample web.config file generated for the Web Service example, WebService1.dll, used until now.

Listing 18.3 A sample web.config file
[View full width]
  1:  <?xml version="1.0" encoding="utf-8" ?>  2:  <configuration>  3:   4:  <system.web>  5:   6:  <compilation defaultLanguage="vb" debug="true" />  7:   8:  <customErrors mode="RemoteOnly" />  9:   10:  <authentication mode="Windows" />  11:   12:  <authorization>  13:  <allow users="*" />  14:  </authorization>  15:   16:  <trace enabled="false" requestLimit="10" pageOutput="false" graphics/ccc.gif traceMode="SortByTime" localOnly="true" />  17:   18:  <sessionState  19:  mode="InProc"  20:  stateConnectionString="tcpip=127.0.0.1:42424"  21:  sqlConnectionString="data source=127.0.0.1;user id=sa;password="  22:  cookieless="false"  23:  timeout="20"  24:  />  25:   26:  <globalization requestEncoding="utf-8" responseEncoding="utf-8" />  27:   28:  </system.web>  29:   30:  </configuration> 

The web.config file contains well- formed , nested XML tags. XML tags are case sensitive. Tag names and attributes are camel-cased (the first character is lowercase, and the first character of concatenated words is uppercase). For example, requestLimit is an example of an attribute. Attribute values are Pascal-cased (the first character of each word is uppercased). For example, RemoteOnly is an example of an attribute value.

Line 1 defines the XML version and UTF-8 encoding means that the file contains Unicode characters .

Lines 2 and 30 are the <configuration> and </configuration> tags that define the beginning and end of the configuration information.

Lines 4 and 28<system.web> and </system.web>are tags that indicate that these configuration options are for ASP.NET Web applications.

The compilation tag on line 6 defines the language and debugging mode. If debugging mode is True, extra symbolic debugging information is added to the Web Service and a .pdb file is created to facilitate debugging. You should only leave the debug="true" value until you are ready to deploy your service. The .asmx file is compiled by the JITter and the debug attribute is used to include symbolic debug information or not.

Set the customErrors mode to "On" or "RemoteOnly" to enable custom error messages (see line 8). "Off" will disable custom error messages. Add <error> tags to indicate each error that you want to handle.

Line 10 describes the authentication mode. You can choose between Windows, Forms, Passport, and None. Use Windows authentication when you are using any form of IIS authentication. Forms authentication uses ASP.NET forms-based authentication. Passport authentication is a forms-based authentication model that uses Triple DES encryption to encrypt and decrypt query strings. Passport is a centralized, secure authentication service provided by Microsoft; you will have to register to use this service. Use None to support anonymous users.

The block on lines 12 through 14 allows you to specify allowed or denied users or roles. The wildcard "*" means applies to everyone, and "?" means applies to anonymous users. Line 13 allows all users to use the Web Service associated with the web.config file in Listing 18.3.

Line 16 specifies application tracing. If trace="true", application tracing occurs. Each time the Web Service is requested , an entry is written to the trace.axd file. You can view the trace file information by browsing to the trace.axd file for a Web Service. Assuming that we are still using WebService.dll on a PC, the trace file (see Figure 18.5) can be viewed by browsing to the following URL:

http://localhost/WebService1/trace.axd

Figure 18.5. A Web Service application trace.

graphics/18fig05.jpg

The sessionState tag on lines 18 to 24 indicates whether cookies will be used to maintain state and stores information about the TCP/IP connection and SQL connection data. The sessionState mode attribute can be InProc, Off, SQLServer, or StateServer. InProc, or In-Process, is the default. SQLServer is an example of an out-of-process state information store. The StateServer is a service that can be started and stopped by typing net start aspnet_state and net stop aspnet_state, respectively. The ASP.NET State Server is an out-of-process state manager too.

The globalization tag on line 26 contains information about the request and response encoding. requestEncoding and responseEncoding of utf-8 indicates that the Web Service will use Unicode encoding.

The Disco File

The .vsdisco file contains discovery information about the Web Service. You can invoke the Web Service with the query string Disco to display a copy of the XML discovery information, for example:

http://localhost/WebService1/Service1.asmx?Disco

Disco information is used to find Web Services and support a directory service maintaining references to Web Services.

The .asmx File

The .asmx file contains the ASP.NET code generated by your Web Service class. When you are designing a Web Service, you are modifying the Designer view of the .asmx.vb file. When you write code, you are adding the code directly to the .asmx.vb file.

For example, a WebService class named Service1 would consist of a Service1.resx file containing Web resource information in XSD (XML Schema and Data) format, a Service1.asmx.vb file containing your Visual Basic .NET source code, and a Service1.asmx file. The latter file maintains a reference to the code behind the page that is JITted when the page is requested.

If you invoke the Web Service programmatically, an object is returned. If you navigate to the .asmx page directly, a test page is displayed (see Figure 18.6).

Figure 18.6. A Web Service test page that allows you to invoke Web methods.

graphics/18fig06.jpg

Near the top of the page shown is a hyperlink to the WebMethod defined by this service. Click the hyperlink and a test page for that service is displayed (see Figure 18.7). Click the Invoke button (see Figure 18.7) and the WebMethod is invoked. When a WebMethod is invoked directly through this test page, appropriate XML is returned. In the example shown in Figure 18.8, the value returned by the HelloWorld Web method is returned.

Figure 18.7. Test page displayed when you navigate directly to a Web Service.

graphics/18fig07.jpg

Figure 18.8. XML response returned from the HelloWorld Web method.

graphics/18fig08.jpg

Clearly, if these rudimentary test pages were the only way to test Web Services, you would quickly find testing to be tedious . Fortunately, Web Services are implemented in Visual Studio .NET, and we can use the IDE's integrated debugger to test and debug Web Services just as we would any other code. Doing so is discussed later in the chapter.

When You Might Need a Web Service

With all of the possibilities that Web Services provide, it is impossible to predetermine most of the things developers will do with Web Services. There are some basic scenarios that suggest a need for a Web Service.

The scenarios suggested here are not my own. Microsoft has had longer to think about Web Services, and the scenarios presented here are gleaned from the help file text.

  • Core business solutions. Build a Web Service to represent a core business solution. If you're building software for an airline, perhaps you'll build an itinerary manager. If you are a software toolsmith , you might specialize in building tools for other developers. Maybe Amazon.com will make Web Services available so that participating Web sites can offer a search engine instead of a link to the Amazon.com site.

  • Integration of applications. Microsoft also suggests that Web Services can be used to integrate disparate applications. Although you may need to build Web Services for each application, and modify those applications to interact with the Web Services, this solution sounds better than rewriting several applications to create an Enterprise solution. Suppose you work for an insurance company, and your company has a good underwriting system. Now suppose that you can buy an off-the-shelf claims system. Rather than rewriting one or the other application to integrate them, you might choose to expose some of their functionality through Web Services.

  • Distribution applications. To some extent, consider using Web Services where you would have used DCOM and HTTP in the past. Web Services are not based on proprietary protocols, and make writing distributed applications easier.

Creating a Web Service

The most direct way to build a Web Service is to select the ASP.NET Web Service template from the New Project dialog box. The template will add all of the pieces you need to a project, allowing you to focus on the code.

Central to the Web Service is the .asmx file. By default the .asmx file will be named Service1.asmx for the first file, incrementing the numeric suffix for each successive file.

You interact with an .asmx file much as you would with a UserControl. There is a designer for adding controls, and you can press F7 to switch to the code editor and Shift+F7 to switch back to Designer view.

Inheriting from WebService

Web Services inherit from the System.Web.Services.WebService class. All the basic information necessary to compile and build a Web Service is provided by inheriting from WebService. To add capabilities you will need to define methods. To expose those capabilities to users, you will need to define methods that use WebMethodAttribute.

We will return to Web methods in a moment.

Applying the WebService Attribute

Optionally, you can apply the WebServiceAttribute to a Web Service class. This enables you to provide additional information about your Web Service by initializing the properties of the WebServiceAttribute class.

The WebServiceAttribute class has no positional arguments but introduces three new named arguments: Description, Name, and Namespace. Description allows you to provide a text description for your WebService. Description supports adding a helpful description when the description documents for a Web Service are generated (see Figure 18.6). Name gets or sets the name of the XML Web Service, and Namespace allows you to specify a namespace in the form of a URL.

Tip

Keep in mind that when attributes are employed, the Attribute suffix is dropped by convention.


The following example demonstrates using the WebServiceAttribute and the named arguments Namespace and Description.

[View full width]
 
[View full width]
<WebService(Description:="Represents a user-defined number of Dice, with random roll graphics/ccc.gif values.", _ Namespace:="http://www.softconcepts.com/")> _

When the description page is shown, the value of the Description field will be displayed, and the URL Namespace helps uniquely identify the Web Service.

Implementing Web Methods

When you have created the ASP.NET Web Service project, you automatically get the module containing the WebService class. Adding WebServiceAttribute is optional.

At this juncture, implementing WebService is a matter of implementing methods and choosing those that will make up the interface of your service by applying the WebMethodAttribute. Web methods must actually be procedures, but you can implement all of the other elements of a class. Users simply won't be able to directly invoke anything that is not a procedure and doesn't have WebMethodAttribute applied.

There are five overloaded versions of the WebMethodAttribute constructor. These represent the positional arguments. And, there are six additional properties that can be initialized using the positional argument syntax. (Refer to Chapter 12, "Defining Attributes," for more information on attributes, including information about using named and positional arguments.) Table 18.2 describes each of the positional arguments that can be initialized when applying WebMethodAttribute.

Table 18.1. WebMethodAttribute Positional Arguments
Property Name Description
BufferResponse Indicating whether the response to a request is buffered. Default is False.
CacheDuration An integer indicating the number of seconds a response should be buffered. Default is 0, or no cache support.
Description A string describing the WebMethod. The default is an empty string.
EnableSession A Boolean indicating whether session state is enabled for a WebMethod. The default is False.
MessageName The name used for the method when passed to and from the Web Service. (The most common use is to provide an alias for polymorphic methods.)
TransactionOption An enumeration indicating the transaction support. The default is Disabled.

The basic application of WebMethodAttribute has the following form:

 <WebMethod()> _ Public Sub SomeProcedure()... 

If you use the basic form, the default values for the properties of the WebMethodAttribute attribute will be used. Listing 18.4 demonstrates a WebService and the WebMethod attribute in a Web Service that returns a random roll of dice.

Listing 18.4 A WebService that returns randomly generated six-sided dice values
  1:  Imports System.Web.Services  2:   3:  <WebService(_  4:  Description:="Represents a random six-sided Dice roller.", _  5:  Name:="Dice", Namespace:="http://www.softconcepts.com/")> _  6:  Public Class Service1  7:  Inherits System.Web.Services.WebService  8:   9:  [ Web Services Designer Generated Code ]  10:   11:  <WebMethod(_  12:  Description:="Returns random values representing six-sided dice.")> _  13:  Public Function Roll(ByVal HowMany As Integer) As Integer()  14:  Dim DiceValues(HowMany) As Integer  15:  Dim R As New Random()  16:   17:  Dim I As Integer  18:  For I = 0 To DiceValues.Length - 1  19:  DiceValues(I) = R.Next(1, 7)  20:  Next  21:   22:  Return DiceValues  23:  End Function  24:   25:  End Class 

Note

The Roll Web Method rolls HowMany + 1 dice because arrays are zero-based . It is a simple matter to adjust the number of dice to account for the extra, zero-indexed Die in this implementation.


Milton Bradley executives aren't going to lose any sleep, but it does demonstrate that game developers working in collaboration could create common objects shared by many games . Every online game could use the random Dice-roll generator.

Lines 3, 4, and 5 demonstrate the WebServiceAttribute and named values for the Description, Name, and Namespace. Line 7 demonstrates inheritance from the WebService class. Lines 11 and 12 demonstrate applying the WebMethodAttribute to a public method to designate it as a Web Method.

The number of dice is passed to the Roll Web Method, which in turn uses the Random class to generate numbers between 1 and 6 for each die. (The upper bound value of the Random.Next method is not inclusive.) Listing 18.5 shows the code from a Windows application that uses the WebService and the Dice.vb module from Chapter 14, "Multithreaded Applications."

Listing 18.5 A Windows application that uses the random Dice Web Service
  1:  Imports UseWebDice  2:   3:  Public Class Form1  4:  Inherits System.Windows.Forms.Form  5:   6:  [ Windows Form Designer generated code ]  7:   8:  Private FDice() As Dice = _  9:  {New Dice(New Rectangle(10, 10, 50, 50), Color.Red), _  10:  New Dice(New Rectangle(70, 10, 50, 50), Color.Blue)}  11:   12:  Private Sub Button1_Click(ByVal sender As System.Object, _  13:  ByVal e As System.EventArgs) Handles Button1.Click  14:   15:   16:  Dim Dice As New localhost.Dice()  17:  Dim FValues() As Integer = Dice.Roll(2)  18:   19:  Dim I As Integer  20:  For I = 0 To FDice.Length - 1  21:  If (I < FValues.Length) Then  22:  FDice(I).Value = FValues(I)  23:  FDice(I).Draw(CreateGraphics)  24:  End If  25:  Next  26:   27:  End Sub  28:   29:  Private Sub Form1_Paint(ByVal sender As Object, _  30:  ByVal e As System.Windows.Forms.PaintEventArgs) _  31:  Handles MyBase.Paint  32:   33:  Dim I As Integer  34:  For I = 0 To FDice.Length - 1  35:  FDice(I).Draw(CreateGraphics)  36:  Next I  37:   38:  End Sub  39:   40:  Private Sub Timer1_Tick(ByVal sender As System.Object, _  41:  ByVal e As System.EventArgs) Handles Timer1.Tick  42:  Button1_Click(sender, e)  43:  End Sub  44:  End Class 

Each time a button is clicked on the form, the Dice object from the Web Service is created and the random roll of the Dice is returned. The returned values are used to specify the value of each Die and the Die is drawn. (The Timer was addedon lines 40 to 44 to roll the Dice on auto-pilot.)


Team-Fly    
Top
 


Visual BasicR. NET Unleashed
Visual BasicR. NET Unleashed
ISBN: N/A
EAN: N/A
Year: 2001
Pages: 222

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