Remote Scripting, WebService Behaviour, and Script Call Back

Introduction

I am going to discuss one of the important but less used features in a real-world scenario: the capability of calling a server method from a client script. But, before you start looking at this article's topics, it will be better if you ask what happens when you send a request for a page from a browser so that you can understand what happens behind the scenes and why the same is not straightforward.

However, I am not going to explain how the request maps of IIS or how server-side code and client-side code differs. If you are looking for this, first you must be sure that the client script is not run at the server from which you request your page through the URL and that it runs on your browser and the server code runs at the server). Thus, what happens when you send a request for a specific URL from your browser is that you send a command to the target URL or IP address, asking it to give you the requested page. The browser opens a socket to the target URL or IP address and waits for the response; upon receiving the response, it displays according to the content type.

Therefore, every time you get a new page even though you are posting to the same page (ASP.NET). This is what called the stateless architecture of HTTP. To make the client talk to the server but yet not have the page postback or refresh, some sort of secret or behind-the-scenes request is required from the client script; later, the same needs to be mixed with the current contents of the browser.

People often ask how they can invoke/validate their data from the server without a post back because they need to invoke the same from a client script. A practical example of this is that you need to validate some 10–15 fields in a Web form from the client side, without a page refresh, or perhaps you need to call a server function without submitting the page. There are many pros and cons with these approaches of invoking a server method from client script or calling a Web service from a script as well as quite a few methods/techniques have evolved and been adopted successfully. The three primitives are remote scripting, Web service behavior, and script callback.

Although there are other alternative practices to adopting good caching (the page still gets refreshed although data will come from the cache here) or using hidden field transfer, the data from and to the server and client or preloading all the possible alternatives in client memory through XML or any other format. All of these work fine, but there are times when the amount of data is just too overwhelming for all the possible combinations.

I know that by giving such power to a client script, there are a lot of security concerns but there are workarounds and, for intranet applications, adapting such techniques is much better and essential sometimes. I will discuss the pros and cons of each technology; also, I'll discuss the working of Remote scripting, Web service behaviors (with an example), and script callback (in detail with an example).

Remote Scripting

This is one of the first and earliest technologies used for calling the server method from a client script. In remote scripting, a hidden request is made to the server to execute a method to return the data required; the plus is the entire page is not required to be processed in the server. There were two popular remote scripting techniques used in past: Microsoft provided the client- and server-side include files for carrying the task in a Scriptlibrary directory, and the Java Version of JSRS in JSP; it created a hidden element on the page that submitted the request to the server which then respond back to it based on the browser. However, the Microsoft model was the only version that supported both Synchronous and Asynchronous mode (the Java version only supported Asynchronous mode).

The workings of remote scripting

Remote scripting uses HTTP requests to the server over port 80; this is helpful for firewall negotiation. It provides the mechanism to call code on the server using three components (client-side Microsoft Java Script, Client-Side Java Applet, and Server-Side script). To implement the same, you add a script block to the page and call the RSEnableRemoteScripting function. This function will load the Java applet onto the page, based on the browser. The applet provides the communication mechanism through HTTP to the server. Please refer the References section if you need the details regarding the same.

Pros and cons of remote scripting

Pros Cons
Protocol is lightweight—it uses HTTP GET Remote scripting uses its own non-standard, XML-based protocol
Can work with IE, Mozilla, Netscape Hard to debug
  Limit of only 4 Kb of data transport. Not restricted to doing HTTP GET

Web Service Behavior

By using Web service behavior, you can invoke the remote method exposed by the Web service or other Web server that supports SOAP and WSDL from the client script. The Web service behavior supports a large number of data types, including intrinsic SOAP data types, arrays, objects, and XML data. The Web service behavior is implemented with an HTML Component (HTC) as an attached behavior; thus, it can be used with IE5.0 and later.

How it works

By using the Web service behavior, you can call a Web service method from the client script in both modes: synchronous or asynchronous. To invoke the method, first you need to attach the webservice.htc to the page.

The next step is to call the Web service in sync or async mode. The syntax is:

service.useService("WSDL path of websvc","servicename");
service.Service1.callService(callbackfunc,"webmethod name",
                             parameter value);

The asynchronous mode of method invocation is the default mode of the Web service behavior. For the Sync mode, you need to set the async=false of the callObj and pass the same.

Example

var callObj = new Object();
callObj.funcName = " webmethod name "; callObj.portName = "Port1";
callObj.async = false; service.useService("WSDL path of websvc","
                                          servicename");
service.Service1.callService(callbackfunc, callObj , parameter value);

For a detailed example, download the accompanying code.

Pros and Cons of Web Service Behaviors

Pros Cons
Not restricted to doing HTTP GET for server requests. Remote Scripting is limited to 2 Kb of data when making a request to a server. The Web service behavior uses HTTP POST, so it doesn't suffer from this restriction Limited to a specific browser (IE 5.0 or above)
Allows you to take advantage of .NET functionality from within a browser Memory leak (see References)
Works great with ASP.NET so that you can take advantage of all the enhancements (speed, compiled languages, .NET Framework) that ASP.NET offers  

Script Callback in ASP.NET 2.0

Overview

The idea behind script callback features is not different from remote scripting or Web service behavior; it serves the same purpose, but this time there is no applet and it is already implemented as part of the script model for ASP.NET 2.0 together with many other important and wonderful features. To make the script callback work, you need to define a trigger element that retrieves input data from the current page and binds the same to some JavaScript code. This will prepare a call to a built-in script, webform_docallback, which will open an HTTP connection to the remote ASP.NET page from which you'll retrieve the required values. Now, the ASP.NET runtime detects the callback and executes a particular method (server side) and returns the executed value back to the client. As a response on the client side, the response is passed to a user-defined callback JavaScript and then mixed with the client contents thru DHTML. The same features are built in with many controls with ASP.NET 2.0.

How it works

When a call made thru webform_docallback (rather, the connection is established), how does ASP.NET know that this is a normal request or callback one? The HTTP handler decides by looking into the request header and body for the _CALLBACKID that was generated by the docallback process. If it finds that it is a callback, it sets page.iscallback=true. Further, the requested page and controller should implement the ICallbackEventHandler interface so that it could be differentiated from a postback. If a page implements the ICallbackEventHandler, it has the <%@implements Interface=system.web.ui.ICallbackEventHandler %> directive. If a control implements the Icallbackhandler interfacen the ASP.NET runtime invokes the RaiseCallbackEvent method on the interface and prepares the response from the results of the call. The ICallbackEventHandler interface has one method with a string parameter and a string return type. The parameter is taken from the request collection. The point to remember is that the GetCallbackEventReference method returns a string that represents the JavaScript function that invokes the Remote method. This string is bound to a client-side event.

Remote Scripting, WebService Behaviour, and Script Call Back

Implementing the Solution

Now, you canstart building the solution. You;ll ask the user to enter the user id and validate the user id from the backend server using script callback. Although a real-world application will be different, I found this as an easy to understand and better demonstration idea. You need to define the server-side code that will be called through callback from the client side. Before any code, let me repeat again that the server page can be any page that implements ICallbackEventHandler; here you have the same page acting as the remote page.

In the page load event, you need to generate the callback event and the required client script. Thus, you need to define the client-side script dynamically to the textbox's onchange event that will fire the callback through the GetCallbackEventReference function. The code for this is:

public partial class validatecallback_aspx :ICallbackEventHandler

Here goes the page_load

void Page_Load(object sender, EventArgs e)
{
   TextBox1.Attributes.Add("onchange", "GetId(TextBox1.value,
                           'TextBox1');");
   string callback = Page.GetCallbackEventReference(this, "arg",
      "ClientCallback", "context", "ClientError");
   string clientFunction = "function GetId(arg, context)
                                          { " + callback + "; }";
   Page.ClientScript.RegisterClientScriptBlock(this.GetType(),
                                               "GetId",
                                               clientFunction, true);
}

WHERE:

this: The control or page that implements ICallbackEventHandler(Current Page)

arg: The string to be passed to server side as argument

ClientCallback: The client-side function that will receive the result from the server-side event.

context: Context string passed through client scripts

ClientError: Name of the client-side function that will be called if there is any error during this process

The String returned from the GetCallBackReference method will look like this:

WebForm_DoCallback ('__Page', arg, ClientCallback, context,
                    ClientCallbackError);

WebForm_DoCallback is another JavaScript function that comes along with the framework. It will do the XMLHttp work for you. This function is located in the script returned by the WebResource.axd handler.

Now that you have declared and registered the client script that will cause the postback to happen and defined which client function will be raised if an error happens (ClientError), and which function in the client will receive the response back (ClientCallback). Now, you need to handle the callback in the server as well; this is generated above. As I mentioned before, you need to implement RaiseCallbackEvent that will raise the callback from the server to the client. The event argument takes the parameter you passed through the script (TextBox1.value here). The result is the string that you received in the client script function.

public string RaiseCallbackEvent(string eventArgument)
{
   //Validation logic here to validate the ID from BE
   //return the string result to ClientCallback
}

That's all that you have in your server side code that you registered and generated the callback dynamically. Also, you handle the callback and send the response. Now, its the client's turn to handle the response for the callback. Here is the client to handle the same. In the client script you should define the following:

function ClientCallback(result, context)
{
   //manipulate the result string object here
}

   function ClientCallbackError(result, context)
   {
      alert(result);
   }

Example

For a detailed example, download the code.

Notes:
  1. Using the script, call back what you passed from the client to the server. It is a string but it can be of a different format: it can be CSV, script, XML, and so forth.
  2. You must attach the client-side code to an HTML element but not to a submit button. Clicking on that will cause a postback to occur, entire pages will refresh, and all of remote call contents will be gone.
  3. Any browser that doesn't support Dynamic HTML can't execute callbacks because they need to refresh information without refreshing the whole page.
  4. In the sample application, change the connection string accordingly—that is, the server name and dbname—and create a table EMP in the database with ID as a column to be validated with.

Conclusion

In script callback, a special round trip occurs even though a round trip still occurs. But, neither the entire page is posted nor is the entire page at the remote URL processed though page_load. pre_render still happens, after which the callback method is processed and result the returned back. Thus, the page from which you made the callback is not refreshed and, because the remote page is not entirely processed, it is a useful and faster technique to learn with.

This callback mechanism is implemented using XMLHttp Post and DHTML support is used to mix the contents with the current contents; it still support multiple browsers, such as Netscape 7.0 and up and Safari 1.2 for Apple clients. Further, you can verify whether or not callback support is there by using SupportCallback and SupportXMLhttppost. Further, you ll find many ASP.NET controls in 2.0 that use this great features extensively to manipulate the data. A prime example is the Gridviewcontrol. I hope that you found this article useful. Please feel free to contact me for any comments and suggestions.

References

For further reference, you can check out www.msdn.com.

Remote scripting

http://www.thycotic.com/dotnet_remotescripting.html

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/rmscpt/html/rmscpt.asp

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnclinic/html/scripting11122001.asp

http://www.codeproject.com/aspnet/AlvaroRemoteScripting.asp

Web service behavior

http://msdn.microsoft.com/library/default.asp?url=/workshop/author/webservice/overview.asp

http://msdn.microsoft.com/library/default.asp?url=/workshop/author/webservice/webservice.asp

http://msdn.microsoft.com/library/default.asp?url=/workshop/author/webservice/using.asp

http://msdn.microsoft.com/msdnmag/issues/04/06/WebQA/

http://support.microsoft.com/?id=309170

http://blog.steeleprice.net/archive/2004/10/29/419.aspx

http://dotnetjunkies.com/WebLog/kmotion/archive/2005/02/03/50925.aspx

Script callback

http://msdn.microsoft.com/msdnmag/issues/04/08/CuttingEdge/

http://msdn.microsoft.com/msdnmag/issues/05/01/CuttingEdge/default.aspx

http://www.codeproject.com/aspnet/ScriptCallbackFramework.asp



About the Author

shreemannarayana dash

shreeman narayana dash is a .net architect.His area of interest are distributed programming,Webservice,Remoting and serialization and Network technologies . you can reach shreeman at sndshreeman@rediffmail.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

  • Live Event Date: December 11, 2014 @ 1:00 p.m. ET / 10:00 a.m. PT Market pressures to move more quickly and develop innovative applications are forcing organizations to rethink how they develop and release applications. The combination of public clouds and physical back-end infrastructures are a means to get applications out faster. However, these hybrid solutions complicate DevOps adoption, with application delivery pipelines that span across complex hybrid cloud and non-cloud environments. Check out this …

  • CentreCorp is a fully integrated and diversified property management and real estate service company, specializing in the "shopping center" segment, and is one of the premier retail service providers in North America. Company executives travel a great deal, carrying a number of traveling laptops with critical current business data, and no easy way to back up to the network outside the office. Read this case study to learn how CentreCorp implemented a suite of business continuity services that included …

Most Popular Programming Stories

More for Developers

RSS Feeds