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

Wednesday, January 6, 2010

AJAX for ASP.NET

The most remarkable feature of microsoft development products is that they make things that lets the programmner concentrate more on the problem rather than on how to implement its solution technological wise. The best example of it is the AJAX library provided by microsoft in visual studio 2008. It has a complete set of in-built scripts and related classes that would implement the hard core logics of AJAX. Inspite of all this it is very simple and easy to implement it ! It consists of the following controls:

1. Script Manager
2. Script Manager Proxy
3. Timer
4. Update Panel
5. Update Progress

I will discuss these in details one by one:

1. Script Manager

The ScriptManager control is central to AJAX functionality in ASP.NET. The control manages all ASP.NET AJAX resources on a page. This includes downloading Microsoft AJAX Library scripts to the browser and coordinating partial-page updates that are enabled by using UpdatePanel controls. In addition, the ScriptManager control enables you to do the following:

* Register script that is compatible with partial-page updates. In order to manage dependencies between your script and the core library, any script that you register is loaded after the Microsoft AJAX Library script.

* Specify whether release or debug scripts are sent to the browser.

* Provide access to Web service methods from script by registering Web services with the ScriptManager control.

* Provide access to ASP.NET authentication, role, and profile application services from client script by registering these services with the ScriptManager control.

* Enable culture-specific display of ECMAScript (JavaScript) Date, Number, and String functions in the browser.

* Access localization resources for embedded script files or for stand-alone script files by using the ResourceUICultures property of the ScriptReference control.

* Register server controls that implement the IExtenderControl or IScriptControl interfaces with the ScriptManager control so that script required by client components and behaviors is rendered.

When implementing Script Manager one has to remember that it should be placed before any control in the web-page. Further Using the ScriptManager Control with Master Pages, User Controls, and Other Child Components one has to remember that a page can contain only one ScriptManager control in its hierarchy. To register services and scripts for nested pages, user controls, or components when the parent page already has a ScriptManager control, use the ScriptManagerProxy control.

Microsoft also gives us the liberty of making our own scripts and using them via the script manager thus enabling to make our own library of scripts that suit our requirements.


2. Script Manager Proxy

Only one instance of the ScriptManager control can be added to the page. The page can include the control directly, or indirectly inside a nested component such as a user control, content page for a master page, or nested master page. In cases where a ScriptManager control is already on the page but a nested or parent component needs additional features of the ScriptManager control, the component can include a ScriptManagerProxy control. For example, the ScriptManagerProxy control enables you to add scripts and services that are specific to nested components.


3. Timer

This is the control with with most of the window programmers would be fimiliar. By implementing this in the webpage we can generate a request to the server from the client at specific time intervals which in turn would update he webpage from time to time. It updates anything that is present within the update panel.


4. Update Panel

It is a container that contains the controls on which the AJAX is to be implemented. All the controls within the update panel would be updated via AJAX implementation while the others would be done through post-back.

5. Update Progress

Many a times it is seen that even update panel takes a fraction of time to complete the request and response cycle. For that time being the end user does not know if updation operation is going on. To solve this we can use the Update progress control. In this we specify the template ,which can be any text or image, which will be shown whenever the update panel is fetching fresh values i.e. its in its request response cycle.

Example

Example for the above mentioned topics is as follows:

I have made a page where script manager control, update panel control, update progress control and timer control is used. The page consists of a textbox and a button. Whatever you write in the textbox, on clicking the button you get the length of the text entered. Now to simulate some processing on the server i have made a couple of nested loops that would execute for 3-4 seconds. This would fire the update progress control. Further there is a timer that would go to the server and bring the date-time stamp every 5 seconds. The screen shots of the coding is as follows:
















The code behind is as follows:

















The screen shots of the UI on execution will be as follows:

1. When the application is run we see the following in the webpage:





















2. When the timer control fires automatically after 5 seconds





















3. When we write a text in the texbox and click the Calculate button... the request goes to the server and update progress control is shown.

4.After the processing at the server is complete the length of the text entered is shown.



Hence we see how easily we can implement the AJAX controls in ASP.NET.

Thursday, December 31, 2009

AJAX - The Classical way

AJAX is an acronym that stands for Asynchronous JavaScript and XML. AJAX gains its popularity by allowing data on a page to be dynamically updated without having to make the browser reload the page. I will describe more about how AJAX works, and then go into some sample code to try out.

This term has been made famous by some of Google's latest web apps. At the top of this list is Google Suggest, which gives you suggestions (go figure) on what you are searching for as you type based on popularity of the search term. If you aren't familiar with Google Suggest, check it out.

Microsoft too started its own R&D in this area. In its early development stages, ASP.NET AJAX was given the code name Atlas. Initial releases were made public to the development community in the form of CTPs (Community Technical Previews). The production version, ASP.NET AJAX 1.0 RTM; was released on January 23, 2007. as an extension to ASP.NET 2.0.

Important release milestones for ASP.NET AJAX are as follows:
CTPs - October, December 2005, January, March, April, June, July 2006
Beta - October, November 2006
Release Candidate (RC) - December 2006
ASP.NET AJAX 1.0 RTM - January 23, 2007
ASP.NET AJAX 3.5 - November 19, 2007 (as part of ASP.NET 3.5)

The next version, ASP.NET AJAX 4.0; will be part of the ASP.NET 4.0 framework release which will be available from around Feb 2010. ASP.NET AJAX runs on the following browsers:
Microsoft Internet Explorer (>= 6.0)
Mozilla Firefox (>= 1.5)
Opera (>= 9.0)
Apple Safari (>= 2.0)
Google Chrome

At present, the ASP.NET AJAX suite consists of the following components and packages:
Microsoft Ajax Library 3.5, which is a JavaScript library that provides the client-side features of the ASP.NET AJAX framework. Integrated in ASP.NET 3.5, the library is also available as a separate download for use in other environments, such as PHP.
A server framework – included in ASP.NET 3.5 – for building Ajax-enabled ASP.NET server controls. These components are also available for ASP.NET 2.0 in a separate package called ASP.NET 1.0 Extensions.
ASP.NET 2.0 AJAX Templates, a package with a set of Visual Studio templates for building ASP.NET AJAX applications with ASP.NET 2.0 and Visual Studio 2008.
ASP.NET AJAX Preview, a package with the new features that will be part of the future versions of the framework.

The Classic Way
---------------

There is more going on here than just AJAX however. The actual drop down list is an additional DHTML piece that we will not be covering in this article.

Is AJAX a new technology? Yes and no would both be incorrect answers. A proper answer would be a new application of current technologies, with emphasis on plurality. This list of technologies includes standard HTML controls, JavaScript, an XML HTTP component, and XML data structures.

The Steps
---------

The following is an outline of the sequence of events when using AJAX:
Web page is rendered
A trigger executes a JavaScript function call (i.e. onKeyUp, button click, setTimeout, page load, etc.)
JavaScript instantiates an XML HTTP object
XML HTTP object calls a remote page
Remote Page transforms an XML structure using XSLT and returns the result
JavaScript accepts the results and applies it to the page
Tada! No page reload, just magical dynamic data

Get To It Already!
------------------

These steps are great, but without a sample application it is tough to envision. Being the responsible author that I am, I have of course included a sample of the steps discussed.

I think that it is important to discuss the XML HTTP object to gain a better understanding of what is going on here. XML HTTP allows code to connect to a remote location and perform GET and POST requests asynchronously. This means that we can connect to a remote host, send a request, and continue on with additional logic. When the remote host returns a response, a function designated to handle the return event is able to accept the data and make decisions based on what was received. The data passed to and from the remote host does not have to be in an XML format. XML is simply a well-formatted string. I have found on multiple occassions that passing a string that is not in an XML format is most appropriate for the given task. The XML HTTP object will not be compatible on all browsers or operating systems. Being that this is a client side function the client machine is responsible for the implementation as opposed to the server.

I have been utilizing this object since ASP 3.0 for making remote calls from a web page. Imagine the power here. Data and processes are accessed on disparate locations without the client ever having to leave the comfort of the domain or page that he/she is on.

The JavaScript
--------------

The JavaScript is the real meat and potatoes in AJAX. It handles the change detection, data request and receipt, and placing the data on the page.

Be sure to update the requestURL variable with the path that you will be accessing the aspx file from.

The following is the JavaScript code used:

<-script>
var xmlHttp;
var requestURL = 'http://localhost/misctest/getusernames.aspx?q=';
var is_ie = (navigator.userAgent.indexOf('MSIE') >= 0) ? 1 : 0;
var is_ie5 = (navigator.appVersion.indexOf("MSIE 5.5")!=-1) ? 1 : 0;
var is_opera = ((navigator.userAgent.indexOf("Opera6")!=-1)||(navigator.userAgent.indexOf("Opera/6")!=-1)) ? 1 : 0;
//netscape, safari, mozilla behave the same???
var is_netscape = (navigator.userAgent.indexOf('Netscape') >= 0) ? 1 : 0;

function show_data(strName){
if (strName.length > 0){
//Append the name to search for to the requestURL
var url = requestURL + strName;

//Create the xmlHttp object to use in the request
//stateChangeHandler will fire when the state has changed, i.e. data is received back
// This is non-blocking (asynchronous)
xmlHttp = GetXmlHttpObject(stateChangeHandler);

//Send the xmlHttp get to the specified url
xmlHttp_Get(xmlHttp, url);
}
else {
//Textbox blanked out, clear the results
document.getElementById('nameList').innerHTML = '';
}
}

//stateChangeHandler will fire when the state has changed, i.e. data is received back
// This is non-blocking (asynchronous)
function stateChangeHandler()
{
//readyState of 4 or 'complete' represents that data has been returned
if (xmlHttp.readyState == 4 || xmlHttp.readyState == 'complete'){
//Gather the results from the callback
var str = xmlHttp.responseText;

//Populate the innerHTML of the div with the results
document.getElementById('nameList').innerHTML = str;
}
}

// XMLHttp send GET request
function xmlHttp_Get(xmlhttp, url) {
xmlhttp.open('GET', url, true);
xmlhttp.send(null);
}

function GetXmlHttpObject(handler) {
var objXmlHttp = null; //Holds the local xmlHTTP object instance

//Depending on the browser, try to create the xmlHttp object
if (is_ie){
//The object to create depends on version of IE
//If it isn't ie5, then default to the Msxml2.XMLHTTP object
var strObjName = (is_ie5) ? 'Microsoft.XMLHTTP' : 'Msxml2.XMLHTTP';

//Attempt to create the object
try{
objXmlHttp = new ActiveXObject(strObjName);
objXmlHttp.onreadystatechange = handler;
}
catch(e){
//Object creation errored
alert('IE detected, but object could not be created. Verify that active scripting and activeX controls are enabled');
return;
}
}
else if (is_opera){
//Opera has some issues with xmlHttp object functionality
alert('Opera detected. The page may not behave as expected.');
return;
}
else{
// Mozilla | Netscape | Safari
objXmlHttp = new XMLHttpRequest();
objXmlHttp.onload = handler;
objXmlHttp.onerror = handler;
}

//Return the instantiated object
return objXmlHttp;
}

function UseValue(strVal){
document.frmStuff.txtName.value = strVal;
}
<-/script>

The Client Page (HTML)
----------------------

The client page, excluding the JavaScript, is about as basic as it gets. A simple form with an onKeyUp event in a text box is all that is really required. I included a DIV tag to display the resulting data. The HTML has been provided:

<-html>
<-head>
<-title>Ian Suttle's AJAX Sample<-/title>
<-style>
body, input {font-family: arial; font-size: 12px;}
<-/style>

// Insert JavaScript Here

<-/head>
<-body>
<-form name="frmStuff" id="Form1">
<-table border="0" cellpadding="4" cellspacing="0" id="Table2">
<-tr>
<-td width="100">Name:<-/td>
<-td><-input type="text" name="txtName" id="txtName" autocomplete="off" onkeyup="show_data(this.value);"><-/td>




<-tr>
<-td width="100" valign="top">Suggestions:<-/td>
<-td>
<-div id="nameList"><-/div>
<-/td>
<-/tr>
<-/table>
<-/form>
<-/body>
<-/html>

The Remote Page
---------------

When a request is made from the JavaScript, it makes contact with the "remote page." A query string variable, "q", is included representing the data that was keyed by the user. I am going to construct an XML string, only including those elements that are valid based on the search term. To relieve the client side script from doing any formatting, I have applied an XSL transformation on the XML data. Formatting the XML on the server side is a much better solution than formatting within the JavaScript on the client side. A major point to recognize is that certain browsers will not support XML and XSL objects. Assuming you want your data to always be formatted the same, stick with the server side logic.

Create a page called GetUsernames.aspx. Be sure to remove ALL HTML from the page except the required @Page line. The code-behind will create the output to display on the page. Add the following code to the code-behind file:

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Xml;
using System.Xml.Xsl;
using System.Xml.XPath;

namespace MiscTest
{
///
/// Summary description for GetUsernames.
///

public class GetUsernames : System.Web.UI.Page
{
private void Page_Load(object sender, System.EventArgs e)
{
GetUsernameList();
}

#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Form Designer.
//
InitializeComponent();
base.OnInit(e);
}

///
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
///

private void InitializeComponent()
{
this.Load += new System.EventHandler(this.Page_Load);
}
#endregion

private void GetUsernameList()
{
//Get the request query
string strQuery = Request["q"].ToString();

//Create the XML-like string to be sent back to the request
string strXmlNames = "";

//An arbitrary array of names that will be written to an XML Document.
string[] arrStrNames = new string[5]{"Ian Suttle", "John Doe", "Alex Wright", "Albert Einstein", "Sierra Tracy"};

//Loop through the names, creating a psuedo XML element for each
foreach(string strName in arrStrNames)
{
//If the request matches the beginning of a name, then add it to the string
// otherwise it shouldn't be a valid match
if (strName.ToLower().Substring(0, strQuery.Length) == strQuery.ToLower())
strXmlNames += "" + strName + "";
}

//Prepend and append the parent element
strXmlNames = "" + strXmlNames + "";

//Create an XmlDocument object to store the XML string that we created
XmlDocument xDoc = new XmlDocument();
xDoc.LoadXml(strXmlNames);

//Create a navigator object to use in the XSL transformation
XPathNavigator xPathNav = xDoc.CreateNavigator();

//Create the XSLTransform object
XslTransform xslt = new XslTransform();
xslt.Load(Server.MapPath("Names.xslt"));

//Do the transformation and send the results out to the Response object's output stream
xslt.Transform(xPathNav, null, Response.OutputStream);
}
}
}

The XSL Stylesheet
------------------

The XSL document is used to format the XML data to a defined presentation. The code to do the transformation is included here, although great detail on how this works is not the topic of this article. Create a new XSL document called Names.xslt and paste the following code into it:

<-?xml version="1.0" encoding="UTF-8" ?>
<-xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<-xsl:template match="/">
<-xsl:for-each select="users/user">
<-xsl:value-of select="name" />

<-/xsl:for-each>
<-/xsl:template>
<-/xsl:stylesheet>

Conclusion
----------

So once again, AJAX is nothing more than an application of technologies that have been around for a number of years. ASP.NET isn't the wizard behind this curtain. There is nothing here that can't be done in ASP Classic and JavaScript. Not that given a choice one would revert to ASP Classic :). Additionally, ASP.NET will have a completely different approach to making remote calls from a page.

The possible implications of AJAX are very impressive. Updating notices, checking email, monitoring processes, etc... The limits of application are virtually up to the imagination of the developer.

LinkWithin

Related Posts with Thumbnails