| Web Services using WebService Behavior and .NET |
| Why use WebService Behavior and .NET Test the web service here 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. Introduction to Web Services A web service is a function, method or sub routine that is accessible to not 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, Weather.com is a good source for weather information. Similarly, Google is 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. .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. Web Service Example For the sake of simplicity let us create a web service that returns 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 it’s 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 the 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 FunctionAs you can see, there is 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 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. With out further delay, I will dwell into how to access (or consume) the web service that we created from 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 web service. 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 services. <%@ 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 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. a) Copy the HTC file into the web form project folder. b) Write script using JavaScript to access web service using WebService behavior. c) 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 (Src: 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 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 HTC file at this link: http://msdn.microsoft.com/downloads/samples/internet/behaviors/library/webservice/default.asp 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 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();">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 below. Therefore, in order to access remote web methods, we have 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 statements: c:> WSDL http://localhost/yourWebServices/yourWebMethodClass.asmx?WSDLOnce you 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 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 FunctionNotice 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 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" 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 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 is displayed " & _
" here.</asp:Label></td>
</tr>
</table>
</form>
</body>
</HTML>
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 There may be an error from the client saying that the “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. Sources: Introducing XML Web services: http://samples.gotdotnet.com/quickstart/aspplus/doc/webservicesintro.aspx http://www.codeguru.com/Csharp/Csharp/cs_webservices/tutorials/article.php/c5477/ http://aspnet.4guysfromrolla.com/articles/062602-1.aspx WebService Behavior: http://msdn.microsoft.com/library/default.asp?url=/workshop/author/webservice/overview.asp Download the HTC file: http://msdn.microsoft.com/downloads/samples/internet/behaviors/library/webservice/default.asp Questions and Comments Please feel free to contact XemanteX at team@xemantex.com for any further inquires, questions and comments. |
| Home | About XemanteX | Services & Using XemanteX | Contact XemanteX | Terms of Use | Privacy Policy |
| Copyright © 2002-2003 XEMANTEX INC. All rights reserved. |