WebService Class and Visual Studio

Team-Fly    

 
Application Development Using Visual Basic and .NET
By Robert J. Oberg, Peter Thorsteinson, Dana L. Wyatt
Table of Contents
Chapter 15.  Web Services


As we have previously demonstrated, a Web service is nothing but an HTTP request. As such, a Web service can access the intrinsic objects associated with its HTTP request. These are the same intrinsic objects discussed in the section "State in ASP.NET Applications" in the previous chapter. The WebService class has properties that access these intrinsic objects. In this section we discuss the WebService class, and we use Visual Studio, which makes developing Web services and clients much easier.

You need not derive your Web service class from the framework WebService class. You can derive your Web service class from a different base class if necessary. In this case you can use the current HttpContext to access the intrinsic objects. The WebService class inherits from MarshalByRefObject , however, so if you want your Web service class to be remotable, and you do inherit from a different base class, make sure that class also inherits from MarshalByRefObject . The HttpContext enables you to get information about an HTTP request. By using the static Current property, you can get access to the current request.

We will now build a Web service inside Visual Studio .NET that will illustrate the use of these intrinsic objects inside a Web service. As Figure 15-6 demonstrates , choose ASP.NET Web service from the New Project dialog box in Visual Studio .NET. Call your project Arithmetic , and create it in the Demos directory for this chapter.

Figure 15-6. Visual Studio .NET New Project dialog with ASP.NET Web service project selected.

graphics/15fig06.jpg

When you click the OK button, VS.NET will set up a Web service project for you. Figure 15-7 shows the resulting VS.NET project.

Figure 15-7. Visual Studio .NET Web services project.

graphics/15fig07.jpg

Hello World Web Service

The project created by Visual Studio has commented-out code already provided for a simple "Hello World" Web service. All you have to do to implement a Web service is to uncomment this code, build, and run! Before creating our real example, let's pause and do this simple exercise. Uncomment the last three code lines of the class. You will then have the following code, which is also saved in the folder HelloWebService in the file Service1.asmx .

 graphics/codeexample.gif Imports System.Web.Services <WebService(Namespace := "http://tempuri.org/")> _ Public Class Service1     Inherits System.Web.Services.WebService #Region " Web services Designer Generated Code " ...     ' WEB SERVICE EXAMPLE     ' The HelloWorld() example service returns the string     ' Hello World. To build, uncomment the following lines     ' then save and build the project. To test this web     ' service, ensure that the .asmx file is the start     ' page and press F5.     '    <WebMethod()> Public Function HelloWorld() As String       HelloWorld = "Hello World"    End Function End Class 

If you run from inside Visual Studio, you will get the familiar test page, with a recommendation to change the default namespace before the Web service is made public. See Figure 15-8. You may go ahead and test the Web service in the usual manner, and you should see that, sure enough, the string "Hello World" is returned.

Figure 15-8. Web service test page with recommendation to change default namespace.

graphics/15fig08.jpg

Change the default namespace to the one we have been using for our other examples, http://www.oi.com/netvb . You may then build and run again, and this time you should just get the plain test page without any recommendation.

Arithmetic Web Service

Our Web service will have several methods that demonstrate how to use the intrinsic objects. As you will see, this is really no different from their use in ASP.NET. Two of the methods will illustrate the use of application and session state by calculating a cumulative sum of numbers .

Global.asax

In the global.asax file we initialize our sum to zero in the appropriate event handlers. Global.asax has the same function in Web services as it does for ASP.NET, as discussed in the previous chapter in the section "ASP.NET Applications." Since the Global class inherits from System.Web.HttpApplication , it can access the Application and Session intrinsic objects.

 ' Global.asax Imports System.Web Imports System.Web.SessionState Public Class Global    Inherits System.Web.HttpApplication #Region " Component Designer Generated Code " ...    Sub Application_Start(ByVal sender As Object, _     ByVal e As EventArgs)       Application("TotalSum") = 0.0    End Sub    Sub Session_Start(ByVal sender As Object, _     ByVal e As EventArgs)       Session("SessionSum") = 0.0    End Sub ... 
Arithmetic.asmx

Renaming the Service1.asmx file to arithmetic.asmx , we define several Web methods. We have methods for the four fundamental arithmetic operations, Add , Subtract , Multiply , and Divide . To see the effect of the <WebMethod> attribute, we apply this attribute to all of these methods except Add . As usual, we specify a namespace for our Arithmetic class that inherits from the WebService class.

 ' Arithmetic.asmx Imports System.Web Imports System.Web.Services <WebService(Namespace:="http://www.oi.com/netvb")> _ Public Class Arithmetic    Inherits System.Web.Services.WebService ...    Public Function Add(ByVal x As Double, _     ByVal y As Double) As Double       Return x + y    End Function    <WebMethod()> Public Function Subtract(_     ByVal x As Double, ByVal y As Double) As Double       Return x - y    End Function    <WebMethod()> Public Function Multiply(_     ByVal x As Double, ByVal y As Double) As Double       Return x * y    End Function    <WebMethod()> Public Function Divide(_     ByVal x As Double, ByVal y As Double) As Double       Return x / y    End Function 

By setting the EnableSession argument to the WebMethod attribute to true , we turn on session state for the SessionSum method. (Note the := syntax in VB.NET for assigning a value to an attribute parameter.) Every time a new session is started, the sum is reset to zero.

 <WebMethod(EnableSession:=True)> _ Public Function SessionSum(ByVal x As Double) As Double    Dim sum As Double = CDbl(Session("SessionSum"))    sum += x    Session("SessionSum") = sum    Return sum End Function 

On the other hand, for the CumulativeSum Web method, EnableSession is set to its default value or false, so that the sum is reset to zero only when the Web service application is restarted. The Application intrinsic object is used from the HttpContext object to show how that class is used.

 <WebMethod()> _ Public Function CumulativeSum(ByVal x As Double) As Double    Dim sum As Double = CDbl(Application("TotalSum"))    sum += x    Application("TotalSum") = sum    Return CDbl(HttpContext.Current.Application("TotalSum")) End Function ... 

It should be clear from this code that HttpApplication , WebService , and HttpContext all reference the same intrinsic objects. If you need to save state for the application or session of a Web service, you can use the collections associated with HttpApplicationState and HttpSessionState to do so.

The GetUserAgent method shows how to use the Context object to access information about the request. We return what kind of application is accessing the Web service. The GetServerInfo method accesses the Server intrinsic object.

 <WebMethod()> Public Function GetUserAgent() As String    Return Context.Request.UserAgent End Function <WebMethod()> Public Function GetServerInfo() As String    Dim msg As String = "Timeout for " & _       Server.MachineName & " = " & _       Server.ScriptTimeout & _       "; Located at " & Server.MapPath("")    Return msg End Function 

Running the program from inside Visual Studio brings up the normal test page in Internet Explorer, as illustrated in Figure 15-9. Note that there are links for testing each of our methods, except for Add , which did not have the <WebMethod()> attribute.

Figure 15-9. Test page in Internet Explorer for Arithmetic Web service.

graphics/15fig09.jpg

Client Program for Arithmetic Web Service

graphics/codeexample.gif

Visual Studio makes it very easy to create client programs for Web services. You do not need to explicitly use the wsdl tool to generate a proxy. You can achieve the same effect by adding a "Web Reference" to your project. As a demonstration, we will create a client program for our Arithmetic Web service, saved in the directory ArithmeticClient . If you would like to follow along, do your work in the Demos directory.

  1. Use Visual Studio to create a new Visual Basic console project ArithmeticClient in the Demos directory.

  2. Rename Module1 to Arithmetic , and make it the startup object.

  3. In Solution Explorer, right-click over References and choose Add Web Reference from the context menu.

  4. In the Add Web Reference dialog box that comes up, type in the HTTP address of the Web service in the Address edit box, followed by a carriage return. Information about the Arithmetic Web service will appear, as in Figure 15-10.

    Figure 15-10. Visual Studio display of Arithmetic Web service information.

    graphics/15fig10.jpg

  5. Click on the Add Reference button to add the Web reference. This will add a Web References set of subdirectories below the current project that will contain the proxy class and the wsdl file for the Web service. See Figure 15-11.

    Figure 15-11. Web references are displayed in Visual Studio Solution Explorer.

    graphics/15fig11.jpg

  6. Examine the file Reference.vb , in the localhost subdirectory of the Web References directory in your project. You will see code for a VB.NET proxy class, in the namespace localhost .

  7. To the client program, we will have to reference the proxy class's namespace:

     Imports ArithmeticClient.localhost 
  8. Now add code to exercise the Web service by calling methods of the proxy.

We calculate a sum using the total held by the Application intrinsic object. Next, we calculate a sum for the total held by the Session intrinsic object.

 Dim a As New Arithmetic() Dim sum As Double Dim i As Integer For i = 0 To 4    sum = a.CumulativeSum(i)    Console.WriteLine(_      "Adding {0}, Application sum is now {1}", i, sum) Next Dim sessionSum As Double For i = 0 To 4    sessionSum = a.SessionSum(i)    Console.WriteLine(_      "Adding {0}, Session sum is now {1}", i, sessionSum) Next 

This will give us the following output. The exact numbers for the application-based sum will depend on how many times you have run the application. The output shown is for the first run of the application.

 Adding 0, Application sum is now 0 Adding 1, Application sum is now 1 Adding 2, Application sum is now 3 Adding 3, Application sum is now 6 Adding 4, Application sum is now 10 Adding 0, Session sum is now 0 Adding 1, Session sum is now 1 Adding 2, Session sum is now 2 Adding 3, Session sum is now 3 Adding 4, Session sum is now 4 

We now create another instance of the proxy class and make the same method calls.

 Dim a2 As New Arithmetic() For i = 0 To 4    sum = a2.CumulativeSum(i)    Console.WriteLine(_       "Adding {0}, Application sum is now {1}", i, sum) Next For i = 0 To 4    sum = a2.SessionSum(i)    Console.WriteLine(_       "Adding {0}, Session sum is now {1}", i, sum) Next 

We get the following output. Notice how the application sum continues to increase, while the session bases sum starts again from zero. A new browser session is not the only way to start a new Web service session.

 Adding 0, Application sum is now 10 Adding 1, Application sum is now 11 Adding 2, Application sum is now 13 Adding 3, Application sum is now 16 Adding 4, Application sum is now 20 Adding 0, Session sum is now 0 Adding 1, Session sum is now 1 Adding 2, Session sum is now 2 Adding 3, Session sum is now 3 Adding 4, Session sum is now 4 

Finally, we call the GetUserAgent and GetServerInfo Web methods.

 Console.WriteLine(a2.GetUserAgent()) Console.WriteLine(a2.GetServerInfo()) 

The output will look something like this:

 graphics/codeexample.gif Mozilla/4.0 (compatible; MSIE 6.0; MS Web Services Client Protocol 1.0.3705.0) Timeout for DELLPRO = 90; Located at C:\OI\NetVb\Chap15\Demos\Arithmetic 

Team-Fly    
Top
 


Application Development Using Visual BasicR and .NET
Application Development Using Visual BasicR and .NET
ISBN: N/A
EAN: N/A
Year: 2002
Pages: 190

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