Click here to Skip to main content
Click here to Skip to main content

Web Services using WebService Behavior and .NET

, 18 Jul 2004
Rate this:
Please Sign up or sign in to vote.
NET has supplemented for the easy creation and usage of web services. Web services in .NET utilize open standards like HTTP, SOAP, XML, and WSDL that allow for fast creation, extension, and deployment. Read through.

Introduction

Test the web service here.

I thought to write this article because there are very few resources that elaborate on client-side consuming of 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, 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 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 to not only one computer (the owner or host) but to any computer on the Internet. In a sense, a web service is a collection of universally available functions.

Increasing usage of web services is attributed to the fact that these enable for easy sharing of an application across the Internet. You can find a single web site serving for diverse functions like 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 service would be powered by a third party which specializes in it. For example, this is a good source for weather information. Similarly, this is an excellent resource for searching the web. Instead of creating tools that cater for weather and/or web search tools, a web site owner or a solution provider may obtain services from Weather.com or Google.com for respective needs. This approach not only saves time but also enables 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 Internet are called web services.

Getting Started - Web Method and Client Side Code

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

For the sake of simplicity, let us create a web service that returns the web server’s current date and time. As 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, then we will get the local time at Chicago. Similarly, if the web server is in New Delhi, India, then we will see its local time.

Test this web service here.

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

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

We 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

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 keyword WebMethod that precedes function definition. This implies that the function is accessible to any computer via Internet as a web method. Now, create an .asmx file (call it dateTimeWebSvc.asmx) ((this is our 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 dwell into how to access (or consume) the web service that we created from the client using JavaScript and Web Service components (HTC).

There are 3 steps to consume the web service:

  1. Create an .aspx page.
  2. Add WebService behavior (HTC file) to .aspx page using JavaScript.
  3. Create a proxy server for the web service that we 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. First label has text for testing the web service, and the second label has the results from executing the web service.

(View the web form here.)

<%@ 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">
       <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>

Step 2: Add WebService behavior (HTC file) to consumeWebSvcDateTime.aspx page using JavaScript. This step can be further divided into 3 steps.

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

Step a: The WebService behavior enables us 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). Please read the documentation on WebService behavior at the link provided here. In short, remember that this behavior is to make calls to a web service from client using scripted language. Moreover, this behavior is encapsulated in a HTC (HTML component) file. Thus, in order to use WebService behavior, we need to have the HTC file in the project’s folder. To use the behavior in our consumeWebSvcDateTime.aspx page, download the WebService HTC file and copy it to your web form project’s folder. You will be able to download the HTC file here.

Step b: To invoke “date and time” method, we 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 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 HTML on the consumeWebSvcDateTime.aspx page to handle the double click event.

<body ondblclick="initWebHTC();">

Proxy Server Code

Step 3: Create a proxy server for the web service.

In order to call a web method, we 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 the diagram at this link.

Therefore, in order to access remote web methods, we create a proxy server like so:

We need to copy the DLL that is created by compiling the project that contains the web method that we 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. In order to compile the project via command-prompt, use the following statement:

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

Once you compile 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 may be 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 we created a (proxy) web method that has the same name (you can name it any name; just for easiness, I named it the same as the real web method) as the real web method. As described above, 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; we declared and defined an object called dNtMainWebSvc (Dim dNtMainWebSvc As New yourWebServices.dateTimeWebSvc). This is possible because we added a reference (DLL) of this object (see paragraph above) to client’s project.

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 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

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

Share

About the Author

super_coding

United States United States
No Biography provided

Comments and Discussions

 
QuestionWeb Service variable PinmemberSweetynewb10-Aug-12 2:42 
Questionservice unavailable PinmemberMember 84528061-Dec-11 21:27 
GeneralInvalid active port [modified] PinmemberIspanecStas29-Aug-09 8:25 
GeneralYou can do the same by using AJAX Pinmembersemenoff18-Sep-07 8:48 
Generalzimlet and webservice Pinmemberkarthikajayen21-Feb-07 1:22 
QuestionAccessing webservice from VB Pinmemberdak_anand12-Dec-06 19:12 
GeneralService unavailable. Pinmembermizzi5-Oct-05 5:38 
GeneralRe: Service unavailable. PinmemberPrasad Kopanati6-Oct-05 17:54 
QuestionWeb Service and C# Class Library PinmemberAnand Devani2-Oct-05 21:52 
AnswerRe: Web Service and C# Class Library PinmemberPrasad Kopanati10-Oct-05 6:47 
Generalinvalid active port Pinmemberrobina ephram28-Jul-05 4:14 
GeneralRe: invalid active port PinmemberBill Hepola11-Aug-05 17:10 
Questionsupport for FireFox? Pinmemberbarry.b20-Jul-05 17:53 
Questioninvalid active port? Pinsussyves03030-Mar-05 5:42 
GeneralOne thing I am not sure Pinmemberwyx200028-Sep-04 10:53 
GeneralRe: One thing I am not sure PinmemberDZilla2-Dec-04 3:07 
GeneralRe: One thing I am not sure Pinmembergrhind14-Feb-06 5:53 
GeneralLists on the client PinmemberHiltonG24-Aug-04 2:25 
QuestionWSE? Pinmemberjamesy_ms25-Jul-04 4:38 
QuestionC#? PinmemberRick Engelking20-Jul-04 3:23 
AnswerRe: C#? PinmemberSamJost21-Jul-04 23:52 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web02 | 2.8.140827.1 | Last Updated 19 Jul 2004
Article Copyright 2004 by super_coding
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid