Showing posts with label AJAX. Show all posts
Showing posts with label AJAX. Show all posts

Notes On Ajax

2012-01-29

Ajax- General:
· From a more developer-oriented perspective, AJAX collectively refers to a set of development components, tools, and techniques for creating highly interactive Web applications that give users a better experience
· According to the AJAX paradigm, Web applications work by exchanging data rather than pages with the Web server.
Working
Figure 1-1: Browsers submit an HTML form and receive a new page to display.

The chief factor that enables remote scripting is the ability to issue out-of-band HTTP requests. In this context, an out-of-band call indicates an HTTP request placed using a component that is different from the browser’s built-in module that handles the HTML form submission (that is, outside the traditional mechanism you see in Figure 1-1). The out-of-band call is triggered via script by an HTML page event and is served by a proxy component. In the most recent AJAX solutions, the proxy component is based on the XMLHttpRequest object; the proxy component was a Java applet in the very first implementation of RS(remote scripting).
Figure 1-2: Out-of-band calls are sent through a proxy component, and a JavaScript callback is used to update any portion of the page affected by returned data.





Requirements to work AJAX Applications In A Browser:
Exactly what are the capabilities required of a browser to run AJAX functionalities? As mentioned, a browser needs to provide two key capabilities:
1. a proxy mechanism to make client code able to place out-of-band HTTP calls,
2. and an updatable DOM.
3. In addition, browsers must support JavaScript and preferably cascading style sheets (CSS).
It takes the form of the XMLHttpRequest object and is devised as an interface exposed by the browser to allow script code to perform HTTP client functionality, such as submitting form data or loading data from a remote Web site.

DOM:
The page Document Object Model (DOM) is the specification that defines a platform- and language-neutral interface for accessing and updating the contents, structure, and style of HTML and XML documents. A recognized standard ratified by the W3C committee, the DOM is now supported by virtually all browsers. The DOM provides a standard set of objects for representing the constituent elements of HTML and XML documents. All together, these objects form a standard interface for accessing and manipulating child elements of HTML pages and, more in general, XML documents.
The DOM is a platform-independent and language-neutral representation of the contents of a Web page that scripts can access and use to modify the content, structure, and style of the document.

Representation of Document:

The DOM is a standard API exposed by the browser in which a displayed page has a tree based structure. Each node in the logical tree corresponds to an object. On the other hand, the name “Document Object Model” hints at an object model in the common interpretation of the object-oriented design terminology. A Web page-the document-is modeled through objects. The model includes the structure and behavior of a document. Each node in the logical tree is not static data; rather, it is a live object with a known behavior and its own identity.
The DOM is made of nodes, and each node is an object. For a Web page, each node maps to an object that represents an HTML tag. The object, therefore, has properties and methods that can be applied to an HTML tag. There are three fundamental operations you can accomplish on a node: find the node (including related nodes such as children, parent, or sibling nodes), create a node, and manipulate a node.

XMLHttpRequest:
· Originally introduced with Internet Explorer 5.0, the XMLHttpRequest object is an internal object that the browser publishes to its scripting engine. In this way, the script code found in any client page-typically, JavaScript code-can invoke the object and take advantage of its functionality.
The XMLHttpRequest object allows script code to send HTTP requests and handle their response. Functionally speaking, and despite the XML in the name, the XMLHttpRequest object is nothing more than a tiny object designed to place HTTP calls via script in a non-browser-led way.

DOM & Ajax:
For AJAX, it’s all about exchanging data with a remote server. But once the data is downloaded out-of-band on the client, what can you do with that? The DOM provides an outlet for the data to flow into the current page structure and update it.

The AJAX.NET Professional Library:
· AJAX.NET Professional (AjaxPro) is a pretty popular open-source library that adds a good layer of abstraction over the XMLHttpRequest machinery. Written by Michael Schwarz, the library creates proxy classes that are used by client-side JavaScript to invoke methods on the server page. The AjaxPro framework provides full data type support and works on all common Web browsers, including mobile devices. Nicely enough, the library can be used with both ASP.NET 1.1 and ASP.NET 2.0.
The key tool behind the AjaxPro library is an HTTP handler that hooks up any HTTP requests generated by the client-side part of the library:

<httpHandlers>

   <add verb="POST,GET" path="ajaxpro/*.ashx"

        type="AjaxPro.AjaxHandlerFactory, AjaxPro.2" />

</httpHandlers>
  


Once the web.config file has been correctly set up, you write JavaScript functions to trigger and control the out-of-band call. Each call targets a JavaScript object that represents the publicly callable method on the server ASP.NET page. A client-callable method is just a public method decorated with a specific attribute, as shown here:


[AjaxPro.AjaxMethod] 
  public DateTime GetCurrentTimeOnServer() 
   {
         return DateTime.Now;
   }
 
 }

The class with public methods, as well as any custom types used for I/O, has to be registered with the framework to have the corresponding JavaScript proxy created:

protected void Page_Load(object sender, EventArgs e)
{
   AjaxPro.Utility.RegisterTypeForAjax(typeof(YourAjaxClass));
}
If you do this, the handler guarantees that any managed .NET object that is returned by a server method will be serialized to a dynamically created JavaScript object to be seamlessly used on the client. You can return any managed type, your own classes, or enum types as you would do in plain .NET code. No view state is available during the AJAX request, meaning that you can’t do much with page controls. In light of this, it is recommended that you create callable methods as static methods preferably, though not necessarily, on a separate class.

ASP.NET Ajax Framework(Available In ASP.NET Ajax Extensions package)

Architecturally speaking, the ASP.NET AJAX framework is made of two distinct elements: a client script library and a set of server controls that add AJAX capabilities to ASP.NET 2.0. The client script library is written entirely in JavaScript and therefore works with any modern browser. ASP.NET AJAX offers an end-to-end programming model that spans the client and server environment. It’s also seamless to use for most developers because it simply extends the popular and known application model of classic ASP.NET.
The ASP.NET AJAX framework is made of a client and a server part. Applications use a clientside JavaScript library mostly to manage the page user interface, to call server-based components, and order partial page refreshes. Server components generate the response for the client and emit predefined client script that integrates and sometimes extends the client library. The server-side part of ASP.NET AJAX includes Web services, ad hoc controls, and the JavaScript Object Notation (JSON) infrastructure.

The Microsoft Client Library for AJAX
The AJAX client library is made of a set of JavaScript (*.js) files that are linked from client pages in case of need. These *.js files are downloaded on each client that consumes ASP.NET AJAX pages. These files are transparent to ASP.NET developers, as they are embedded in the ASP.NET AJAX assembly.
The client library provides object-oriented and cross-browser extensions to the JavaScript language such as classes, namespaces, inheritance, and data types. In addition, it defines a largely shrink-wrapped version of the .NET base class library that includes string builders, regular expressions, timers, and tracing. The key part of the ASP.NET AJAX client library is the networking layer that manages the complexity of making asynchronous calls over XMLHttpRequest. This layer allows the client page to communicate with Web services and Web pages through out-of-band calls.

Server-Based Components
ASP.NET AJAX is an extension to ASP.NET, and ASP.NET is a server-side development platform. Hence, ASP.NET AJAX sports a number of server-based components, including Web services and controls, that offer a double benefit. On one end, you can program these components from the client and update the current page without a full refresh; on the other hand, though, the programming model remains unaltered for the most part. In this way, at least limited to core functionalities, the ASP.NET AJAX learning curve might be pleasantly short. Built-in Web services expose a handful of ASP.NET features to client pages, including user profiles, membership, and roles. Server controls look like classic ASP.NET server controls, except that they emit additional script code. The script code enriches the user’s experience with the control by optionally taking advantage of the facilities provided by the AJAX client library. Some key AJAX server controls you will work with are UpdatePanel, UpdateProgress, and

ASP.NET AJAX Extensions:
The ASP.NET AJAX Extensions Microsoft Windows Installer (MSI) package installs a handful of files on your computer under the following folder:
%DRIVE%:\Program Files\Microsoft ASP.NET\ASP.NET 2.0 AJAX Extensions\v1.0.61025
In addition, it places an assembly named System.Web.Extensions.dll in the global assembly cache (GAC). The ASP.NET AJAX assembly incorporates a bunch of JavaScript files (.js files) that form the client script library.

Note
The official installer of ASP.NET AJAX copies the binaries in the GAC. This is still the recommended way to go. However, simply copying the System.Web.Extensions assembly in the Bin folder does suffice to deploy an ASP.NET AJAX Web site.

The simplest way to create an ASP.NET AJAX application is by choosing the Visual Studio 2005 project template. Visual Studio adds to the project a web.config file that contains all settings required to run an ASP.NET AJAX application. In particular, the configuration file links the ASP.NET AJAX assembly to the project.

The JSON Infrastructure

The growing use of out-of-band calls in Web applications poses a new issue-moving more and more complex data around. It’s not a mere serialization issue for which the .NET Framework and other platform-specific frameworks have a ready-made solution. The serialization involved with out-of-band calls is not just cross-platform; it also involves distinct tiers and radically different tools and languages. With out-of-band calls, you move data from a client to a server and back. But the client is a browser (if not a mobile device), and JavaScript is the native format of data. The server is a Web server hosted on a variety of hardware/software platforms and running a specific Web application framework.
JSON is the emerging technology for passing structured data across the Web. It is a data interchange format and is fully described at http://www.json.org. Relatively easy to read for humans and to parse and generate for machines, JSON describes data using two universal data structures-collections and array-that are supported in one way or another by most modern programming languages and class libraries.
JSON is a text format that is completely language independent, although it relies heavily on a number of conventions inherited from the C family of languages.
The JSON client infrastructure can serialize a JavaScript object to an interchange format and send it over the wire to a server-side receiver. The platform-specific receiver will parse the data stream to build a platform-specific object. Likewise, the JSON server infrastructure can take any platform-specific object and serialize to an interchange format. Back on the client, the data stream is promptly transformed in a JavaScript object. As far as the .NET Framework and ASP.NET are concerned, a bit of reflection is used to examine the internal structure of classes and create proper JavaScript wrappers.
Virtually all AJAX-based frameworks implement a JSON infrastructure. ASP.NET AJAX is no exception.

Note
For a while, XML has been touted as the lingua franca of the Web because it is ideal and made-to-measure for developers and architects to package and exchange data in a totally cross-platform way. Today, you find out that JSON (a non-XML technology) is sold for the same task. Is there any difference? Both JSON and XML do the same work. XML is more complex, quirky in some respects, and general-purpose, and it is preferable to describe data to be styled using an XSLT style sheet for UI purposes. For raw data, JSON is a more lightweight format that is easier to read and parse for both humans and computers.

The Microsoft Client Library for AJAX:

The Microsoft AJAX library is written in JavaScript.
Microsoft Client library is a set of JavaScript classes that represent the client-side engine of the ASP.NET AJAX Extensions framework. In the library, you find a bunch of functionalities to support ASP.NET AJAX server controls as well as to command client Web requests. A set of helper classes complete the Microsoft AJAX library to make it easier and more comfortable for developers to create JavaScript callbacks to update a page on demand.
The library is made of a few .js files downloaded to the client browser on demand. At a minimum, the core runtime script file is downloaded. All script files are incorporated as resources in the ASP.NET AJAX assembly-the System.Web.Extensions.dll file-and are extracted and injected in the client page as required by the page itself.

The AJAX client library is made up of three main logical layers: JavaScript extensions, core framework classes, and user-interface (UI) framework classes. (See Figure 2-1.)


Figure 2-1: A graphical view of the AJAX client library

The Sys.Application Object
The execution of each ASP.NET AJAX page is controlled by an application object that is instantiated in the body of the library. The application object is an instance of a private class-the Sys._Application class. As mentioned, JavaScript has no notion of private members; therefore, private members are conventionally indicated by the underscore symbol (_) in their names.
Whenever an ASP.NET AJAX page is loaded in the browser, an instance of the Sys._Application class is promptly created and assigned to the Sys.Application object:

Sys.Application = new Sys._Application();


In addition, each ASP.NET AJAX page is injected with the following script code:

<script type="text/javascript"> <!--
Sys.Application.initialize();
// --> </script>

This code is placed immediately after the closing tag of the page’s form, and it commands the loading of any script files registered for loading with the page’s script manager. More details on script loading are unveiled in Chapter 3, “The Pulsing Heart of ASP.NET AJAX.” As a result, the Sys.Application object is the nerve center of the ASP.NET AJAX page.

The Network Stack:
AJAX libraries in general, and ASP.NET AJAX Extensions in particular, owe their growing popularity to their ability to execute out-of-band Web requests from the client. In particular, ASP.NET AJAX Extensions allows you to invoke Web service methods as well as static methods defined on the server ASP.NET page class. This ability leverages the networking support built into the Microsoft AJAX library.
The Sys.WebForms.PageRequestManager Class
The Sys.Net.WebRequest class and its derivatives serve the purpose of issuing client requests to a server resource. This is the engine behind client Web service calls. ASP.NET AJAX Extensions provides a large share of its functionalities through updatable panels. (See Chapter 4.) Updatable panels are portions of the page that can be refreshed independently of others and the same page as a whole. The PageRequestManager class is the Microsoft AJAX library class in charge of controlling the update of individual panels.

The Script Manager Component:

· Virtually any AJAX library needs a component or a tool that makes some JavaScript code available on the client. This script code represents the client infrastructure necessary for the library to work. An AJAX library, on the other hand, can’t be entirely based on server-side code and does need a lot of script code. The point is, which component or tool is ultimately responsible for injecting this code?
· AJAX libraries tend to offer a server-side, often parameterless, component that when dropped on the page automatically outputs any required scripts. This component is generally known as the AJAX manager or script manager. The script manager accomplishes a number of tasks. In addition to ensuring that the proper script is linked to the page, the script manager typically enables and supports partial page rendering, generates proxy code to call remotely into server-side methods and objects, and sets up auxiliary services.
· In ASP.NET AJAX, the script manager component takes the form of the ScriptManager server control.
· The main control in the server infrastructure of ASP.NET AJAX Extensions is the ScriptManager control and its twin ScriptManagerProxy control. You will find just one instance of the ScriptManager control in each ASP.NET AJAX page. No AJAX capabilities can be enabled in ASP.NET pages that lack a reference to one ScriptManager control. The ScriptManagerProxy control is used only in master pages scenarios.
· The ScriptManager control manages and delivers script resources, thus enabling client scripts to make use of the JavaScript type system extensions and other JavaScript features we covered in Chapter 2, “The Microsoft Client Library for AJAX.” The ScriptManager control also supports features such as partial page rendering and Web service calls.
<asp:ScriptManager runat="server" ID="ScriptManager1" />


The preceding code shows how to insert the script manager in an ASP.NET page. The control produces no user interface, works exclusively on the server, and doesn’t add extra bytes to the page download.

Script Loading

By extensively relying on client capabilities, ASP.NET AJAX requires a lot of script code. The framework itself links a lot of code, as do custom controls and actual user pages. It turns out that registering and loading script and resources-such as hidden fields, styles, and arrays-is a key factor. The ScriptManager control manages resources created to be used by all controls participating in partial page updates.
You add script files using the Scripts collection, either declaratively or programmatically.


Adding Script Resources The ScriptManager control automatically emits in the client page any ASP.NET AJAX required script. As a page developer, you don’t have to worry about the script code necessary to support JavaScript extensions, the UpdatePanel, or perhaps the Timer control. In addition, you have the Scripts collection available as a tool to register optional and custom scripts. The Scripts collection can be populated programmatically or declaratively through the


<asp:ScriptReference> element.

The following example illustrates the script loading model you can use to load optional scripts:

<asp:ScriptManager runat="server" ID="ScriptManager1">
  <Scripts>
    <asp:ScriptReference
         Name="Microsoft.Web.Resources.ScriptLibrary.PreviewGlitz.js"
         Assembly="Microsoft.Web.Preview" />
    <asp:ScriptReference
         Path="~/Scripts/MyLib.js" />
  </Scripts>
</asp:ScriptManager> 


You can reference scripts from an in-memory assembly or from a disk file. The second option is faster, as no extra effort is required to extract scripts from the assembly’s resources.

The ScriptManagerProxy Control:
Only one instance of the ScriptManager control can be added to an ASP.NET AJAX page. However, there are two ways in which you can do this. You can add it directly on the page using the tag or indirectly by importing a component that already contains a script manager. Typically, you can accomplish the second alternative by importing a user control, creating a content page for a master page, or authoring a nested master page.
What if a content page needs to add a new script reference to the manager? In this case, you need a reference to the script manager. Although it’s defined in the master page (or in a user control), the script manager might not be publicly exposed to the content page. You can use the static method GetCurrent on the class ScriptManager to get the right instance: // Retrieve the instance of the ScriptManager active on the page
sm = ScriptManager.GetCurrent(this.Page);

The ScriptManagerProxy class saves you from this sort of coding. In general, in cases where you need features of the ScriptManager control but lack a direct reference to it, you can instead include a ScriptManagerProxy control in the content page.
You can’t have two script managers in the context of the same page; however, you can have a script manager and a proxy to retrieve it. The ScriptManagerProxy control enables you to add scripts and services to nested components, and it enables partial page updates in user controls and nested master pages. When you use the proxy, the Scripts and Services collections on the ScriptManager and ScriptManagerProxy controls are merged at runtime.

Auto Complete Textbox using ASP.NET Ajax Control ToolKit

2011-08-15

1. Add asp.net ajax control tool kit to the web project
2. Register the ajax in the page
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajax" %>
3. Add tab in visual studio for control tool kits
4. Drag the ToolkitScriptManager to the page.
5. Create an extender control for the textbox
i.e
<asp:TextBox ID="txtCustomerEmailID" runat="server"></asp:TextBox>



<ajax:AutoCompleteExtender ID="txtCustomerEmailID_AutoCompleteExtender"

runat="server"

TargetControlID="txtCustomerEmailID"

MinimumPrefixLength="1"

EnableCaching="true"

CompletionSetCount="1"

CompletionInterval="1000"

ServiceMethod="GetCustomerEmailIDSList"

>

</ajax:AutoCompleteExtender>


TargetControlID - The TextBox control where the user types content to be automatically completed.

EnableCaching- Caching is turned on, so typing the same prefix multiple times results in only one call to the web service.

MinimumPrefixLength- Minimum number of characters that must be entered before getting suggestions from the web service.

CompletionInterval - Time in milliseconds when the timer will kick in to get suggestions using the web service.

CompletionSetCount - Number of suggestions to be retrieved from the web service.

5. Create a webservice method in the page
i.e

<System.Web.Services.WebMethodAttribute(), System.Web.Script.Services.ScriptMethodAttribute()>

  Public Shared Function GetCustomerEmailIDSList(ByVal prefixText As String) As List(Of String)

      Dim ObjPMSRequestDTO As ClsPMSRequestDTO = New ClsPMSRequestDTO()

      Dim ObjPMSFacade As IAbstractPMSFacade = New PMSFacade()

      Dim lstCustomerCustomersEmailIDS As List(Of String) = New List(Of String)

      ObjPMSRequestDTO.Request = CType(HttpContext.Current.Session("SessionHandlerComponent"),



ClsSessionHandlerComponent).Request.Clone()

      ObjPMSRequestDTO.CustomerEmailID = prefixText

      lstCustomerCustomersEmailIDS = ObjPMSFacade.ProcessGetAllCustomersEmailID(ObjPMSRequestDTO)

      Return lstCustomerCustomersEmailIDS



  End Function