Create Efficient UIs

WebService behaviors make it easy to call a service, pass it parameters, and integrate returned data into a DHTML page.

Dan Wahlin

October 30, 2009

9 Min Read
ITPro Today logo

XtremeData

LANGUAGES: C# | JavaScript

TECHNOLOGIES:Web Services

 

Create Efficient UIs

WebService behaviors make it easy to call a service,pass it parameters, and integrate returned data into a DHTML page.

 

By Dan Wahlin

 

Web Services are touted for their ability to integratedistributed systems in a cross-platform and language-neutral manner. Theirsolid grounding in XML standards allows this type of integration to occur.However, Web Services also can play a large role in other environments such ascorporate intranets even when distributed systems might not necessarily need tobe integrated. By using Web Services, data can be pulled into a Web pagedynamically to minimize page refreshes and give customers a more client-serverlook and feel.

 

You can accomplish this technique by tying into WebServices using the WebService behavior, which Microsoft provides for use withInternet Explorer (IE). This JavaScript file makes it easy to call a service,pass it parameters, and retrieve returned data that can be integrated into apage using Dynamic HTML (DHTML). You can download the latest version of theWebService behavior from http://msdn.microsoft.com/downloads/samples/internet/behaviors/library/webservice/default.asp.

 

In this article, I'll show you how to leverage theWebService behavior to tie into Web Services and allow users to update, insert,and delete data more efficiently through an intranet page using mainlyJavaScript and DHTML.

 

What is the WebService Behavior?

The WebService behavior is a JavaScript file embedded in aWeb page using specific IE behavior syntax. You need IE 5 or higher, so thistechnique is a strong candidate for use in intranet applications where you arecertain IE is being used because Netscape, Opera, and other browsers don'tsupport behaviors.

 

Behaviors are JavaScript files that have embedded XMLmetadata describing the different features they expose. The WebService behaviorexposes its own object model with properties, methods, and events. TheWebService behavior has these tags at the top of the file to help describe it:

 

             VALUE="MicrosoftWebService Behavior 1.0.1.1120" />                                                 NAME="onserviceavailable"/>   Although a complete discussion of all of these features isbeyond the scope of this article, you will see how to leverage some of the moreimportant features. Currently, the behavior works with products that supportWeb Services Description Language (WSDL) 1.1 such as the .NET Framework, SOAPToolkit, and Apache SOAP Web Services. You can find complete documentation forthe behavior at http://msdn.microsoft.com/workshop/author/webservice/webservice.asp.   Use WebService Behavior ASP.NETPages The first thing that must be done to use the WebServicebehavior in a Web page is to embed it using syntax similar to this:      style="BEHAVIOR:url(Scripts/WebService.htc)">   The previous code relies on the behavior functionalitybuilt into IE 5 and higher to identify the location of the JavaScript file thatwill be used to call Web Services. As shown, this file has an extension of htc.File loading occurs on the client rather than on the server.   Once embedded, the behavior can be invoked and used to tieinto a WSDL 1.1-compliant Web Service using JavaScript code. This isaccomplished by referencing the embedded behavior id (webService in theprevious code) and calling its useService method:   var webServicePath =  "WebServices/CustomersWS.asmx?WSDL"; webService.useService(webServicePath,"wsSend");     The useService method accepts the path to the WSDLfile for the Web Service and a custom name used to reference the Web Service. A"friendly" name of wsSend is assigned in this example. This name will be usedeach time the Web Service at CustomersWS.asmx is called using the behavior.   Although additional features are available, this is allthat is required to hook up the behavior to a Web Service. WebMethods - methodsfound in a Web Service - can then be called using the behavior's callServicemethod, the behavior id, and the "friendly" name you assigned to the service.Here's an example of how to call the GetCustomerData method of thewsSend service:   wsCallID = webService.wsSend.callService(onWSGetCustomerData,             "GetCustomerData", customerID);   This call passes a parameter named customerID to themethod for processing. If the method accepted additional parameters, you couldinclude them as well by separating them with commas. Once called, any datareturned from the GetCustomerData WebMethod is passed to an eventhandler named onWSGetCustomerData where it is processed. I'll discussthe code within this and other event handlers later in the article.   Build a Customer Support App Now that you've seen the basics of wiring the WebServicebehavior to a Web Service, let's build a customer support application thatusers can use on an intranet to insert, update, and delete customer datathrough the browser. By using the behavior, the Web page doesn't need to berefreshed each time new data is viewed, which enhances the user experiencegreatly because they can perform their duties quicker and in a more enjoyablemanner. Figure 1 shows the customer support application.  
Figure 1. You can use the WebService behavior to call Web Services fromASP.NET pages. The customer support application allows users to select anexisting customer and then edit or delete their data. When a customer isselected, the WebService behavior grabs the data, JavaScript, and DHMTL, thenhandles adding the proper data into the page. This allows the data to be addedwithout refreshing the page.   The application loads the initial customer data into anASP.NET DataGrid Web Server control on the server side when the pagefirst loads. The DataGrid is put into a scrollable div block. Iinitially used a DropDownList control to show the different customers,but because the user needed to be able to see multiple columns simultaneously,the scrollable div solution worked better.   The code to create the DataGrid is shown in Figure2. Notice that the div tag wrapping the DataGrid has a style attributethat limits its height to 180 pixels and has its overflow property setto "auto" in order to create a scrollable area for the DataGrid.  

       CellSpacing="0" BorderWidth="0"Cellpadding="0"     Width="100%"Runat="server"     AutoGenerateColumns="False"   >                 Font-Name="arial" />                     DataField="ContactName" />                DataField="CompanyName" />                                       decoration:underline;cursor:hand;color:#02027a"             title="Edit Customer"             onClick="GetCustomerData('<%# DataBinder.Eval(                Container.DataItem,"CustomerID")%>')">             <%# DataBinder.Eval(              Container.DataItem,"CustomerID")%>                                    Figure 2. In applications where multiple columns needto be displayed to a user in a scrollable area, you can embed a DataGrid withina scrollable div. The code shown in this figure demonstrates how to bind aDataGrid to a data source and place the resulting grid columns into a div thathas its CSS overflow property set to auto (for auto scrolling).   Instead of linking the CustomerID column in the DataGrid(see Figure 1) to a different page or even the same page, the link calls alocal JavaScript function named GetCustomerData (see the bold section inFigure 2), which fires up the WebService behavior embedded in the page usingthe techniques I described earlier. The GetCustomerData JavaScriptmethod accepts the CustomerID value and passes this value to the WebServicebehavior, which in turn calls the actual GetCustomerData Web Servicemethod:   function GetCustomerData(customerID) {  ChangeCursor("wait");   //Call actual WebService using the WebService Behavior  wsCallID = webService.wsSend.callService(onWSGetCustomerData,              "GetCustomerData", customerID); }   Back on the server, the GetCustomerData Web Servicemethod simply queries a SQL Server database for the appropriate customer dataand returns a DataSet to the caller:   [WebMethod] public DataSet GetCustomerData(string customerID) {  string sql =    "SELECT * FROMCustomersWS WHERE CustomerID='" +   customerID +"'";   SqlConnection dataConn =new SqlConnection(connStr);   SqlDataAdapter adap =new SqlDataAdapter(sql,dataConn);   DataSet ds = newDataSet();  adap.Fill(ds,"CustomersWS");       return ds; }   Once the call to the Web Service method completes, the onWSGetCustomerDataevent handler in the Web page's JavaScript is fired and the returned DataSetdata is accessed. Because DataSets are returned as XML, you can loadthem on the client side into a DOMDocument object to access the nodes.The code in Figure 3 shows how to load the returned XML into a DOMDocumentobject.   function onWSGetCustomerData(result) {   if (result.error) {    //Pull the errorinformation from the    //result.errorDetailproperties    var xfaultcode   = result.errorDetail.code;     var xfaultstring =result.errorDetail.string;     var xfaultsoap   = result.errorDetail.raw;     alert("Errorreturned from Web Service: " +              xfaultcode +" " + xfaultstring);   } else if (!result.error) {  //Access returned data    var returnData = newActiveXObject("MSXML2.DOMDocument");     returnData.async =false;       //Assign data returnedfrom the Web Service to    //the DOMDocument    returnData.documentElement = result.value;      BindCustomerData(returnData);     returnData = null;   }   ChangeCursor("default"); }Figure 3. The onWSGetCustomerData client-side callbackfunction is called when the GetCustomerData Web Service methodcompletes. The Web Method returns a DataSet that is loaded into a DOMDocumentobject on the client side.   Once the DataSet data is loaded into the DOMDocument,a JavaScript method named BindCustomerData is called, which reads theXML and binds it to text-box controls on the page. You can accomplish thiseasily by walking through the DOM structure (see Figure 4).   function BindCustomerData(xmlData) {  document.all.spanMessage.innerText = "";   document.all.tblCustomerData.style.display= "block";   document.all.btnSubmitInsert.disabled = true;   document.all.btnSubmitUpdate.disabled = false;   document.all.btnSubmitDelete.disabled = false;   var customers =    xmlData.selectSingleNode("//CustomersWS");   if (customers != null) {//Make sure we found the node    for (vari=0;i      var childNode =customers.childNodes(i);         //Add each text nodevalue in the XML to the proper      //textbox in theHTML.       if (document.all("dc"+ childNode.nodeName)) {        document.all("dc" +          childNode.nodeName).value = childNode.text;       }    }  }}Figure 4. XML data returned from calling a remote WebService can be bound to client-side controls by walking through a DOM structureprogrammatically. The BindCustomerData method shown here accepts a DOMDocumentobject as a parameter and binds the data within the object to controls on thepage.   By clicking on a CustomerID link in the DataGrid,users can display any customer's data quickly and easily without a round tripto the Web server and the accompanying refresh, giving the user a moreclient/server feel to the application.   Performing an insert, update, or delete operation to thecustomer data is accomplished in a similar manner by using the WebServicebehavior. First, a JavaScript method is called, which creates an XML documentfrom the data in the different text boxes. This document is then passed to aWeb Service method named UpdateCustomerData using the WebServicebehavior. UpdateCustomerData then parses the XML and performs theappropriate update, insert, or delete operation on the database.   By thinking creatively, you'll find you can use theWebService behavior in many ways within your intranet to make the process ofworking with data much more pleasant and efficient for users. Although onepotential example of using the behavior has been demonstrated in this article,the sky's the limit - there are many other ways you can use the WebServicebehavior to perform useful tasks.   To see a live demo of the WebService behavior applicationdiscussed in this article, visit the XML for ASP.NET Developer's Web site at http://www.xmlforasp.net/codeSection.aspx?csID=67.   The files referenced in this article are available fordownload.   Dan Wahlin is president of Wahlin Consulting and founded theXML for ASP.NET Developers Web site (http://www.xmlforasp.net),which focuses on using XML and Web Services in Microsoft's .NET platform. Healso is a corporate trainer and speaker and teaches XML and ASP.NET trainingcourses around the United States. Dan co-authored Professional Windows DNA (Wrox), ASP.NET: Tips, Tutorialsand Code (Sams), and authored XML for ASP.NET Developers (Sams). E-mail Dan at mailto:[email protected].  Tell us what you think! Please send any comments about thisarticle to [email protected] include the article title and author.      

Sign up for the ITPro Today newsletter
Stay on top of the IT universe with commentary, news analysis, how-to's, and tips delivered to your inbox daily.

You May Also Like