Consuming a Web Service

   

Consuming a Web Service is easy. Visual Studio automates the process of querying a Web Service to discover the public methods , the arguments that they take, and the data that they return. Visual Studio queries Web Services, and then creates a class, which you can easily use in your applications.

To create a reference to a Web Service in a Web application, go to the Solution Explorer window and right-click on the name of the application. A pop-up menu appears. Select Add Web Reference from the pop-up menu. A dialog box entitled Add Web Reference appears. In the address field, type the address of the Web Service. For instance, if you have a Web Service that is located on a server somewhere, you type in the name of the domain, then the path to the Web Service (which will be an .asmx file). You must also add '?WSDL' so that the Web Service knows it must return the WSDL contract for this Web Service.

The Service help page also provides a link to the Web Service's service description, which is a formal definition of the Web Service's capabilities. The service description is a document that uses the Web Service Description Language (WSDL) grammar. The service description defines the contract for the message formats that clients need to follow when exchanging messages with the Web Service.

As a matter of fact, I have a Web Service that you can use right now from your application. If you go to the Add Web Reference dialog box and type http://www.UsingAsp.net/TipOfDay/WebService1.asmx?SDL, you will get a reference to the TipOfDay Web Service that I showed you in the "A Health Tip Web Service" section. When the reference is retrieved in the left pane of the Add Web Reference dialog box, you can see the service description. In the right pane is a link that you can click if you want to view the contract. To use this Web Service, all you need to do is click on the Add Reference button and the class is created. With it you can use this Web Service.

The class for this Web reference can be found in the Solution Explorer window. First, find the Web References folder in the Solution Explorer window. Then open up the net.UsingASP.www icon. You will see a reference.map file and a WebService1.sdl file. Not shown is the source code file that contains the class. I am not sure why Visual Studio does not show this in the list of files, but I have the feeling by the final release of Visual Studio.NET that you will be able to see the VB or C# source code file for the class that was added. Figure 14.3 shows a Web project in which a Web reference is being added.

Figure 14.3. To add a Web Reference, you must query it for a contract.

graphics/14fig03.gif

The source code for the class that is added is interesting. It is not necessary however, for you ever even look at it. But for curiosity , to see what is contained in the file, you may want to. Listing 14.5 contains the source code for the wrapper class for the Multiply Web Service. This particular Web service resides on my local computer.

Listing 14.5 The Wrapper Class for Invoking the Multiply Web Service
 namespace WebServiceConsumer.localhost {      using System.Xml.Serialization;      using System.Web.Services.Protocols;      using System.Web.Services;      public class WebService1 : System.Web.Services.Protocols.SoapClientProtocol {          public WebService1() {              this.Url = "http://localhost/Simple/WebService1.asmx";          }          [System.Web.Services.Protocols.SoapMethodAttribute ("http://tempuri.org/ graphics/ccc.gif Multiply")]          public int Multiply( int nFirst,  int nSecond) {              object[] results = this.Invoke("Multiply", new object[] {nFirst,                          nSecond});              return (int)(results[0]);          }          public System.IAsyncResult BeginMultiply(int nFirst, int nSecond, System. graphics/ccc.gif AsyncCallback callback, object asyncState) {              return this.BeginInvoke("Multiply", new object[] {nFirst,                          nSecond}, callback, asyncState);          }          public int EndMultiply(System.IAsyncResult asyncResult) {              object[] results = this.EndInvoke(asyncResult);              return (int)(results[0]);          }      }  } 

I have created an example that uses the Multiply Web Service. It can be found on www.UsingASP.net. To get to it, select the Chapter Examples link from the main page, go to Chapter 14, and then select the Multiply example. You can see a Web page, as shown in Figure 14.4. It enables you to enter your first and second numbers ”these are numbers of your choice that will be multiplied. (As you can see in the figure, I have entered 6 and 17.) Then you can click on the Use the Simple Service button to see the answer.

Figure 14.4. The Multiply Web Service multiplies two numbers.

graphics/14fig04.gif

The source code that invokes the Web Service is very simple. Actually, the hard part was adding the service to the Visual Studio project. The easy part is creating a class and invoking it from the code. You can see in Listing 14.6 that the code to invoke the multiply method is very simple. I instantiate the class, then I call the method, and finally I display the result to the label.

Listing 14.6 The Code That Responds to a Button Click and Calls the Remote Multiply() Method
 public void Button1_Click(object sender, EventArgs e)  {      WebServiceConsumer.localhost.WebService1 simple = new WebServiceConsumer.localhost. graphics/ccc.gif WebService1();      int nAnswer = simple.Multiply( TextBox2.Text.ToInt32(),          TextBox3.Text.ToInt32() );      Label1.Text = "The answer is " + nAnswer;  } 

The same Web page that I used to demonstrate the Multiply service is used to demonstrate the TipOfTheDay service. To get a health tip, the user clicks the Use the Health Tip Service button. The health tip that is returned from the Web Service is then displayed in the label at the top of the Web page. You can see the health tip displayed in the Web page in Figure 14.5. The source code that consumes the health tip service is even easier than the source code that consumed the Multiply() method.

Figure 14.5. The Health Tip service returns a health tip for children.

graphics/14fig05.gif

As you can see in Listing 14.7, I instantiated the Web Service class, and then I assigned the label text to whatever the service returned after calling the TipOfTheDay method.

Listing 14.7 The Code the Responds to a Button Click and Consumes the TipOfTheDay() Method
 public void Button2_Click(object sender, EventArgs e)  {      WebServiceConsumer.localhost1.WebService1 tip = new WebServiceConsumer.localhost1. graphics/ccc.gif WebService1();      Label1.Text = tip.TipOfTheDay();  } 

The Credit Card Validator service that you saw earlier can be seen running in Figure 14.6. This uses the same Web page that I used to test and demonstrate the Health Tip service and the Multiply service. To test the credit card service, the user types in a card number and then clicks on the Use the Credit Card Validator Service button. The result of the credit card validation is displayed in a label at the top of the Web page.

Figure 14.6. The Credit Card Validator service determines whether a credit card number is valid.

graphics/14fig06.gif

Note

If interested in the two Web Services, use the following URLs:

http://www.usingasp.net/Chapter14/TipOfDay/Service1.asmx?WSDL

http://www.usingasp.net/Chapter14/CardService/Service1.asmx?WSDL


I displayed this at VSLive! in Australia. It was easy enough to show them a credit card number that was invalid. But for some reason I had no luck in getting anyone from the audience to voluntarily let me use their credit card number to demonstrate what this example looks like with a valid credit card number.

Calling the Credit Card Validator service requires a bit more code than the Multiply or Health Tip services did. As you can see in Listing 14.8, the first thing I did was instantiate the service class that was added by Visual Studio.NET. The next thing I did was obtain the result from the CardType() method. Of course I had to pass the credit card string to the CardType() method. Then, if the result is less than 0, the label advises the user that the credit card number was invalid. Otherwise, the label says that the credit card number entered was valid.

Listing 14.8 The Code Responds to a Button Click and then Calls the CardType() Method
 public void Button3_Click(object sender, EventArgs e)  {      WebServiceConsumer.localhost2.WebService1 validator = new WebServiceConsumer. graphics/ccc.gif localhost2.WebService1();      int nResult = validator.CardType( TextBox1.Text );      Label1.Text = "The credit card number you entered is valid.";      if( nResult < 0 )      {          Label1.Text = "The credit card number you entered is invalid.";      }  } 
   


Special Edition Using ASP. NET
Special Edition Using ASP.Net
ISBN: 0789725606
EAN: 2147483647
Year: 2002
Pages: 233

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