Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
(ebook) Visual Studio .NET Mastering Visual Basic.pdf
Скачиваний:
136
Добавлен:
17.08.2013
Размер:
15.38 Mб
Скачать

BUILDING A WEB SERVICE 1085

Building a Web Service

In all previous chapters, I’ve used the visual tools for just about anything. Here I’ll make an exception to show you how easy it really is to build a Web service. You’ll build your first Web service with Notepad. The following listing is a simple class that exposes two simple members. The same class could appear in any VB project. Its two methods are way too simple, but they contain straight VB code and you can make them as complicated as you wish.

Public Class MasteringServices

Public Function Add(ByVal a As Decimal, ByVal b As Decimal) As Decimal

Return(a + b)

End Function

Public Function Multiply(ByVal a As Decimal, ByVal b As Decimal) As Decimal

Return(a * b)

End Function

End Class

To turn this class into a Web service, insert the following statements at the beginning of the file:

<%@ webservice class=”MasteringServices” language=”vb” %> Imports System.Web.Services

The first statement is a directive that tells the compiler that the rest of the file is a Web service, written in Visual Basic. The name of the class is MasteringServices, but it will normally be a name made up from your company’s (or department’s) name and a name that reflects the functionality of the class. The second statement imports the System.Web.Services class, necessary for all Web services. Then prefix each method’s definition with the following tag:

<WebMethod()>

The <WebMethod()> tag tells the compiler that the specific method is to be exposed to HTTP requests; the class may also contain private members. The WebMethod tag may also contain attributes, similar to the attributes of the members exposed by the controls. One of them is the Description attribute, whose syntax is shown next:

<WebMethod(“Description”, “This method adds two numbers”)>

Listing 25.1 shows the code of your first Web service. Create a text file with these statements, and save it under the filename Mastering.asmx (the extension must be ASMX) in the Web server’s root folder. You’re actually ready to test your Web service.

Listing 25.1: The Structure of a Web Service

<%@ webservice class=”MasteringServices” language=”vb” %> Imports System.Web.Services

Public Class MasteringServices <WebMethod()> _

Public Function Add(ByVal a As Decimal, ByVal b As Decimal) As Decimal Return(a + b)

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

1086 Chapter 25 XML WEB SERVICES

End Function <WebMethod()> _

Public Function Multiply(ByVal a As Decimal, ByVal b As Decimal) As Decimal Return(a * b)

End Function End Class

To test the new service, start Internet Explorer and connect to the following URL:

http://localhost/Mastering.asmx

If you’re using a Web server on another machine, replace the localhost specification with the appropriate server address or name. A few seconds later, you will see the page shown in Figure 25.1.

Figure 25.1

Testing the

MasteringServices

Web service

The page shown in Figure 25.1 isn’t your page. Obviously, it was created on the fly and contains information about the MasteringServices Web service. Actually, you won’t find this page anywhere on your server. When you contact the Web service for the first time, it’s compiled and the compiler generates code to display the test pages as well.

Below the title of the Web service is a list of the members it exposes, the Add and Multiply methods. There’s also a warning to the effect that it uses the default namespace, which is http:// tempuri.org/. That’s a placeholder domain name owned by Microsoft and stands for “temporary URI.” When you post a Web service on the Web so that others can connect to it, you’ll add the following attribute to the WebService tag:

namespace=”http://your.server.com/yourservices”

as suggested at the bottom of the page.

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

BUILDING A WEB SERVICE 1087

The two methods are hyperlinks. Click the Add hyperlink and you’ll see the arguments of the method on a new page, which is shown in Figure 25.2. On this page, you can enter two numeric values to be added and then click the Invoke button. A new page will appear, with the result returned by the Add method. The result returned by the method is:

<?xml version=”1.0” encoding=”utf-8” ?>

<decimal xmlns=”http://tempuri.org/”>18</decimal>

Figure 25.2

Connecting to a Web service with your browser

This is the XML description of a decimal value. Had you entered the values –0.91 and 1.92, the Add method would have returned the following value:

<?xml version=”1.0” encoding=”utf-8” ?>

<decimal xmlns=”http://tempuri.org/”>1.01</decimal>

Test the Multiply function as well; nothing will differ. You can also add more members to the test class; you can use any VB statement or function, as well as any of the Framework’s classes, because the method’s code is executed on a machine that has access to the .NET Framework.

A Web service is a Class that resides on a Web server and makes its members (usually methods) available to any client. In addition, it displays information about itself on a page that’s built automatically when you attempt to contact one of the members of the Web service. This information includes the service’s name and the members it exposes. As you saw, you can even test these members from within Internet Explorer. Of course, the format of the output is a little unusual, but this is the only way to get information to the client through the HTTP protocol. Besides, only text will go through firewalls. Web services use XML to format their return value and pass it to the client. In effect, the Web service and its consumer (the application that makes use of the Web service) pretend they’re exchanging requests and HTML pages, all in textual format. As you can see, no special component needs to be installed on the client or the server.

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

1088 Chapter 25 XML WEB SERVICES

Web services aren’t necessarily text files created with Notepad. You will see in the following section how to create Web services in the environment of Visual Studio, but I wanted to demonstrate how easy it is to build a Web service.

Consuming the Web Service

The Web service is in place, and you have tested it with your browser. The ultimate goal is for an application to consume this Web service, so let’s build one. Actually, we’ll build two applications that consume the same Web service, a Windows app and an ASP Web app.

Start a new Windows Application project and place a Button control on its form. Since VB calculates sums too quickly to notice, let’s use the Add method of the MasteringServices Web service. To access the members of a Web service, you must add a reference to it through the Project Add Web Reference command. When the Add Web Reference dialog box appears, enter the URL of the ASMX file in its Address bar and press Enter. You will see the description of the MasteringServices Web service on the dialog box, as shown in Figure 25.3. At this point, you can click the Add Reference button at the bottom of the window to add the Web service to the current project. This is similar to adding a reference to a regular class.

Figure 25.3

Referencing a Web service in a project

When you first open the Add Web Reference dialog box and before you select a Web service, you’ll see a link that displays the Web services on the localhost (the Web References On Local Web Server link). In addition, you will see two links for the Microsoft’s UDDI directory and Microsoft’s UDDI test directory. Click the link to display the Web references on your local Web server. You will see the names of the Web services you may have already built, but the Mastering service won’t be listed.

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

ASP.NET WEB SERVICE PROJECTS 1089

As you can see, each Web service is represented by a .vsdico file. This is called a discovery file and contains information about your service, and this is how clients that connect to your server can find out what services it provides. This file is created automatically by Visual Studio when you create a Web Service project, but we haven’t created this project in VS—we simply creates an ASMX file to the Web server’s root folder. We’ll do so shortly, but in the meantime you can add a reference to the new Web service explicitly. Enter the URL of the Mastering.asmx file in the Address box of the Add Web Reference dialog box. This URL is the following:

http://localhost/mastering.asmx

You will see the names of the two methods in the left pane of the dialog box. Click the Add Reference button to close the dialog box and return to the project.

Then insert the following code in the button’s Click event handler:

Private Sub Button1_Click(ByVal sender As System.Object,_

ByVal e As System.EventArgs) Handles Button1.Click

Dim WS As New localhost.MasteringServices()

MsgBox(WS.Add(43.32, 22.1))

End Sub

You don’t really need an elaborate interface to test the members of the simple Web service. Run the project, click the button, wait, and the sum of the two values should appear on a message box. The delay, which is more than noticeable, is due to the fact that the ASMX file must be compiled and contacted through the HTTP protocol. There’s a lot of overhead, but then again Web services are not usual Classes. If you insert another call to the Add method (or a call to the Multiply method) in the Click event handler, the second call will be serviced immediately, because the class has been compiled and is ready to be used by any client.

ASP.NET Web Service Projects

In this section, we’ll build a slightly more complicated Web service that exposes a single method to calculate monthly payments on a loan. We’ll add some error handling to the method, to make it more robust than the first one. We’ll also use the tools of the IDE to build the new service.

Start a new project and select the ASP.NET Web Service template. Call the new project WSLoan. Notice that, by default, all Web service projects are stored in the localhost virtual folder (this is the root folder of the Web server). Initially, the Designer will add to the project an ASMX file called Service1, a configuration file, and a discovery file. The configuration file contains configuration information for the Web server, and the discovery file (the one with extension .vsdisco) contains information that allows other applications that connect to your server to locate the specific service and see its “contract” (the names and the syntax of its members). The initial configuration of the IDE for an ASP.NET Web service project is shown in Figure 25.4.

The project we’ll build in this section is within this chapter’s folder on the CD. Copy the entire Loan folder in the Web server’s root folder, and then open it with VB.

Ready to build another loan calculator? This example isn’t going to be quite as trivial as you think. You’ll see how you can raise exceptions from within a Web service and catch them in your VB code. Listing 25.2 shows the Loan class’s source code. Right-click the design surface of Service1, select View Code from the context menu, and then enter the listing’s statements in the editor.

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

1090 Chapter 25 XML WEB SERVICES

Figure 25.4

Starting a new Web service project

Listing 25.2: The Loan Web Service

Imports System.Web.Services Public Class Service1

Inherits System.Web.Services.WebService <WebMethod()> _

Public Function Loan(ByVal Amount As Decimal, ByVal Duration As Integer, _ ByVal Rate As Decimal, ByVal PayEarly As Boolean) As Decimal

If Rate < 0 Then

Throw New Exception(“Interest rate can’t be negative!”) End If

If Rate < 1 Then Rate = Rate / 12

Else

Rate = Rate / (12 * 100) End If

Return Pmt(Rate, Duration, Amount, 0, PayEarly) End Function

End Class

The actual project on the CD contains one more method, which will be discussed shortly. The Web service is ready to be tested. Press F5 and Internet Explorer will come up with the

description of the new Web service. Click the Loan hyperlink to test the Loan method. On the page

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

ASP.NET WEB SERVICE PROJECTS 1091

that appears (Figure 25.5), enter the parameters of the loan and click the Invoke button as before. The result for the loan shown in Figure 25.5 is:

<?xml version=”1.0” encoding=”utf-8” ?>

<decimal xmlns=”http://tempuri.org/”>-740.680595446082</decimal>

Figure 25.5

Testing the Loan method of the Service1 Web service

The Web service works; let’s copy it to the Web server so that other applications can use it. Stop the project, and select the Copy Project command in the Project menu. In the subsequent dialog box (see Figure 25.6), specify the Loan folder under the Web server’s root folder and click OK. All the files needed for the discovery and use of the Loan Web service will be copied in the specified folder.

Figure 25.6

Copying a project’s files to the Web server

Now start a new Windows application that will contact the Loan service. The test project on the CD is called TestLoan (unlike the Web Service project, the test project may appear anywhere on your hard disk). Make sure that you change the project type in the New Project dialog box, because

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

1092 Chapter 25 XML WEB SERVICES

the IDE remembers the type of the last project and will create another Web Service project. The test application’s form is shown in Figure 25.7. To make use of the Web service, add a reference to it as explained in the previous example and enter the code of Listing 25.3 behind the Monthly Payment button.

Listing 25.3: Consuming a Web Service from within a Windows Application

Private Sub Button1_Click(ByVal sender As System.Object,_

ByVal e As System.EventArgs) Handles Button1.Click Dim ws As New localhost.Service1()

Dim amount, duration, rate As Decimal Dim payEarly As Boolean

Try

amount = CDec(txtAmount.Text) duration = CInt(txtDuration.Text) rate = CSng(txtRate.Text) payEarly = False

If chkPayEarly.Checked Then payEarly = True Catch DataException As SystemException

MsgBox(DataException.ToString) Exit Sub

End Try Try

txtPayment.Text = -Math.Round(ws.Loan(amount, duration, rate, payEarly), 2) Catch calcException As Exception

MsgBox(calcException.Message) End Try

End Sub

Figure 25.7

The TestLoan application’s form

Run the application and see that it calculates the monthly payments of properly defined loans. Set the interest rate to a negative value, and the exception raised in the Web service’s class will be caught in your VB application. But of course you should improve the exception-handling code; the exception’s message is too lengthy and too technical for the average user (it’s meant to help the developer, not the user). Figure 25.8 shows the error message cause by a negative interest rate. The

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com