Chapter 11: Practical Application of Web Services


The Development Stage

In this stage, the requirements are all gathered. Now it’s a matter of actually implementing the code. The author chose to implement the service in Java for no other reason other than because a choice had to be made.

The Java Web Service

The following Java Web Service is meant for Apache Axis, which may be obvious because of the lack of import statements. All the other implementations covered in this book require import statements, but when you create a Web Service for Axis you just need to put a jws extension on the file and place it in the webapps directory. Remember, you need to make a request to it so Axis compiles it.

The example starts by defining the class and the first method. The method returnUSDollarEquiv takes the country name and the currency amount and converts to the United States currency. It’s simply a long if-then-else statement. The returnForeignEquiv returns the equivalent to U.S. dollars, and the final method, returnCurrencyName, returns the name of the currency of the foreign country.

    public class MoneyExchange {           public double returnUSDollarEquiv           (String countryName, float quantity) {           double totalValue = 0;           //currency values as of 10/5/02          if (countryName.equals("Argentina")) {              totalValue = .2663 * quantity;          } else if (countryName.equals("Australia")) {              totalValue = .54 * quantity;          } else if (countryName.equals("China")) {              totalValue = .128 * quantity;          } else if (countryName.equals("Japan")) {              totalValue = .0081 * quantity;          } else if (countryName.equals("Mexico")) {              totalValue = .0988 * quantity;          } else if (countryName.equals("Swiss")) {              totalValue = .675 * quantity;          } else if (countryName.equals("UK")) {              totalValue = 1.568 * quantity;          } else {              totalValue = -1;          }        return totalValue;        }         public double returnForeignEquiv         (String countryName, float quantity) {           double totalValue = 0;           //currency values as of 10/5/02           if (countryName.equals("Argentina")) {              totalValue = 3.755 * quantity;           } else if (countryName.equals("Australia")) {              totalValue = 1.83 * quantity;           } else if (countryName.equals("China")) {              totalValue = 8.29 * quantity;           } else if (countryName.equals("Japan")) {              totalValue = .0081 * quantity;           } else if (countryName.equals("Mexico")) {              totalValue = 10.12 * quantity;           } else if (countryName.equals("Swiss")) {              totalValue = 1.4782 * quantity;           } else if (countryName.equals("UK")) {              totalValue = .63784 * quantity;           } else {              totalValue = -1;           }           return totalValue;        }        public String returnCurrencyName(String countryName)        {          String name = null;          if (countryName.equals("Argentina")) {             name = "Peso";          } else if (countryName.equals("Australia")) {             name = "Dollar";          } else if (countryName.equals("China")) {             name = "Renminbi";          } else if (countryName.equals("Japan")) {             name = "Yen";          } else if (countryName.equals("Mexico")) {             name = "Peso";          } else if (countryName.equals("Swiss")) {             name = "Franc";          } else if (countryName.equals("UK")) {             name = "Pound";          } else {             name = "No match";          }          return name;        }        }

This is a good example because you need to pass-in values that are floats and strings to the service. You will find that this is a little tricky when you create Web page consumers.

Java Test Client

As discussed in Chapter 8, creating a proxy for a Java Web Service makes the client code cleaner and simpler, and allows you to develop a client quickly. You can use a tool such as WebServiceStudio to test your server, but this tests the service only from the .NET environment. So it is necessary to write a quick client test just to ensure you can connect from Java.

The first step is to generate the proxy with the following commands.

  java org.apache.axis.wsdl.WSDL2Java   http://localhost:8080/axis/MoneyExchange.jws?wsdl

Remember that to use this command, the environment on your PC needs to be configured in such a way that all the libraries in Axis are available in your environment.

When this command executes it generates the following files:

  MoneyExchange.java   MoneyExchangeSoapBindingStub.java   MoneyExchangeService.java   MoneyExchangeServiceLocator.java

MoneyExchange.java shows the methods available from the Money Exchange Web Service. It is simply an interface definition that defines the methods that other classes in this proxy need to utilize such as MoneyExchangeService. Notice that there isn’t any code here that executes. Remember to compile all these classes before trying to use them in client code.

    /**      * MoneyExchange.java      *      * This file was auto-generated from WSDL      * by the Apache Axis WSDL2Java emitter.     */     package localhost;     public interface MoneyExchange extends java.rmi.Remote     {         public java.lang.StringreturnCurrencyName         (java.lang.String countryName) throws         java.rmi.RemoteException;         public double returnForeignEquiv         (java.lang.String countryName, float quantity)          throws java.rmi.RemoteException;          public double returnUSDollarEquiv          (java.lang.String countryName, float quantity)          throws java.rmi.RemoteException;      }

MoneyExchangeService reveals the methods for calling the service encapsulated by the proxy created here.

    /**      * MoneyExchangeService.java      *      * This file was auto-generated from WSDL      * by the Apache Axis WSDL2Java emitter.      */     package localhost;     public interface MoneyExchangeService extends     javax.xml.rpc.Service {        public String getMoneyExchangeAddress();        public localhost.MoneyExchange getMoneyExchange()        throws javax.xml.rpc.ServiceException;       public localhost.MoneyExchange       getMoneyExchange(java.net.URL portAddress)       throws javax.xml.rpc.ServiceException;     }

MoneyExchangeServiceLocator stores the location of the Web Service and then handles any errors if the service can’t be reached. But unlike the comments the generator put in the code state, this is unlikely because you used WSDL that resides at the location of the Web Service. If you can reach that, you can probably reach the service.

     /**      * MoneyExchangeServiceLocator.java      *      * This file was auto-generated from WSDL      * by the Apache Axis WSDL2Java emitter.      */      package localhost;      public class MoneyExchangeServiceLocator extends      org.apache.axis.client.Service      implements localhost.MoneyExchangeService {      // Use to get a proxy class for MoneyExchange      private final java.lang.String MoneyExchange_address =      "http://localhost:8080/axis/MoneyExchange.jws";       public String getMoneyExchangeAddress() {          return MoneyExchange_address;       }       public localhost.MoneyExchange getMoneyExchange()       throws javax.xml.rpc.ServiceException {          java.net.URL endpoint;          try {             endpoint = new             java.net.URL(MoneyExchange_address);          }          catch (java.net.MalformedURLException e) {             return null; // unlikely as URL was validated                          // in WSDL2Java         }         return getMoneyExchange(endpoint);       }       public localhost.MoneyExchange getMoneyExchange       (java.net.URL portAddress) throws        javax.xml.rpc.ServiceException {         try {             return new             localhost.MoneyExchangeSoapBindingStub             (portAddress, this);         }         catch (org.apache.axis.AxisFault e) {             return null; // ???         }       }        /**         * For the given interface, get the stub         *implementation.         * If this service has no port for the given         *interface,         * then ServiceException is thrown.         */         public java.rmi.Remote getPort        (Class serviceEndpointInterface) throws         javax.xml.rpc.ServiceException {         try {             if            (localhost.MoneyExchange.class.isAssignableFrom            (serviceEndpointInterface)) {                 return new                 localhost.MoneyExchangeSoapBindingStub                 (new java.net.URL(MoneyExchange_address),                 this);             }         }         catch (Throwable t) {             throw new javax.xml.rpc.ServiceException(t);         }         throw new javax.xml.rpc.ServiceException        ("There is no stub implementation for the interface"         +(serviceEndpointInterface == null ? "null" :           serviceEndpointInterface.getName()));         }        }

MoneyExchangeSoapBindingStub.java contains the actual client code. Look toward the bottom and you’ll find client code just like that was written in Chapters 7 and 8. Except this time the proxy generator created it for you. If you look at the proxy code carefully, you’ll notice that it is much like the WSDL XML in some ways. It starts out by defining each of the details of the service and works its way down to the actual call.

    /**      * MoneyExchangeSoapBindingStub.java      *      * This file was auto-generated from WSDL      * by the Apache Axis WSDL2Java emitter.      */      package localhost;      public class MoneyExchangeSoapBindingStub extends      org.apache.axis.client.Stub implements      localhost.MoneyExchange {     private java.util.Vector cachedSerClasses = new     java.util.Vector();     private java.util.Vector cachedSerQNames = new     java.util.Vector();     private java.util.Vector cachedSerFactories = new     java.util.Vector();     private java.util.Vector cachedDeserFactories = new     java.util.Vector();     public MoneyExchangeSoapBindingStub() throws     org.apache.axis.AxisFault {          this(null);     }     public MoneyExchangeSoapBindingStub    (java.net.URL endpointURL, javax.xml.rpc.Service     service)     throws org.apache.axis.AxisFault {        this(service);        super.cachedEndpoint = endpointURL;     }     public     MoneyExchangeSoapBindingStub     (javax.xml.rpc.Service service) throws      org.apache.axis.AxisFault {         try {             if (service == null) {                 super.service = new                 org.apache.axis.client.Service();             } else {                 super.service = service;             }         }         catch(java.lang.Exception t) {             throw org.apache.axis.AxisFault.makeFault(t);         }     }     private org.apache.axis.client.Call createCall() throws      java.rmi.RemoteException {         try {             org.apache.axis.client.Call call =             (org.apache.axis.client.Call)             super.service.createCall();             if (super.maintainSessionSet) {             call.setMaintainSession(super.maintainSession);             }             if (super.cachedUsername != null) {                call.setUsername(super.cachedUsername);             }             if (super.cachedPassword != null) {                call.setPassword(super.cachedPassword);             }             if (super.cachedEndpoint != null) {                call.setTargetEndpointAddress               (super.cachedEndpoint);             }             if (super.cachedTimeout != null) {                call.setTimeout(super.cachedTimeout);             }             java.util.Enumeration keys =             super.cachedProperties.keys();             while (keys.hasMoreElements()) {                 String key = (String)                      keys.nextElement();                 if(call.isPropertySupported(key))                     call.setProperty(key,                     super.cachedProperties.get(key));                 else                     call.setScopedProperty(key,                     super.cachedProperties.get(key));             }             // All the type mapping information is             // registered             // when the first call is made.             // The type mapping information is             // actually registered in             // the TypeMappingRegistry of the service,             // which             // is the reason why registration is only             // needed for the first call.             synchronized (this) {                 if (firstCall()) {                  // must set encoding style before                  registering serializers                  call.setEncodingStyle                 (org.apache.axis.Constants.URI_SOAP11_ENC);                     for (int i = 0; i <                        cachedSerFactories.size(); ++i) {                        Class cls = (Class)                        cachedSerClasses.get(i);                        javax.xml.namespace.QName qName =                        (javax.xml.namespace.QName)                         cachedSerQNames.get(i);                         Class sf = (Class)                           cachedSerFactories.get(i);                         Class df = (Class)                         cachedDeserFactories.get(i);                         call.registerTypeMapping                        (cls, qName, sf, df, false);                     }                 }             }             return call;         }         catch (Throwable t) {             throw new org.apache.axis.AxisFault             ("Failure trying to get the Call object", t);         }     }         public java.lang.String         returnCurrencyName(java.lang.String countryName)         throws java.rmi.RemoteException{         if (super.cachedEndpoint == null) {             throw new             org.apache.axis.NoEndPointException();         }         org.apache.axis.client.Call call = createCall();         javax.xml.namespace.QName p0QName = new         javax.xml.namespace.QName("", "countryName");         call.addParameter         (p0QName, new javax.xml.namespace.Qname         ("http://www.w3.org/2001/XMLSchema", "string"),         java.lang.String.class,         javax.xml.rpc.ParameterMode.IN);         call.setReturnType(new javax.xml.namespace.Qname         ("http://www.w3.org/2001/XMLSchema", "string"));         call.setUseSOAPAction(true);         call.setSOAPActionURI("");         call.setOperationStyle("rpc");         call.setOperationName         (new javax.xml.namespace.Qname         ("http://localhost:8080/axis/MoneyExchange.jws",          "returnCurrencyName"));         Object resp = call.invoke        (new Object[] {countryName});         if (resp instanceof java.rmi.RemoteException) {             throw (java.rmi.RemoteException)resp;         }         else {             try {                 return (java.lang.String) resp;             } catch (java.lang.Exception e) {               return (java.lang.String)               org.apache.axis.utils.JavaUtils.convert              (resp, java.lang.String.class);             }           }         }                 /* And much more generated code */ 

The simple Java client imports the proxy code, and then creates a location object which stores information about where the Web Service resides. Then creating a MoneyExchange object involves calling the getMoneyExchange method from the location object.

  import localhost.*;     public class TestMoneyExchange {       public static void main(String [] args)       throws Exception {       //init value passed back from service       double returnedValue = 0;       String currencyName = null;       MoneyExchangeServiceLocator myMoneyExchangeLocation =       new MoneyExchangeServiceLocator();       localhost.MoneyExchange myMoneyExchange =       myMoneyExchangeLocation.getMoneyExchange();       //get currency name       currencyName = myMoneyExchange.returnCurrencyName       ("Japan");       System.out.println("The name of the currency is:"       + currencyName);       //get equiv       returnedValue = myMoneyExchange.returnForeignEquiv       ("Japan",1000);        System.out.println("The Japanese Equivalent is:"        + returnedValue);        //get other equiv        returnedValue =        myMoneyExchange.returnUSDollarEquiv("Japan",1000);        System.out.println("The American Equivalent is:"        + returnedValue);       }     } 

Remember this test client just ensures that you can test the Web Service from the desired platform. There needs to be more extensive testing of the Web Service, and this gets covered in greater detail later in the chapter.

JSP Consumer

JSP provides an easier way than a servlet to integrate Java code into a Web page because code mixes with the HTML elements. This way a developer does not need to be involved to change something simple like a title. Java code can be abstracted into a JSP custom tag or simply coded in a Scriptlet where code appears between <% %> elements in a page.

In this first JSP example, the page starts out by importing the classes from the package localhost which were created by the WSDL2Java tool. A scriptlet then instantiates the location and the myMoneyExchange objects so the call to the returnCurrencyName method can occur. The name of the currency is then displayed with <%= %> tags so the value of the currencyName variable actually displays in the web page.

Note

Remember that to use the code generated by the WSDL2Java tool, you need to place the Java class files in the web apps WEB-INF/classes directory. This is where Tomcat looks for classes to load when it executes.

    <HTML>     <HEAD>         <TITLE>This is a simple JSP Client</TITLE>     </HEAD>     <BODY>     <!-- import the proxy classes -->     <%@ page import="localhost.*" %>     <%      //init value passed back from service      double returnedValue = 0;      String currencyName = null;      MoneyExchangeServiceLocator myMoneyExchangeLocation =      new MoneyExchangeServiceLocator();      localhost.MoneyExchange myMoneyExchange =      myMoneyExchangeLocation.getMoneyExchange();      //get currency name      currencyName =      myMoneyExchange.returnCurrencyName("Japan");       %>       <h2>          The currency name is <%= currencyName %>       </h2>    </BODY>    </HTML>

The previous example is a simple JSP page that allows you to test the ability to contact the Web Service, but really would be useful to any of your clients who sent you requirements. It doesn’t allow you to choose a particular country to convert to and you can’t specify an amount. The next JSP example takes the functionality one step further by being more interactive.

Again, the first chunk of code imports the libraries you need. Notice that in this example there is an import for java.text.*. This provides the JSP page the ability to format the output of the some of the method calls.

Following the import statement, the code creates several variables so that the form can be processed differently depending on whether the page first loads or receives a request through a Post method. Notice that dollarsConverter receives the value of the getParameter method of the request object. The first time the page loads this won’t have a value, so the code that appears right after the variable definitions will not execute.

The next chunk of code again looks to see if data has been submitted to the form, and if it has it reads the countryName value from the request and coverts the dollarsConverter variable to the float variable dollars using methods from the Float class.

An if statement then checks to ensure that both variables that need to be submitted by the form, countryName and dollars, have value before executing the code after the conditional. This prevents errors that occur when the methods to the service get called before the variables they pass get populated. If the variables do indeed have value, the calls are made to the Web Service just like in the simple Java client shown earlier, and the values are then displayed in the HTML that follows.

Then there is a form tag whose action sends the information back to this JSP page for processing and display. The remaining HTML elements set up a text box and a select HTML tags so the user can select country and enter the quantity of currency they wish to convert.

    <HTML>     <HEAD>         <TITLE>Convert to Other Currency</TITLE>     </HEAD>     <BODY>     <%@ page import="localhost.*, java.text.*" %>     <!-- The following handles the response -->     <!-- Get parameters passed from get or post -->     <%     String dollarsConverter = null;     dollarsConverter = request.getParameter("dollars");     String countryName = null;     String currencyName = null;     float dollars = 0;     if(dollarsConverter != null)  {         countryName = request.getParameter("countryName");         dollars =         Float.valueOf(dollarsConverter).floatValue();     }     %>     <!-- Call methods with values passed in from form -->     <%      if ((countryName != null) && (dollars > 0)) {          double foreignValue = 0;      MoneyExchangeServiceLocator myMoneyExchangeLocation      = new MoneyExchangeServiceLocator();      localhost.MoneyExchange myMoneyExchange      = myMoneyExchangeLocation.getMoneyExchange();      //get currency name      currencyName =      myMoneyExchange.returnCurrencyName(countryName);      foreignValue =        myMoneyExchange.returnForeignEquiv        (countryName,dollars);      String formattedForeignValue =        NumberFormat.getCurrencyInstance()        format(foreignValue);      %>      <h3>         The equivalent to &nbsp;<%= dollars %> US Dollars         in &nbsp;<%= currencyName %> is &nbsp;         <%= formattedForeignValue %>.      </h3>      <% } %>      <!--notice that form sends data to itself -->      <form method="get" action="test2.jsp">      <h2>          Please enter the amount of dollars and the          country's currency you wish to convert to.      </h2>       Dollar amount:       <input type="text" name="dollars"><br>       Select a country:       <select name = "countryName">          <option></option>          <option>Argentina</option>          <option>Australia</option>          <option>China</option>          <option>Mexico</option>          <option>Swiss</option>          <option>UK</option>       </select>       <p>       <input type="submit"><br>      </form>      </BODY>      </HTML> 

This example provides more of a real-world example of applying a Web Service. This page actually takes and processes information from the user that is then sent to the Web Service. Figure 11.1 shows how this form appears in Internet Explorer.

click to expand
Figure 11.1: The JSP consumer with the drop-down list.

This is the type of form your users are likely to demand for an interface to a Web Service.

C# Test Client

Originally the Web Service in this chapter was only going to support JSP pages, but in the ever-changing world of Information Technology, “management” decided that the monetary conversion Web Service needs to be compatible with .NET. Even though Apache Axis possesses tools that generate WSDL that is reliably compatible with .NET, you still need to test each service from your desired language within .NET. This ensures that your services are truly cross platform compatible during your development stage, prevents you from discovering any glitches during deployment, and ensures that some client code actually works.

Just like with the Java code, Visual Studio.NET or the .NET Framework SDK creates a proxy for each Web Service contacted. The following C# code is the proxy for the MoneyExchange Java Web Service. If you examine the code closely, you’ll find that it does many of the same things that the Java proxy code does. It contains information about the Web Service location and the types of values that need to be passed back and forth, and also generates the appropriate namespace for the client to be able to call the service. The proxy Microsoft generates, however, is much more succinct than the Java proxy.

Note

It is not coincidence that the proxy code and the WSDL that both .NET and Axis Web Services generate are similar. Microsoft and IBM (remember that IBM started the Axis project as the “Web Service Toolkit”) work very closely together on not only creating Web Service software but also toward creating standards they find useful. Remember that SOAP was originally an intellectual product of Microsoft until it was released to the standards committees.

    //------------------------------------------------     // <autogenerated>     //     This code was generated by a tool.     //     Runtime Version: 1.0.3705.0     //     //     Changes to this file may cause incorrect     //     behavior and will be lost if     //     the code is regenerated.     // </autogenerated>     //------------------------------------------------     //     // Assembly WebServiceStudio Version = 1.0.3705.0     //     using System.Diagnostics;     using System.Xml.Serialization;     using System;     using System.Web.Services.Protocols;     using System.ComponentModel;     using System.Web.Services;     // <remarks/>     [System.Diagnostics.DebuggerStepThroughAttribute()]     [System.ComponentModel.DesignerCategoryAttribute     ("code")]     [System.Web.Services.WebServiceBindingAttribute(        Name="MoneyExchangeSoapBinding",        Namespace=        "http://localhost:8080/axis/MoneyExchange.jws")]    public class MoneyExchangeService :    System.Web.Services.Protocols.SoapHttpClientProtocol {     /// <remarks/>     public MoneyExchangeService() {         this.Url =         "http://localhost:8080/axis/MoneyExchange.jws";     }     /// <remarks/>     [System.Web.Services.Protocols.SoapRpcMethodAttribute     ("",       RequestNamespace=       "http://localhost:8080/axis/MoneyExchange.jws",       ResponseNamespace=       "http://localhost:8080/axis/MoneyExchange.jws")]     [return:     System.Xml.Serialization.SoapElementAttribute     ("return")]     public string returnCurrencyName(string countryName) {         object[] results =         this.Invoke("returnCurrencyName",                     new object[] {                     countryName});         return ((string)(results[0]));     }     /// <remarks/>     public System.IAsyncResult     BeginreturnCurrencyName(string countryName,     System.AsyncCallback callback, object asyncState) {         return this.BeginInvoke        ("returnCurrencyName", new object[] {          countryName}, callback, asyncState);     }     /// <remarks/>     public string EndreturnCurrencyName    (System.IAsyncResult asyncResult) {         object[] results = this.EndInvoke(asyncResult);         return ((string)(results[0]));     }     /// <remarks/>     [System.Web.Services.Protocols.SoapRpcMethodAttribute     ("", RequestNamespace=     "http://localhost:8080/axis/MoneyExchange.jws",     ResponseNamespace=     "http://localhost:8080/axis/MoneyExchange.jws")]     [return: System.Xml.Serialization.SoapElementAttribute     ("return")]      public System.Double returnForeignEquiv      (string countryName, System.Single quantity) {         object[] results =         this.Invoke("returnForeignEquiv", new object[] {                     countryName, quantity});         return ((System.Double)(results[0]));       }     /// <remarks/>     public System.IAsyncResult    BeginreturnForeignEquiv(string countryName,                            System.Single quantity,                            System.AsyncCallback callback,                            object asyncState) {         return this.BeginInvoke        ("returnForeignEquiv", new object[] {            countryName,               quantity}, callback, asyncState);     }     /// <remarks/>     public System.Double     EndreturnForeignEquiv(System.IAsyncResult asyncResult)      {         object[] results = this.EndInvoke(asyncResult);         return ((System.Double)(results[0]));     }     /// <remarks/>     [System.Web.Services.Protocols.SoapRpcMethodAttribute     ("",     RequestNamespace=     "http://localhost:8080/axis/MoneyExchange.jws",     ResponseNamespace=     "http://localhost:8080/axis/MoneyExchange.jws")]     [return:     System.Xml.Serialization.SoapElementAttribute     ("return")]     public System.Double returnUSDollarEquiv     (string countryName, System.Single quantity) {         object[] results = t         this.Invoke("returnUSDollarEquiv", new object[] {                     countryName,quantity});         return ((System.Double)(results[0]));     }     /// <remarks/>     public System.IAsyncResult     BeginreturnUSDollarEquiv     (string countryName,      System.Single quantity,      System.AsyncCallback callback, object asyncState) {         return         this.BeginInvoke("returnUSDollarEquiv",         new object[] {         countryName,quantity}, callback, asyncState);     }     /// <remarks/>     public System.Double     EndreturnUSDollarEquiv(System.IAsyncResult asyncResult)     {         object[] results = this.EndInvoke(asyncResult);         return ((System.Double)(results[0]));     }    }

Now that the proxy is part of your Visual Studio.NET project, you can create a simple test client that ensures you can call the methods from the Java Web Service. Note that in the following C# example that you are not required to create a location object first and then call the service like you did with Java. Microsoft hides that detail from you.

    using System;     namespace TestJavaMoneyService     {      class Class1      {      [STAThread]      static void Main(string[] args)      {      String currencyName = null;      double returnedValue = 0;       localhost.MoneyExchangeService myMoneyExchange =      new localhost.MoneyExchangeService();      currencyName =      myMoneyExchange.returnCurrencyName("Argentina");      Console.WriteLine      ("The name of the money in Argentina:"       + currencyName);      returnedValue =      myMoneyExchange.returnForeignEquiv("Argentina",12322);      Console.WriteLine      ("The Argentinian equivalent is: " + returnedValue);      returnedValue =      myMoneyExchange.returnUSDollarEquiv("Argentina",433);      Console.WriteLine      ("The Argentinian equivalent is: " + returnedValue);       }      }     }

This C# Client tests each of the three methods available through the Web Service. It is not an extensive test but does provide the knowledge that the Web Service is available.

ASP.NET Consumer

The following ASP.NET example sets up a simple Web page that makes a call to the Web Service with a value that’s hard-coded in the form. As with all the other examples, this example checks to see if you can actually call the Web Service within the ASP.NET page. Also, this example assumes that you have already added a Web reference in Visual Studio.NET in order to create the proxy.

The import statement in this example makes the proxy code to the Web Service available. The page definition describes which .NET language this page uses and information describing where the code resides and any inheritance path.

Then, in between the opening and closing script tag, lies a method that executes when a button has the method Submit_Click associated with it. Remember that you need the runat="server" attribute of the script tag in order for the code to execute. Otherwise the code gets sent to the browser as client code, and the browser just ignores because it doesn’t know what to do with the information. The code then creates a myExchange object which represents the MoneyExchange Web Service and calls the returnCurrencyName method. The string variable currencyName contains the return value and is displayed by sending the value to the Text attribute of the asp:label message.

    <%@ Import         Namespace="MoneyConversionClient.localhost"%>     <%@ Page language="c#"              Codebehind="WebForm1.aspx.cs"              AutoEventWireup="false"              Inherits="MoneyConversionClient.WebForm1" %>     <html>       <head>            <title>Money Exchange Client</title>       </head>       <body MS_POSITIONING="GridLayout">            <script runat="server">                protected void Submit_Click(                Object Src, EventArgs E){                     MoneyExchangeService myExchange =                   new MoneyExchangeService();                   String currencyName =                   myExchange.returnCurrencyName("Swiss");                     Message.Text = currencyName;                 }             </script>             <form  method="post" runat="server">             <p>             The currency name is:&nbsp;             <asp:Label  Runat="server" /><br>             </p>             <input type="submit"              value="get money name"              onserverclick="Submit_Click"              runat="server"                            NAME="Submit1"/>             </form>         </body>     </html>

Just as with the JSP examples, the first ASP.NET example ensures that you can actually call the service whereas this one will actually allow someone to enter values and receive useful information about exchange rates back.

In the next ASP.NET code example, the attributes of the import and page tags remain the same. The method within the script tags, Submit_Click, changes in this case. Instead of just containing a hard-coded value, the code actually looks at a text box and an asp:ListBox to get information to pass to the methods. Once the methods are called, the return values are displayed within the HTML.

    <%@ Import     Namespace="MoneyConversionClient.localhost" %>    <%@ Page language="c#"             Codebehind="WebForm1.aspx.cs"             AutoEventWireup="false"             Inherits="MoneyConversionClient.WebForm1" %>     <html>          <head>               <title>Money Exchange Client</title>          </head>      <body MS_POSITIONING="GridLayout">           <script runat="server">               protected void Submit_Click               (Object Src, EventArgs E){                 String currencyName = null;                 String foreignValue = null;                 String myDollars = dollars.Text;                 String myCountryName =                 countryName.SelectedItem.Text;                 float myFloatDollars =                 float.Parse(myDollars);                 MoneyExchangeService myExchange                 = new MoneyExchangeService();                 currencyName =myExchange.returnCurrencyName                 (myCountryName);                 foreignValue =                 myExchange.returnForeignEquiv                 (myCountryName,myFloatDollars).ToString();                 currencyNameLabel.Text = currencyName;                 dollars.Text = myFloatDollars.ToString();                 foreignValueLabel.Text = foreignValue;               }           </script>           <form  method="post" runat="server">           <p>           The equivalent to &nbsp;          <asp:Label  Runat="server" />           US Dollars in &nbsp;          <asp:Label                      Runat="server" />           is &nbsp;           <asp:Label                       Runat="server" />.           </p>           <h2>               Please enter the amount of dollars and the               country's currency you wish to convert to.           </h2>         Dollar amount:         <input type="text" name="dollars"><br>            Select a country:         <asp:ListBox id = "countryName" Runat=server>           <asp:ListItem></asp:ListItem>           <asp:ListItem>Argentina</asp:ListItem>           <asp:ListItem>Australia</asp:ListItem>           <asp:ListItem>China</asp:ListItem>           <asp:ListItem>Mexico</asp:ListItem>           <asp:ListItem>Swiss</asp:ListItem>           <asp:ListItem>UK</asp:ListItem>        </asp:ListBox>        <p>               <input type="submit"              value="get money name"              onserverclick="Submit_Click"              runat="server"                            NAME="Submit1"/>           </form>          </body>       </html>

Figure 11.2 contains the output of this form once some values have been input and the “Submit” button has been clicked.

click to expand
Figure 11.2: The ASP.NET client form.

Note

This ASP.NET note example uses the “Parse” method of the float object. This takes a string read-in from the form and converts it into a float value. If you experience problems with this method or you can’t compile the page due to mysterious errors on this line, you may need to download VS.NET Service Pack 2.




Cross-Platform Web Services Using C# and Java
Cross-Platform Web Services Using C# & JAVA (Charles River Media Internet & Web Design)
ISBN: 1584502622
EAN: 2147483647
Year: 2005
Pages: 128

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