Web Services Using JavaScript and .NET

Introduction

Test the Web service here: http://www.xemantex.com/consumeWebSvcDateTime.aspx

I wrote this article because there are very few resources that elaborate on client-side consuming a Web service. This type of consuming is very handy when one has to make Web service calls to a remote Web server directly from the client. One can think of many instances where one would want to make Web service calls from the client. Look at this Web site, http://www.xemantex.com, for example, that uses the double-click on the client to call a Web service. Double-click on any word to get the word's meanings. On the other hand, calling Web services from the client has an added advantage of refreshing only that part of the Web page that accesses the Web service. A Web service call does not re-render the entire content on the page. Thus, one can attain a partial refresh of the Web page, providing a good improvement in the browsing efficiency for the end user.

A Web service is a function, method, or sub routine that is accessible not only to one computer (the owner or host) but also to any computer on the Internet. In a sense, a Web service is a collection of universally available functions.

Why Web Services?

The increasing usage of Web services is attributed to the fact that they enable easy sharing of an application across the Internet. You can find a single Web site serving for diverse functions such as stock quotes, weather information, and airline tickets. It is quite possible that the Web site directly provides for all these services, but in most cases each of the services would be powered by a third party that specializes in it. For example, http://www.weather.com is a good source for weather information.

Similarly, http://www.google.com is excellent resource for searching the Web. Instead of creating tools that cater to weather and/or Web search tools, a Web site owner or a solution provider may obtain services from Weather.com or Google.com for those respective needs. This approach not only saves time but also enables the site to provide reliable, accurate, and consistent information to the end user. Services like these that are made available to other computers anywhere in the world via the Internet are called Web services.

.NET has supplemented the easy creation and usage of Web services. Web services in .NET utilize open standards such as HTTP, SOAP, XML, and WSDL that allow for fast creation, extension, and deployment. Creating a Web service using .NET is a snap. You will look into creating and consuming a Web service in the following paragraphs.

Code Sample

For the sake of simplicity, you can create a Web service that returns a Web server's current date and time. Because this is a Web service, this will return the date and time of the geographical location where its server is located. If the Web server is in Chicago, USA, you will get the local time at Chicago. Similarly, if the Web server is in New Delhi, India, you will see its local time.

Test this Web service here: http://www.xemantex.com/consumeWebSvcDateTime.aspx.

There are two steps to creating a Web service using .NET (note that creating and consuming are two different things for a Web service).

  1. Create an .asmx file (call it dateTimeWebSvc.asmx).
  2. Write the required functions to accomplish business processes.

You will look into Step 2 before going to Step 1. Following is the code for a function to return the current date and time as a string:

<WebMethod()> Public Function currDateTime() As String
   Dim dateTimeStr As String
   Dim tZn         As TimeZone              'get the time zone
   Dim tZnNameStr  As String                'time zone name
                                            '(CST, EST, etc)
   tZn = System.TimeZone.CurrentTimeZone    'get name of time zone
   If tZn.IsDaylightSavingTime(Now) Then
      tZnNameStr = tZn.DaylightName
   Else
      tZnNameStr = tZn.StandardName
   End If
   dateTimeStr = "Current date and time at this web server's _
                  geographical location " & _
   "is- " & Now.ToString & " " & tZnNameStr
   Return dateTimeStr
End Function

Web Services Using JavaScript and .NET

As you can see, I declared a public function called "currDateTime". This function returns the current date and time as a string. More importantly, note the key word "WebMethod" that precedes function definition. This implies that the function is accessible to any computer via the Internet as a Web method. Now, create an .asmx file (call it dateTimeWebSvc.asmx) ((this is your Step 1) using Visual Studio editor or a text editor) and copy the above function into this file. The dateTimeWebSvc.asmx file that you created will be your Web services class.

Without further delay, I will delve into how to access (or consume) the Web service that you created from the client using JavaScript and Web Service components (HTC).

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.

Step 1: Create an .aspx page

This will be the Web form to access the Web service. The following code shows the consumeWebSvcDateTime.aspx page. It has two labels. The first label has text for testing the Web service and the second label has the results from executing the Web services. (View the web form here: http://www.xemantex.com/consumeWebSvcDateTime.aspx.)

<%@ Page Language="vb" AutoEventWireup="false"
    Codebehind="consumeWebSvcDateTime.aspx.vb" %>
<HTML>
   <HEAD>
      <title>Web Services - Create and Consume Demo</title>
   </HEAD>
   <body>
      <form id="frmWebSvcDateTime" method="post" runat="server">
         <table cellpadding="0" cellspacing="0" ID="Table1">
            <tr>
               <td>
               <asp:Label id="lblAllText" runat="server"
                          Width="581px" Height="36px">
               We are trying to understand web services here. At this
               time, we know how to create a web service. Do we know
               how to consume yet? It will be no more than two
               minutes till we get there. Now, double-click on any
               word to get servers date time using our Web service.
               </asp:Label>
               </td>
            </tr>
            <tr>
               <td>
               <asp:Label backcolor="#99eedd" id="lblDateTime"
               runat="server" Width="581px" Height="36px">
               Date and time will be displayed here.</asp:Label>
               </td>
            </tr>
         </table>
      </form>
   </body>
</HTML>

Step 2: Add WebService behavior (HTC file) to consumeWebSvcDateTime.aspx page using JavaScript

This step can be further divided into three steps.

  1. Copy the HTC file into the Web form project folder.
  2. Write a script using JavaScript to access the Web service using WebService behavior.
  3. Modify the HTML on the consumeWebSvcDateTime.aspx page to handle the click event.

Step a: 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 (Source: http://msdn.microsoft.com/library/default.asp?url=/workshop/author/webservice/overview.asp). Please read the documentation on WebService behavior at the link provided above. In short, remember that this behavior is to make calls to a Web service from a client using a scripted language. Moreover, this behavior is encapsulated in a HTC (HTML component) file. 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.

Web Services Using JavaScript and .NET

Step b: 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, as shown below.

<DIV id="dNtWbSvc" style="BEHAVIOR: url(webservice.htc)"></DIV>

Once this behavior is attached, add the following code to consumeWebSvcDateTime.aspx to enable the use of the WebService behavior and make calls to Web services.

<SCRIPT language="JavaScript">
function initWebHTC()
      {
      //init and create short-cut name for Web service
      dNtWbSvc.useService("consumeDnTWebSvc.asmx?WSDL","dNtSvc");
      var iCallID;
      if (dNtWbSvc.dNtSvc)
         {
            document.getElementById("lblDateTime").innerHTML=
               "Loadin..."
            iCallID= dNtWbSvc.dNtSvc.callService(gtDnTRslt,
                                                 "currDateTime");
         }
      }
   function gtDnTRslt(result)
      {
      //if an error then get error details
      if(result.error)
      {
         //Pull error info from 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
         document.getElementById("lblDateTime").innerHTML="Error:
         " + " "xfaultcode + " ; " + xfaultstring + " ; " + xfaultsoap;
      }
      else
      {
         //alert(result.value);
         document.getElementById("lblDateTime").innerHTML=result.value;
         //clear any selection
         var sRng;
         sRng = document.selection.createRange();
         sRng.execCommand("unselect"); 
         }
      }
</SCRIPT>

Step c: Modify the HTML on the consumeWebSvcDateTime.aspx page to handle the double-click event.

<body ondblclick="initWebHTC();">

Proxy Server and Code

Step 3: Create a proxy server for the Web service

To call a Web method, you need a proxy server. What is a proxy server? A client cannot call the Web methods that are located on a remote Web server directly. Instead, it has to route the Web method calls from the local Web server. Please see this link: http://msdn.microsoft.com/workshop/author/webservice/using.asp#Security_Issues.

Therefore, to access remote Web methods, you create a proxy server like so: You need to copy the DLL that is created by compiling the project that contains the Web method that you defined in the first few paragraphs of this article. To compile the project, you can use the Visual Studio editor or use the command-prompt commands. To compile the project via the command prompt, use the following statements:

c:> WSDL http://localhost/yourWebServices/yourWebMethodClass.asmx?WSDL

(Thanks to user "mark4asp" for letting me know about the these WSDL.exe and csc.exe file-path locations and their importance).

WSDL.exe is a program located at this file path: C:\Program Files\Microsoft Visual Studio .NET 2003\SDK\v1.1\Bin\WSDL.exe. You may want to use a qualified path when compiling the project using WSDL.

Moreover, use the command-line below to create a DLL for the Web service.

C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\csc.exe
   /nologo /t:library /out:dateTimeWebSvc.dll dateTimeWebSvc.cs

(Note: csc.exe - C Sharp Compiler)

Once you've compiled the project, you will have the DLL file for the project in its bin folder. Copy the DLL file and paste it into the bin folder for the project that contains your client pages. You can (and maybe need to) also "right-click" on the project's name and choose "Add Reference" to add the DLL file that you created.

Create an .asmx file (call it consumeDnTWebSvc.asmx) in the project where your client page exists. Add the following code in this .asmx file:

<WebMethod()> Public Function currDateTime() As String
   Dim dNtMainWebSvc As New yourWebServices.dateTimeWebSvc
   'instantiate date and time web svc
   Dim dateTimeStr As String
   dateTimeStr = dNtMainWebSvc.currDateTime()    'call date and time
                                                 'web svc
   Return dateTimeStr
End Function

Notice that you created a (proxy) Web method that has the same name (you can name it any name; just for simplicity, I named it the same as the real Web method) as the real Web method. As described above, the client will not be able to talk with the remote Web server directly. Instead, it will send its requests to its local Web server, which in turn will request the remote Web server.

Also, note one more thing in the WebMethod above: You declared and defined an object called dNtMainWebSvc (Dim dNtMainWebSvc As New yourWebServices.dateTimeWebSvc). This is possible because you added a reference (DLL) of this object (see paragraph above) to the client's project.

Web Services Using JavaScript and .NET

Your client side consumeWebSvcDateTime.aspx page should look like this when you are done:

<%@ Page Language="vb" AutoEventWireup="false" 
                    Codebehind="consumeWebSvcDateTime.aspx.vb" %>
<HTML>
 <HEAD>
  <title>Web Services - Create and Consume Demo</title>
  <SCRIPT language="JavaScript">
   function initWebHTC()
   {
     //init and create short-cut name for web service
     dNtWbSvc.useService("consumeDnTWebSvc.asmx?WSDL","dNtSvc");
     var iCallID;
     if (dNtWbSvc.dNtSvc)
     {
       document.getElementById("lblDateTime").innerHTML="Loadin...";         
       iCallID= dNtWbSvc.dNtSvc.callService(gtDnTRslt,"currDateTime");
     }
   }
   function gtDnTRslt(result)
   {
     //if an error then get error details
     if(result.error)
     {
       //Pull error info from 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
       document.getElementById("lblDateTime").innerHTML="Error: " 
         + xfaultcode + " ; " + xfaultstring + " ; " + xfaultsoap;
     }
     else
     {
       //alert(result.value);
       document.getElementById("lblDateTime").innerHTML=result.value;
       //clear any selection
       var sRng;
       sRng = document.selection.createRange();
       sRng.execCommand("unselect"); 
     }
   }
  </SCRIPT>
 </HEAD>
 <body ondblclick="initWebHTC();">
   <DIV id="dNtWbSvc" style="BEHAVIOR: url(webservice.htc)"></DIV>
   <form id="frmWebSvcDateTime" method="post" runat="server">
    <table cellSpacing="0" cellPadding="0">
     <tr>
      <td>
       <asp:label id="lblAllText" runat="server" 
       Width="581px" Height="36px">We are trying to understand 
       web services here. At this time, we know how to create 
       a web service. Do we know how to consume yet? 
       It will be no more than 2 minutes till we get there..
       Now double click on any word to get server's date time 
       using our web service.</asp:label>
      </td>
     </tr>
     <tr>
      <td>
       <asp:Label backcolor="#99eedd" id="lblDateTime" 
       runat="server" Width="581px" Height="36px">
       Date and time will be displayed here.</asp:Label>
      </td>
     </tr>
    </table>
   </form>
 </body>
</HTML>

Test the Web Service

That is it. You have everything in place. You have a "real" Web service class. There is a client to consume the Web service. You also created a "proxy" Web service for your client. Fire up your project in the browser and double-click on any word on the page to see results from the Web service—you should see the current date and time from the remote Web server.

Test the Web service here.

Conclusion

There may be an error from the client saying: "service unavailable." This happens when the client could not connect to the remote Web service. This error occurs if you do not have an .HTC file, or if you mistyped the name of the proxy server's Web method, and other related reasons. Write to me if you have such a case, and we will see how to proceed.

Prasad Kopanati is the Vice President of XemanteX Inc., an Internet company offering language related services for Web users. You can reach him via email at team@xemantex.com.

Sources



About the Author

Prasad Kopanati

Prasad Kopanati is the Vice President of XemanteX Inc. http://www.xemantex.com, an internet company offering language related services for web users. You can reach him via email at team@xemantex.com.

Downloads

Comments

  • There are no comments yet. Be the first to comment!

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Download the Information Governance Survey Benchmark Report to gain insights that can help you further establish business value in your Records and Information Management (RIM) program and across your entire organization. Discover how your peers in the industry are dealing with this evolving information lifecycle management environment and uncover key insights such as: 87% of organizations surveyed have a RIM program in place 8% measure compliance 64% cannot get employees to "let go" of information for …

  • With JRebel, developers get to see their code changes immediately, fine-tune their code with incremental changes, debug, explore and deploy their code with ease (both locally and remotely), and ultimately spend more time coding instead of waiting for the dreaded application redeploy to finish. Every time a developer tests a code change it takes minutes to build and deploy the application. JRebel keeps the app server running at all times, so testing is instantaneous and interactive.

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds