When creating a commercial website, developers only need to use a browser as the user interface. For example, in many cases, users want to retrieve information from the server after performing some operations (such as entering employee numbers. To achieve this goal, they will send the page back to the server, retrieve employee information, and refresh the page with the information retrieved from the server. Although the current method of refreshing the entire page is common, its efficiency is very low, because the web page is refreshed and the content of the whole page is re-presented, even if only a few parts of the page have actually changed. When searching for a category or search engine, you can notice this low efficiency. Its latency and resource waste are very obvious. However, if the same functions are completed without refreshing the browser page, the user experience will be greatly improved. To achieve this purpose, we need to execute a piece of server code without leaving the current page. This is the role of web service behavior. In this case, the code snippet executed on the server is the code of the web service method, and the role of the browser is to call this server code without leaving or refreshing the current page.
When using web service behavior, you only need to send a request to execute a specific web service method from the web page of a client browser. On the server side, when ASP. NET is running, it receives a request and uses relevant parameters to call the Web service method. After the Web Service is executed, it sends the result to the caller, and the result is displayed or processed by the browser. As a result, you can establish a typical client/server communication without having to ignore the stateless feature of the lower-layer HTTP protocol. Another advantage of web service behavior is that only one file (WebService. HTC) is required on the client to implement the function. When using the web service method, you can also call the Web service method asynchronously. This capability is very powerful and can be used to build a rich user experience on the client. For example, when a user continues to process transactions on the same page, you can use web service behavior to allow the server to verify certain data. Once the function is returned, you can get the execution result and send the result to the user.
Web Service Behavior
Web Service Behavior implements the function of using the HTML component (HtC) file as the affiliated behavior. It can be used for Internet Explorer 5 and later versions. As mentioned above, Web Service Behavior provides a way to call remote web methods across platforms by using industrial standard protocols (such as HTTP, soap, and XML. One of the important features of web service behavior is that it allows you to use these features without deep soap knowledge. Web Services process soap packet communication between browsers and Web Services, which simplifies remote calls of Web Services. You don't have to worry about the aggregation and disaggregation of soap messages ). All codes that process soap details are encapsulated in behavior, simplifying client scripts on the main web page.
Web service behavior is to embed Javascript files on Web pages using specific ie behavior syntax. By exposing properties and methods to client scripts, Web Service Behavior aggregates messages and breaks down the response information sent back by Web Services. Objects exposed by behaviors not only enable clear error handling methods, but also provide simple access to returned data. Web Service behaviors receive method calls from client scripts and send requests to Web services using soap messages. The result returns the client script and the processing continues. Next, you can use the information on the web page in any situations you need, such as updating some parts of the page and sending error messages.
A key feature of web service behavior is that it allows client scripts to access the Web service without having to navigate to another URL. The following list details the important methods supported by Web Service Behavior:
· Createuseoptions (options used for creation)-allows us to save user authentication information across remote method calls. It is useful when we use SSL to communicate with remote web services.
· Callservice: allows us to call remote Web Services asynchronously.
· Useservice-allows us to create a "friendly" name for the service when calling the web service.
To use web pages of IE 5.0 and later versions, you must download the WebService. HTC behavior file and save it in the same folder as your web page. This file can be downloaded from the following link: keystore.
Implementation Process
You have learned some basic knowledge about Web service behavior. Now you can look at a sample application that demonstrates how to use web service behavior in ASP. NET applications. In this example, you will create a simple application that allows you to retrieve employee information from the northwind database. The sample application also allows you to search for employee information based on the employee ID.
Creation process of the employee Web Service
In this section, you must first create a New Visual C # web service project called employeewebservice. After the project is created, you need to change the default web service class name service1 to employeeservice. Next, you need to import the following namespace to access and process XML data.
using System.Data.SqlClient;
using System.Xml;
[Webmethod]
Public xmldocument getempdetailsbyempid (INT employeeid)
{
String connstring =
System. configuration. configurationsettings. etettings ["connectionstring"];
Sqlconnection = new sqlconnection (connstring );
Try
{
Dataset employeedataset = new dataset ("employeesroot ");
// Pass the name of the stored procedure to be executed and the sqlconnection object as parameters
Sqldataadapter adapter = new sqldataadapter ();
Sqlcommand command = new sqlcommand ("select * from employees where employeeid =" + employeeid. tostring (), sqlconnection );
// Set the attributes of the sqlcommand object
Command. commandtype = commandtype. text;
Adapter. selectcommand = command;
// Fill the dataset with the values returned by the Stored Procedure
Adapter. Fill (employeedataset, "employees ");
Xmldocument xmldoc = new xmldocument ();
Xmldoc. loadxml (employeedataset. getxml ());
Return xmldoc;
}
Catch (exception ex)
{
Throw ex;
}
Finally
{
If (sqlconnection. State = connectionstate. open)
{
Sqlconnection. Close ();
}
}
}
Webmethod indicates that this method will be exposed as a web method that can be called. During project deployment, ASP. NET provides information about all pipelines required to call this method on the Internet using certain protocols (such as XML, HTTP, and SOAP.
[Webmethod]
The method name above tells us that getempdetailsbyempid takes the employee ID as the parameter and returns the employee details in xmldocument form.
public XmlDocument GetEmpDetailsByEmpID(int employeeID)
{
string connString = System.Configuration.ConfigurationSettings.
AppSettings["connectionString"];
The preceding Code uses the deleettings attribute of the configurationsettings class to retrieve the connection string from the <deleettings> section of the web. config file. The connection string in the web. config file is defined as follows:
<appSettings>
<add key="connectionString"
value="server=localhost;uid=sa;pwd=;database=Northwind" />
</appSettings>
The following code creates an instance of the sqlconnection object and passes it a connection string used to establish a database connection:
SqlConnection sqlConnection = new SqlConnection(connString);
Then You encapsulate all executable code in a try... catch code block to handle any errors that may occur when executing the following statements:
try
{
DataSet employeeDataset = new DataSet("EmployeesRoot");
SqlDataAdapter adapter = new SqlDataAdapter();
Next, you have created an instance of the sqlcommand object and passed the SQL statement you want to execute to its constructor and the sqlconnection object created in the previous step:
SqlCommand command = new SqlCommand("Select * from Employees Where EmployeeID =" + employeeID.ToString(),sqlConnection);
Then you set the selectcommand attribute to an appropriate value, indicating that you want to execute an SQL statement:
// Set the attributes of the sqlcommand object
Command. commandtype = commandtype. text;
Set the selectcommand attribute of the sqldataadapter object to the previously created sqlcommand object:
adapter.SelectCommand = command;
Now we use the fill method to retrieve data from the data source by executing the specified SQL statement on the Data source:
// Fill the dataset with the value returned by the Stored Procedure
Adapter. Fill (employeedataset, "employees ");
Once the employee information becomes a dataset, you can retrieve its content and pass it as a parameter to the loadxml method of the xmldocument object. Finally, return the xmldocument object to the caller of the web service:
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(employeeDataset.GetXml());
return xmlDoc;
}
catch (Exception ex)
{
throw ex;
}
In the final code block, you checked the State property to verify whether the connection is still open. If the connection is still open, you can close it by calling the close method of the connection object:
finally
{
if (sqlConnection.State == ConnectionState.Open)
{
sqlConnection.Close();
}
}
}
Now that you have created a Web Service, right-click the employeeservice. asmx file and select build and browse to test its functions. The screen you get should be similar to the following:
Click the method name (getempdetailsbyempid) on the screen above to display the following screen:
If you enter the employee ID and click invoke to call the Web service method, you will get the following output:
Now that you have tested the web service, you should use web service behavior to call it from the ASP. NET page to test its functions.
How to use web service behavior to call Web Services on ASP. NET pages
The first step to use web service behavior in a Web page is to embed it into the page code using a syntax similar to the following:
<div id="service" style="BEHAVIOR:url(webservice.htc)"></div>
The code above relies on the built-in behavior function of IE 5 (or later) to verify the location of the Javascript file, which is used to call the web service. As mentioned above, the location of the WebService. HTC file must be the same as the folder on the web page. We should pay attention to the fact that loading behavior files occurs on the client rather than on the server.
After the above Code is embedded, we can use JavaScript code to call behavior and link it to a web service compatible with WSDL 1.1. This is achieved by referencing the embedded behavior ID (the service in the previous Code) and calling its useservice method:
service.useService("http://localhost/MyProjects/WebServiceBehavior/EmployeeService.asmx?WSDL","svcEmployee");
You need to call the useservice method in the onload event handle of the page to ensure that the Web service has been mapped before calling any method of the web service.
The useservice method has the following two parameters:
· Path of the Web Service's WSDL file.
· A "friendly" name used to reference the Web service in the future. This name is used every time you call the method in the employeeservice. asmx file.
Now you have created a web service and can access it. Asynchronous invocation of web services can be divided into two steps. The advantage of asynchronous calling is that the web page does not have to wait for the Web service to return. Step 1: Call the web method and use the callback function as a parameter. Step 2: After the required method is executed, the Web service returns and starts the callback function.
The complete source code list is as follows:
<% @ Page Language = "C #" codebehind = "employeeserviceclient. aspx. cs"
Autoeventwireup = "false" inherits ="
Employeewebserviceclient. employeeserviceclient "%>
<HTML>
<Head>
<Title> employee details </title>
<Script language = "jscript">
// Define a module-level variable to capture the event ID
VaR icallid;
Function getemployeedetails ()
{
// Call the getemployeedetails method of the svcemployee Web Service
Icallid =
Service. svcemployee. callservice (displayresults, "getempdetailsbyempid", txtemployeeid. value );
}
Function displayresults (result)
{
VaR strxml, objxmlnode, objxmldoc, objemployee, strhtml;
// Check whether the event ID is the same
If (icallid! = Result. ID)
Return;
If (result. Error)
{
// Display the error message
VaR faultcode = result. errordetail. Code;
VaR faultstring = result. errordetail. String;
Alert ("error: code =" + faultcode + ", fault string =" + faultstring );
}
Else
{
// Assign the result value to the local variable
Objxmlnode = result. value;
Objxmldoc = new activexobject ("Microsoft. xmldom ");
// Load the returned XML string into the xmldom object
Objxmldoc. loadxml (objxmlnode. XML );
// Get the pointer of the employees Node
Objemployee =
Objxmldoc. selectsinglenode ("getempdetailsbyempidresult"). selectsinglenode ("employeesroot"). selectsinglenode ("employees ");
// Check whether the employee pointer returned from the server is valid
Strhtml = "<font color = '# 0000ff'> ";
If (objemployee! = NULL)
{
// Dynamically generate HTML and add it to a string variable
Strhtml + = "<br> employee ID: <B>" +
Objemployee. selectsinglenode ("employeeid"). Text + "</B> <br> ";
Strhtml + = "Employee First name: <B>" +
Objemployee. selectsinglenode ("firstname"). Text +
"</B> <br> ";
Strhtml + = "employee last name: <B>" +
Objemployee. selectsinglenode ("lastname"). Text + "</B> <br> ";
Strhtml + = "Employee title: <B>" +
Objemployee. selectsinglenode ("title"). Text + "</B> <br> ";
Strhtml + = "Employee title: <B>" +
Objemployee. selectsinglenode ("title"). Text + "</B> <br> ";
Strhtml + = "title of courtesy: <B>" +
Objemployee. selectsinglenode ("titleofcourtesy"). Text + "</B> <br> ";
Strhtml + = "Postal code: <B>" +
Objemployee. selectsinglenode ("postalcode"). Text + "</B> <br> ";
}
Else
{
Strhtml + = "<br> <B> employee
Not found </B> ";
}
Strhtml + = "</font>"
// Assign the dynamically generated HTML to the DIV tag
Divcontents. innerhtml = strhtml;
}
}
Function Init ()
{
// Create a web service instance and call it svcemployee
Service. useservice ("http: // localhost/myprojects/15 seconds/webservicebehavior /_
Employeewebservice/employeeservice. asmx? WSDL "," svcemployee ");
}
</SCRIPT>
</HEAD>
<body onload="init()">
<div id="service" style="BEHAVIOR: url(webservice.htc)"></div>
<H1 align="center">
<font color="#800080">Employee Details</H1>
</FONT>
<br><br>
<P align="left"><font color="#800080"><b>Enter the
Employee ID:</b></font> <INPUT
id="txtEmployeeID" name="txtEmployeeID" style="LEFT: 149px; TOP:
72px"><INPUT id="btnAdd" type="button" value="Get Employee Details"
name="btnGetEmployee" onclick="return GetEmployeeDetails()"></P><P></P>
<div id="divContents">
</div>
<P></P>
</body>
</HTML>
In the getemployeedetails method, you can call the web method of the web service by passing the callback method name and input parameters as parameters to the web service. This is implemented by calling the callservice Method for Web Service Behavior:
Function getemployeedetails ()
{
// Call the getemployeedetails method of the svcemployee Web Service
Icallid =
Service. svcemployee. callservice (displayresults, "getempdetailsbyempid", txtemployeeid. value );
}
The callservice method returns a unique identifier, which can be used to identify web service calls. If you call multiple asynchronous web services and then assemble the results in the client browser, This identifier is necessary. In this case, you match this ID with the ID returned by an attribute of the result object. The matching process is completed in the callback function:
function DisplayResults(result)
{
var strXML,objXMLNode,objXMLDoc,objEmployee,strHTML;
In the following code, you can match the ID of the result object with the ID returned by the callservice method:
// Check whether the events are the same
If (icallid! = Result. ID)
Return;
Then, check the error attribute to determine whether an error has occurred during the Web Service Execution. If an error occurs, the error message is displayed in the message window. If there are no errors, process the returned results and display them in the HTML Div Tag:
If (result. Error)
{
// Read error message
VaR faultcode = result. errordetail. Code;
VaR faultstring = result. errordetail. String;
Alert ("error: code =" + faultcode + ", fault string =" + faultstring );
}
Else
{
// Assign the result value to the local variable
Objxmlnode = result. value;
Objxmldoc = new activexobject ("Microsoft. xmldom ");
// Load the returned XML string into the xmldom object
Objxmldoc. loadxml (objxmlnode. XML );
// Get the pointer of the employees Node
Objemployee = objxmldoc. selectsinglenode ("getempdetailsbyempidresult ").
Selectsinglenode ("employeesroot"). selectsinglenode ("employees ");
// Check whether the employee pointer returned from the server is valid
Strhtml = "<font color = '# 0000ff'> ";
If (objemployee! = NULL)
{
// Dynamically generate HTML and add it to the string content
Strhtml + = "<br> employee ID: <B>" +
Objemployee. selectsinglenode ("employeeid"). Text +
"</B> <br> ";
Strhtml + = "Employee First name: <B>" +
Objemployee. selectsinglenode ("firstname"). Text +
"</B> <br> ";
Strhtml + = "employee last name: <B>" +
Objemployee. selectsinglenode ("lastname"). Text +
"</B> <br> ";
Strhtml + = "Employee title: <B>" +
Objemployee. selectsinglenode ("title"). Text +
"</B> <br> ";
Strhtml + = "Employee title: <B>" +
Objemployee. selectsinglenode ("title"). Text +
"</B> <br> ";
Strhtml + = "title of courtesy: <B>" +
Objemployee. selectsinglenode ("titleofcourtesy"). Text +
"</B> <br> ";
Strhtml + = "Postal code: <B>" +
Objemployee. selectsinglenode ("postalcode"). Text +
"</B> <br> ";
}
Else
{
Strhtml + = "<br> <B> employee
Not found </B> ";
}
Strhtml + = "</font>"
// Assign the dynamically generated HTML to the DIV tag
Divcontents. innerhtml = strhtml;
}
}
In the preceding example, you use the callback function specified when calling the Web service to process the results returned by the web service. You can also specify a callback function when defining the DIV tag (this method is used to include Web Service Behavior in the page ). For example, in the following code, you use the onresult event handle supported by web service behavior to specify the callback function:
<div id="service" style="BEHAVIOR: url(webservice.htc)"
onresult="DisplayResults()"></div>
With the above definition, you can process the results returned by the web service in the displayresults function. The following code demonstrates an implementation example of the displayresults function:
Function displayresults ()
{
// Check whether the event ID is the same
If (icallid! = Event. Result. ID)
Return;
If (event. Result. Error)
{
VaR faultcode = event. Result. errordetail. Code;
VaR faultstring = event. Result. errordetail. String;
Alert ("error: code =" + faultcode + ", fault string =" +
Faultstring );
}
Else
{
// Display the result value
Alert (event. Result. value );
}
}
In the code, you can see that we use the event object to get a pointer to the result object containing the results returned by a Web service call.
Put Code together
If you use a browser to view the above ASP. NET page, the output you see is similar. Enter a valid employee ID in the employee text box and click "get employee details" to call the remote web service. This operation will result in asynchronous calls to the Web Service, and the results returned by the web service will be displayed in the DIV element on the web page.
I want to emphasize again that Internet Explorer 5 or a later version is required for Web Service behaviors. Therefore, if you can determine the browser type you are using, this technology is suitable for enterprise intranet applications.
Conclusion
In this article, you will see how Web Service Behavior provides an improved solution to transfer information from a Web server to a client browser. Using Web service behavior to call remote web methods simplifies client operations, making web services more attractive. At the same time, we can see how Web service behavior improves user experience by providing dynamic interactive web pages. Because Web service behavior (WebService. HTC file) encapsulates the Code required to call a remote web service using soap. With the evolution of the soap standard, you can update the behavior independently without changing the client script.