Consume Webservices Using Javascript

  • July 2020
  • PDF

This document was uploaded by user and they confirmed that they have the permission to share it. If you are author or own the copyright of this book, please report to us by using this DMCA report form. Report DMCA


Overview

Download & View Consume Webservices Using Javascript as PDF for free.

More details

  • Words: 2,887
  • Pages: 8
To consume a Web service, we must be able to do the following: 1. 2. 3. 4. 5.

Find the Web service Obtain its WSDL service contract Generate a proxy class with which to call the Web service Create an instance of the proxy class Call the methods exposed by the proxy

Obtaining the WSDL document We have two choices for obtaining the WSDL document that describes our CTemp Web service. We can use the .NET disco tool or the Internet Explorer Web browser. Each of these methods has specific strengths and weaknesses. Your choice and the level of success you may experience will most likely depend on characteristics of the Web service you wish to consume. The .NET disco tool is a good choice in the following situations: § You know at least the URL of the target Web server on which the Web service is deployed. § Web service discovery has been enabled through the use of one or more DISCO documents on the target Web server. Internet Explorer is a good choice in the following situations: § You know the exact URL of the Web service entry point. § The Web service is an ASP.NET Web service (which implies that it supports discovery of the WSDL document via a properly formatted HTTP request, or obtained via the Web service help page). § Web service discovery via disco is not possible because no DISCO documents are available for the service. To obtain the WSDL document for our CTemp Web service, we would specify the following URL in the Address bar of our Web browser: http://localhost/CTemp/CTemp.asmx?WSDL This returns the WSDL for the CTemp Web service to your browser in XML format. You can then use the File ® Save As option in Internet Explorer to save the WSDL to a file in your consumer application virtual directory. To obtain the WSDL document for the CTemp Web service using the .NET Framework disco tool, follow these steps: 1. Open a command prompt window. 2. At the command prompt, change the current directory to your Web application folder, as in "cd c:\inetpub\wwwroot\CTempClient," and press Enter. 3. At the command prompt, type "disco http://localhost/ctemp/ctemp.asmx" and press Enter. Note If you do not have the path to the .NET Framework SDK in your default path, you will have to include the complete path to the disco tool. By default, the disco tool is located at Program Files\Microsoft .NET\FrameworkSDK\Bin\disco.exe. SANjEEV KUMAR [MCA, ADCA, BCA, MCP]

January 2008

Tip You can type "disco /?" at the command prompt to obtain help on the command syntax and available options for the disco tool. Executing the disco tool with default options results in the creation of three files in the current directory. Now that we have the WSDL document, we can create a proxy class that can be used by our consumer application to make method calls on the CTemp Web service. Of course, if you are using Visual Studio, you can use the Add Web Reference dialog box to locate and create references to Web services. Add Web Reference dialog box within Visual Studio automatically create a Web service proxy class that can be used to interact with the service.

Generating the proxy class The proxy takes care of preparing the XML based on the parameters you pass, and it carefully translates the XML response it receives into the .NET type specified by the proxy method. The WSDL document describes the capabilities of the CTemp Web service in terms of the data types, inputs, outputs, and message exchange patterns that it supports. In effect, this is a contract between the Web service and the consumer that documents what the Web service will provide and how it will deliver it when supplied with properly constructed messages. Wsdl tool that we can use to generate proxy classes from these WSDL documents. Using this tool, we can generate an ASP.NET Web service proxy class in any of the supported .NET languages when we supply the tool with a properly formatted WSDL document as input. The proxy class can then be used by our consumer application to make requests against the Web service using a local class that hides all the low-level details of the communication that takes place using HTTP and SOAP. To generate a proxy class for the CTemp Web service from the WSDL document, follow these steps: 1. Open a command prompt window. 2. At the command prompt, change the current directory to your Web application folder, as in "cd c:\inetpub\wwwroot\CtempClient." 3. At the command prompt, type "wsdl /l:vb /o:CTempProxy.vb CTemp.wsdl" and press Enter.

/n:CTempProxy

Tip You can type "wsdl /?" at the command prompt to obtain help on the command syntax and available options for the wsdl tool. Not also that you must specify the entire path to the wsdl tool if you have not added its path to your PATH environment variable. The /l (lowercase L) option specifies the desired source language for the proxy class, such as VB (Visual Basic), CS (C#), or JS (JavaScript). The /o (lowercase O) option specifies the name to be given the proxy class file. If you prefer to use C# for your proxy class, simply substitute CS for VB with the /l option. The /n option specifies the namespace to be assigned to the proxy. This will be useful when we reference the namespace in our client code using ASP.NET's @Import directive. Given a valid proxy class, we can now compile this class into a .NET assembly using the appropriate language compiler. Execute the following command, appropriate for the language you are using. SANjEEV KUMAR [MCA, ADCA, BCA, MCP]

January 2008

VB.NET: vbc /t:library /out:bin\CTempProxy.dll /r:System.Web.Services.dll /r:System.XML.dll /r:System.dll CTempProxy.vb C#: csc /t:library /out:bin\CTempProxy.dll /r:System.Web.Services.dll /r:System.XML.dll /r:System.dll CtempProxy.cs Tip The .NET compilers are installed in WINNT\System32\Microsoft.NET\version by default. To reference them without a complete path prefix, you might wish to add this path to the system PATH environment variable on your computer. This also simplifies references to .NET assemblies using the /r option. This command will compile the CTemp Web service proxy class into a .NET assembly that we can then reference from our Web Forms client application. The /t:library option specifies that we wish to create a DLL (rather than an executable). The /r option specifies the .NET assemblies that correspond to the .NET namespaces referenced by the proxy class. The /out option saves the assembly in the Web application's .\bin folder.

Creating an instance of the proxy class To call methods of the proxy class that represents the Web service, you must create an instance of the proxy class. creating an instance of a Web service proxy is identical to creating an instance of any other .NET class, The first step we need to complete is to import the namespace of the assembly that contains our CTemp proxy class implementation. Recall that when we generated our proxy class using the wsdl tool, we provided a namespace for the proxy class. using CTempProxy; TempConverter TC = new TempConverter();

Calling the CTemp proxy method txtOutputTemp.Text = Format(TC.CTemp(CType(txtInputTemp.Text, _ Decimal), optFromUnits.SelectedItem.Value, optToUnits.SelectedItem.Value), "Fixed")

Web Services Using JavaScript and .NET There are three steps to consuming the Web service: 1. Create an .aspx page. 2. Add a WebService behavior (HTC file) to the .aspx page using JavaScript. 3. Create a proxy server for the Web service that you created for the client. Add WebService behavior (HTC file) to consumeWebSvcDateTime.aspx using JavaScript This step can be further divided into three steps. a. Copy the HTC file into the Web form project folder. b. Write a script using JavaScript to access the Web service using WebService behavior. c. Modify the HTML on the consumeWebSvcDateTime.aspx page to handle the click event

SANjEEV KUMAR [MCA, ADCA, BCA, MCP]

January 2008

The WebService behavior enables you to make a method call to a Web service using a scripted language. It is a reusable DHTML component that uses Web services by communicating over HTTP using SOAP The WebService behavior is implemented with an HTML Component (HTC) file as an attached behavior, so it can be used in Microsoft Internet Explorer 5 and later versions. Thus, to use a WebService behavior, you need to have the HTC file in the project's folder. To use the behavior in your consumeWebSvcDateTime.aspx page, download the WebService HTC File and copy it to your Web form project's folder. You will be able to download HTC file at this link: http://msdn.microsoft.com/downloads/samples/internet/behaviors/library/webservice/default.asp. To invoke the "date and time" method, you will have to attach the WebService.HTC file to a (or any other valid element) DIV element in consumeWebSvcDateTime.aspx. It is also necessary to set the id attribute so that this element can be easily referenced in script, as shown in the following example.
The behavior can also be applied using other variations of Cascading Style Sheets (CSS) style sheet syntax. The WebService behavior provides the useService method to map the Web Service URL to a FriendlyName, which is passed as a parameter to the method. After this method has been called, the friendly name for the Web Service can be used directly in script to reference the Web Service URL, which helps to keep the script code readable and simple. The basic syntax of the useService method is as follows: id.useService("ServiceURL","FriendlyName"); The id that the useService method is applied on is the value of the id attribute specified on the HTML tag to which the behavior is attached. Based on the preceding behavior attachment sample, the following code example shows how the useService method can be coded. service.useService("/services/math.asmx?WSDL","MyMath"); The WSDL file consists of XML file with a .xsd file extension. To ensure that the useService method works correctly, it should be placed inside a handler for the onload event, so that the first attempt to call a method in the behavior only occurs after the page has been downloaded and parsed. The code placed inside this handler may define friendly names for one or more Web Services. The following sample shows how this can be accomplished. <script language="JavaScript"> function init() { service.useService("/services/math.asmx?WSDL","MyMath"); service.useService("/loaninfo.asmx?WSDL","loanInfo"); service.useService("/financebroker.asmx?WSDL","finance"); }


SANjEEV KUMAR [MCA, ADCA, BCA, MCP]

January 2008

Note The current implementation of the WebService behavior requires that the Web Services being referenced directly by the useService method reside on the same domain as the Web server that delivers the Web page. When the useService method is called, the behavior downloads the SDL description for the Web Service, so that it has all the information it requires to construct the appropriate method calls. Because the friendly names are defined before making calls to useService, performance is somewhat improved when the method call is actually made, because by that time the behavior has already obtained the Web Service description. It is quite possible that two different Web Services could each have the same name, even though the URL is unique. Indeed, it is certain that this will commonly occur once a large enough number of Web Services exist. It's also quite possible for such services to have similar classes and methods. The useService method avoids namespace conflicts by specifying a unique friendly name for each service. The callService method can be used to invoke methods. The callService method returns a unique value when it is invoked, so that the returned result can be identified with a specific instance of a method call. The WebService behavior enables both synchronous and asynchronous remote procedure calls to Web Services. By default, the asynchronous mode of remote method invocation is used.The async property of the call object is used to control the mode of invocation. Here's the basic syntax for callService. iCallID = id.FriendlyName.callService([CallbackHandler,] "MethodName", ...);

Param1, Param2,

The callService method has an optional first parameter that specifies a callback handler function to process the results received from the method call. If no callback handler is specified, then the event handler for the onresult event is used. The onresult event is fired by the WebService behavior once the result of the remote call has completed. The callService method has an optional first parameter that specifies a callback handler function to process the results received from the method call. If no callback handler is specified, then the event handler for the onresult event is used. The onresult event is fired by the WebService behavior once the result of the remote call has completed. Continuing with the sample, the following approach can be used to return a unique value from a call to a Web Service method named add. <script language="JavaScript"> var iCallID; iCallID = service.MyMath.callService("add",5,6); Note Because the callService method does not return the result from the add function immediately, call returns a unique identifier that is stored in the variable iCallID in the preceding example. The value of this identifier enables the positive identification of a particular result. In summary, three types of parameters can be specified by call; the first is the Method Name, the second is an optional parameter to specify the name of a callback handler function, and the remaining parameters are passed directly into the method on the Web Service and depend entirely on the method being called. If a more complex data structure needs to be passed to a method, this can be accomplished by specifying an object as one of the parameters. SANjEEV KUMAR [MCA, ADCA, BCA, MCP]

January 2008

Handling Results from WebService Calls The callService method initiates an asynchronous communication between the WebService behavior and the Web Service. Eventually the Web Service responds, or a time-out error occurs in the WebService behavior. In either case, the result of the call should be processed by an event handler or callback function to determine whether an error occurred and to evaluate and interpret the results.

Obtaining Results with the onresult Event When the WebService behavior has received the XML data packets containing the results from a previous call, it fires an onresult event. It will only fire this event if a callback function was not specified in the callService method. The onresult event has an event object, which contains a number of important properties. These properties fall into two categories, the first containing the results, assuming a method was called successfuly, and the second set providing information on errors. The following code shows how the onresult event handler can be used to interpret the results from Web Service calls. In the sample code, the iCallID variable has global scope and contains a unique value that is returned from the method callService. The iCallID variable stores the unique value of the call, which is later tested in the onWSresult function in two places to see if its value matches with the event.result.id property. The other conditional expressions test for an error, as indicated by comments in the code. <SCRIPT language="JavaScript"> // All these variables must be global, // because they are used in both init() and onresult(). var iCallID = 0; var intA = 5; var intB = 6; function init() { // Establish the friendly name "MyMath" for the WebServiceURL service.useService("/services/math.asmx?WSDL","MyMath"); // The following method doesn't specify a callback handler, so onWSresult() is used iCallID = service.MyMath.callService("add", intA, intB); } function onWSresult() { // if there is an error, and the call came from the call() in init() if((event.result.error)&&(iCallID==event.result.id)) { // Pull the error information from the event.result.errorDetail properties var xfaultcode = event.result.errorDetail.code; var xfaultstring = event.result.errorDetail.string; var xfaultsoap = event.result.errorDetail.raw; // Add code to handle specific error codes here }

SANjEEV KUMAR [MCA, ADCA, BCA, MCP]

January 2008

// if there was no error, and the call came from the call() in init() else if((!event.result.error) && (iCallID == event.result.id)) { // Show the arithmetic! alert(intA + ' + ' + intB + ' = ' + event.result.value); } else { alert("Something else fired the event!"); } }
Obtaining Results with a Callback Function <SCRIPT language="JavaScript"> // All these variables must be global, // because they are used in both init() and onResult(). var iCallID = 0; var intA = 5; var intB = 6; function init() { // Establish the friendly name "MyMath" for the WebServiceURL service.useService("/services/math.asmx?WSDL","MyMath"); // The following uses a callback handler named "mathResults" iCallID = service.MyMath.callService(mathResults, "add", intA, intB); } function mathResults(result) { // if there is an error, and the call came from the call() in init() if(result.error) { // Pull the error information from the event.result.errorDetail properties var xfaultcode = result.errorDetail.code; var xfaultstring = result.errorDetail.string; var xfaultsoap = result.errorDetail.raw; // Add code to handle specific error codes here } // if there was no error else { // Show the arithmetic alert(intA + ' + ' + intB + " = " + result.value); }

}

SANjEEV KUMAR [MCA, ADCA, BCA, MCP]

January 2008

Note If result.error is false, then the errorDetail properties are undefined. The main difference is that the callback approach doesn't use the event object to obtain the results. Instead, the callback function receives a parameter containing the results. In the example the object is named result, and this object exposes the same set of properties as the event.result object used in Obtaining Results with the onresult Event.

SANjEEV KUMAR [MCA, ADCA, BCA, MCP]

January 2008

Related Documents

Webservices
July 2020 7
Webservices
June 2020 6
Webservices-book
November 2019 9
Webservices Profiling
May 2020 11
Consume Me
October 2019 18